diff --git a/.cliffignore b/.cliffignore new file mode 100644 index 000000000..187668fd1 --- /dev/null +++ b/.cliffignore @@ -0,0 +1,7 @@ +9766c534bddad8e82e6d19f9bad5cf70b9887f9a +92ce77ec0ec703c08a659419087a373f76e711f7 +2d53efc945c7747be1755d0b66557a86bdc12cbd +602137b65129b817811b80975a369ebde3270c6d +4eb26ae37e1f4c82a45961517ffeb54c20200408 +e59adce848a9e10ee5775254045cbbd915236b8b +9e0a64108d62236ab07b3f8d10e8c78269b8e1d1 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..ddde48ba4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org + +root = true + +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 2 + +[*.{diff,md}] +trim_trailing_whitespace = false + +[*.{php,tpl}] +indent_size = 4 diff --git a/.env.example b/.env.example new file mode 100644 index 000000000..c0776eda9 --- /dev/null +++ b/.env.example @@ -0,0 +1,13 @@ +# Common params +TP_HOST=example.com +TP_PORT=80 +APP_ENV=production +APP_CRON_ENABLED=true +APP_DEMO_MODE=false + +# Database credentials +DB_HOST=localhost +DB_PORT=3306 +DB_DATABASE=torrentpier +DB_USERNAME=root +DB_PASSWORD=secret diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..0baf955a6 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +github: torrentpier +open_collective: torrentpier diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..c3a7bf266 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,62 @@ +name: Bug Report +description: File a bug report +title: "[Bug]" +labels: [Bug] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + The more detailed this bug report is, the faster it can be reviewed and fixed. + - type: input + id: version-torrentpier + attributes: + label: TorrentPier Version + description: TorrentPier version your using? + placeholder: 2.4.0 + validations: + required: true + - type: input + id: version-php-os + attributes: + label: PHP & Platform + description: Exact PHP and Platform (OS) versions your using. + placeholder: 8.2.2 - Ubuntu 22.04 x64 + validations: + required: true + - type: checkboxes + id: requirements + attributes: + label: Have you done this? + options: + - label: I am willing to share my stack trace and logs + required: true + - label: I can suggest a fix as a Pull Request + required: false + - type: textarea + id: expectation + attributes: + label: Expectation + description: Write what you expect to (correctly) happen. + placeholder: When I do this, I expect to this to happen. + validations: + required: true + - type: textarea + id: description + attributes: + label: Description + description: Write what (incorrectly) happens instead. + placeholder: Instead, when I do this, I receive that. + validations: + required: true + - type: textarea + id: logs + attributes: + label: Stack trace & logs + description: | + If you have a stack trace, you can copy it here. You may hide sensitive information. + Including a stack trace when reporting an error 500 is required. + placeholder: This is automatically formatted into code, no need for backticks. + render: shell + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/feature---enhancement-request.md b/.github/ISSUE_TEMPLATE/feature---enhancement-request.md new file mode 100644 index 000000000..9f68fc3a6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature---enhancement-request.md @@ -0,0 +1,7 @@ +--- +name: Feature / Enhancement request +about: Suggest an idea for TorrentPier +title: "[Feature]" +labels: [Feature, Enhancement] +assignees: '' +--- diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..28f94a001 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 + +updates: + - package-ecosystem: "composer" + directory: "/" + versioning-strategy: increase-if-necessary + commit-message: + prefix: "Composer" + include: "scope" + schedule: + interval: "daily" diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 000000000..f257360c6 --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,80 @@ +name: Continuous Deployment + +on: + push: + tags: + - "v*.*.*" + +jobs: + generate-changelog: + name: Generate changelog + runs-on: ubuntu-22.04 + outputs: + release_body: ${{ steps.git-cliff.outputs.content }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Generate a changelog + uses: orhun/git-cliff-action@v4 + id: git-cliff + with: + config: cliff.toml + args: -vv --latest --no-exec --github-repo ${{ github.repository }} + + - name: Print the changelog + run: cat "${{ steps.git-cliff.outputs.changelog }}" + + release: + name: Create release + needs: [ generate-changelog ] + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v4 + - name: Set the release version + shell: bash + run: echo "RELEASE_VERSION=${GITHUB_REF:11}" >> $GITHUB_ENV + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + + - name: Install Composer dependencies + run: composer install --no-dev --no-progress --prefer-dist --optimize-autoloader + + - name: Cleanup + run: php _cleanup.php && rm _cleanup.php + + - name: Create archive + id: create-zip + run: | + ZIP_NAME="torrentpier-v${{ env.RELEASE_VERSION }}.zip" + zip -r "$ZIP_NAME" . -x ".git/*" + echo "ZIP_NAME=$ZIP_NAME" >> $GITHUB_OUTPUT + + - name: Publish to GitHub + if: ${{ !contains(github.ref, '-') }} + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: ${{ steps.create-zip.outputs.ZIP_NAME }} + overwrite: true + tag: ${{ github.ref }} + release_name: "v${{ env.RELEASE_VERSION }}" + body: "${{ needs.generate-changelog.outputs.release_body }}" + + - name: Publish to GitHub (pre-release) + if: ${{ contains(github.ref, '-') }} + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: ${{ steps.create-zip.outputs.ZIP_NAME }} + overwrite: true + tag: ${{ github.ref }} + release_name: "v${{ env.RELEASE_VERSION }}" + body: "${{ needs.generate-changelog.outputs.release_body }}" + prerelease: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..d4fd0b722 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,45 @@ +name: Continuous Integration + +on: + push: + branches: + - master + +jobs: + nightly: + name: Nightly builds 📦 + runs-on: ubuntu-22.04 + + steps: + - name: Checkout code 🗳 + uses: actions/checkout@v4 + + - name: Setup PHP 🔩 + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + + - name: Install Composer dependencies 🪚 + run: composer install --no-dev --no-progress --prefer-dist --optimize-autoloader + + - name: Get commit hash 🔗 + id: get-commit-hash + run: | + COMMIT_HASH=$(git rev-parse --short HEAD) + echo "COMMIT_HASH=$COMMIT_HASH" >> $GITHUB_OUTPUT + + - name: Cleanup + run: php _cleanup.php && rm _cleanup.php + + - name: Create archive 🗞 + id: create-zip + run: | + ZIP_NAME="torrentpier-${{ steps.get-commit-hash.outputs.COMMIT_HASH }}.zip" + zip -r "$ZIP_NAME" . -x ".git/*" + echo "ZIP_NAME=$ZIP_NAME" >> $GITHUB_OUTPUT + + - name: Upload Archive 📤 + uses: actions/upload-artifact@v4 + with: + name: TorrentPier-master + path: ${{ steps.create-zip.outputs.ZIP_NAME }} diff --git a/.github/workflows/phpmd.yml b/.github/workflows/phpmd.yml new file mode 100644 index 000000000..3e06d7538 --- /dev/null +++ b/.github/workflows/phpmd.yml @@ -0,0 +1,57 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# PHPMD is a spin-off project of PHP Depend and +# aims to be a PHP equivalent of the well known Java tool PMD. +# What PHPMD does is: It takes a given PHP source code base +# and look for several potential problems within that source. +# These problems can be things like: +# Possible bugs +# Suboptimal code +# Overcomplicated expressions +# Unused parameters, methods, properties +# More details at https://phpmd.org/ + +name: PHPMD + +on: + push: + branches: [ "master" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "master" ] + schedule: + - cron: '40 0 * * 3' + +permissions: + contents: read + +jobs: + PHPMD: + name: Run PHPMD scanning + runs-on: ubuntu-latest + permissions: + contents: read # for checkout to fetch code + security-events: write # for github/codeql-action/upload-sarif to upload SARIF results + actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@aa1fe473f9c687b6fb896056d771232c0bc41161 + with: + coverage: none + tools: phpmd + + - name: Run PHPMD + run: phpmd . sarif codesize --reportfile phpmd-results.sarif + continue-on-error: true + + - name: Upload analysis results to GitHub + uses: github/codeql-action/upload-sarif@v2 + with: + sarif_file: phpmd-results.sarif + wait-for-processing: true diff --git a/.github/workflows/schedule.yml b/.github/workflows/schedule.yml new file mode 100644 index 000000000..c1ad4f3c1 --- /dev/null +++ b/.github/workflows/schedule.yml @@ -0,0 +1,41 @@ +name: Changelog generation + +on: + schedule: + - cron: '0 0 * * *' + workflow_dispatch: + +jobs: + changelog: + name: Changelog generation + runs-on: ubuntu-22.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: master + token: ${{ secrets.REPO_TOKEN }} + + - name: Generate a changelog + uses: orhun/git-cliff-action@v4 + id: git-cliff + with: + config: cliff.toml + args: v2.4.6-alpha.4.. --verbose + env: + OUTPUT: CHANGELOG.md + GITHUB_REPO: ${{ github.repository }} + + - name: Print the changelog + run: cat "${{ steps.git-cliff.outputs.changelog }}" + + - name: Commit changelog + run: | + git checkout master + git config --local user.name 'belomaxorka' + git config --local user.email 'roman25052006.kelesh@gmail.com' + set +e + git add CHANGELOG.md + git commit -m "changelog: Update CHANGELOG.md 📖" + git push https://${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git master diff --git a/.gitignore b/.gitignore index d430f2cc7..dd0e1f365 100644 --- a/.gitignore +++ b/.gitignore @@ -1,30 +1,40 @@ +### IDE ### +.idea +.vscode + ### TorrentPier ### -.idea/ -data/avatars/**/ -data/old_files/ -data/torrent_files/ -internal_data/ajax_html/*.html -internal_data/atom/ -internal_data/cache/ -internal_data/captcha/**/ -internal_data/log/ -internal_data/sitemap/*.xml -internal_data/triggers/ +*.log +install.php_* +composer-setup.php +.env +.php_cs.cache +data/avatars +data/uploads +internal_data/atom +internal_data/cache +internal_data/log +internal_data/updater.json +sitemap +internal_data/triggers library/config.local.php +vendor ### Archives ### -*.log -*.zip +*.phar *.rar *.tar *.gz +*.zip +*.7z *.torrent +*.pak ### Windows ### Thumbs.db Desktop.ini $RECYCLE.BIN/ *.lnk +*.bat ### OSX ### .DS_Store @@ -32,4 +42,6 @@ $RECYCLE.BIN/ .LSOverride ._* .Spotlight-V100 -.Trashes \ No newline at end of file +.Trashes +*.orig +*.rej diff --git a/.htaccess b/.htaccess index 8298e9bdd..a689fba84 100644 --- a/.htaccess +++ b/.htaccess @@ -6,13 +6,13 @@ Options All -Indexes ## sitemap and atom rewrite RewriteEngine On -RewriteRule ^sitemap.xml$ internal_data/sitemap/sitemap.xml [L] +RewriteRule ^sitemap.xml$ sitemap/sitemap.xml [L] RewriteRule ^/internal_data/atom/(.*) /atom$1 [L] ## deny access to git folder RedirectMatch 404 /\\.git(/|$) ## deny access to system files - -deny from all - \ No newline at end of file + +Require all denied + diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 000000000..64c6be3ca --- /dev/null +++ b/.styleci.yml @@ -0,0 +1,10 @@ +preset: psr2 + +finder: + name: + - "*.php" + not-name: + - "*Stub.php" + path: + - "src" + - "tests" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..deebe3d07 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,113 @@ +[![TorrentPier](https://raw.githubusercontent.com/torrentpier/.github/refs/heads/main/versions/Cattle.png)](https://github.com/torrentpier) + +# 📖 Change Log + +## [v2.8.3](https://github.com/torrentpier/torrentpier/compare/v2.8.2..v2.8.3) (2025-07-03) + +### 🚀 Features + +- *(lang)* Added `RTL` languages support ([#2031](https://github.com/torrentpier/torrentpier/pull/2031)) - ([fd46d3d](https://github.com/torrentpier/torrentpier/commit/fd46d3d04ad3ab1453256b2ab620508e2ba33586)) +- *(updater)* Added exceptions logging ([#2026](https://github.com/torrentpier/torrentpier/pull/2026)) - ([51f2c70](https://github.com/torrentpier/torrentpier/commit/51f2c70d81b910012cdecd111b5b92c1dfd0d6f6)) + +### 🚜 Refactor + +- *(TorrentFileList)* Reduce duplication in root directory unset logic ([#2027](https://github.com/torrentpier/torrentpier/pull/2027)) - ([d4d8210](https://github.com/torrentpier/torrentpier/commit/d4d82101dd67c9f4cd86e0f6f909495696974354)) + + +## [v2.8.2](https://github.com/torrentpier/torrentpier/compare/v2.8.1..v2.8.2) (2025-06-30) + +### 🐛 Bug Fixes + +- *(TorrentFileList)* Avoid `array_merge` reindexing for numeric folder names ([#2014](https://github.com/torrentpier/torrentpier/pull/2014)) - ([915e1d8](https://github.com/torrentpier/torrentpier/commit/915e1d817c61d2a4f0691b24ec1bc6577a9cd44b)) + +### 🚜 Refactor + +- Use `DEFAULT_CHARSET` constant instead of hardcoded string ([#2011](https://github.com/torrentpier/torrentpier/pull/2011)) - ([7ac3359](https://github.com/torrentpier/torrentpier/commit/7ac335974baa44a8575bebb71ae2fbc0902d10e7)) + + +## [v2.8.1](https://github.com/torrentpier/torrentpier/compare/v2.8.0..v2.8.1) (2025-06-24) + +### 🐛 Bug Fixes + +- *(filelist)* `Undefined property: FileTree::$length` when v2 torrent only ([#2004](https://github.com/torrentpier/torrentpier/pull/2004)) - ([7f4cc9d](https://github.com/torrentpier/torrentpier/commit/7f4cc9d3b9a5b87100f710cc60f636d6e7d5a34e)) +- *(ip-api)* Add error handling and logging for freeipapi.com requests ([#2006](https://github.com/torrentpier/torrentpier/pull/2006)) - ([f1d6e74](https://github.com/torrentpier/torrentpier/commit/f1d6e74e5d4c74b6e12e9e742f60f62e71783d11)) + + +## [v2.8.0](https://github.com/torrentpier/torrentpier/compare/v2.7.0..v2.8.0) (2025-06-21) + +### 🐛 Bug Fixes + +- *(template)* Handle L_ variables in template vars when not found in lang vars ([#1998](https://github.com/torrentpier/torrentpier/pull/1998)) - ([c6076c2](https://github.com/torrentpier/torrentpier/commit/c6076c2c278e9a423f3862670236b75bddeadd87)) + + +## [v2.7.0](https://github.com/torrentpier/torrentpier/compare/v2.6.0..v2.7.0) (2025-06-21) + +### 🚀 Features + +- *(database)* Add visual markers for Nette Explorer queries in debug panel ([#1965](https://github.com/torrentpier/torrentpier/pull/1965)) - ([2fd3067](https://github.com/torrentpier/torrentpier/commit/2fd306704f21febee7d53f4b4531601ce0cb81ce)) +- *(language)* Add new language variable for migration file and enhance template fallback logic ([#1984](https://github.com/torrentpier/torrentpier/pull/1984)) - ([a33574c](https://github.com/torrentpier/torrentpier/commit/a33574c28f2eb6267a74fa6c9d97fea86527157a)) +- *(migrations)* Implement Phinx database migration system ([#1976](https://github.com/torrentpier/torrentpier/pull/1976)) - ([fbde8cd](https://github.com/torrentpier/torrentpier/commit/fbde8cd421c9048afe70ddb41d0a9ed26d3fbef5)) +- *(test)* [**breaking**] Add comprehensive testing infrastructure with Pest PHP ([#1979](https://github.com/torrentpier/torrentpier/pull/1979)) - ([cc9d412](https://github.com/torrentpier/torrentpier/commit/cc9d412522938a023bd2b8eb880c4d2dd307c82a)) +- [**breaking**] Implement Language singleton with shorthand functions ([#1966](https://github.com/torrentpier/torrentpier/pull/1966)) - ([49717d3](https://github.com/torrentpier/torrentpier/commit/49717d3a687b95885fe9773f2597354aed4b2b60)) + +### 🐛 Bug Fixes + +- *(database)* Update affected rows tracking in Database class ([#1980](https://github.com/torrentpier/torrentpier/pull/1980)) - ([4f9cc9f](https://github.com/torrentpier/torrentpier/commit/4f9cc9fe0f7f4a85c90001a3f5514efdf04836da)) + +### 🚜 Refactor + +- *(database)* Enhance error logging and various fixes ([#1978](https://github.com/torrentpier/torrentpier/pull/1978)) - ([7aed6bc](https://github.com/torrentpier/torrentpier/commit/7aed6bc7d89f4ed31e7ed6c6eeecc6e08d348c24)) +- *(database)* Rename DB to Database and extract debug functionality ([#1964](https://github.com/torrentpier/torrentpier/pull/1964)) - ([6c0219d](https://github.com/torrentpier/torrentpier/commit/6c0219d53c7544b7d8a6374c0d0848945d32ae17)) +- *(stats)* Improve database row fetching in tr_stats.php ([#1985](https://github.com/torrentpier/torrentpier/pull/1985)) - ([728116d](https://github.com/torrentpier/torrentpier/commit/728116d6dc9cf4476cce572ced5e8a7ef529ead8)) + +### ⚙️ Miscellaneous + +- Update minimum `PHP` requirement to `8.2` ([#1987](https://github.com/torrentpier/torrentpier/pull/1987)) - ([9b322c7](https://github.com/torrentpier/torrentpier/commit/9b322c7093a634669e9f17a32ac42500f44f2496)) +- Removed useless `composer update` from workflows & installer ([#1986](https://github.com/torrentpier/torrentpier/pull/1986)) - ([423424e](https://github.com/torrentpier/torrentpier/commit/423424e9478e0772957014fb30f5e84158067af7)) +- Added --no-dev composer flag for some workflows ([#1982](https://github.com/torrentpier/torrentpier/pull/1982)) - ([e9a9e09](https://github.com/torrentpier/torrentpier/commit/e9a9e095768ba68aa5d5058a3e152ffaec916117)) +- Added `--no-dev` composer flag for some workflows ([#1981](https://github.com/torrentpier/torrentpier/pull/1981)) - ([e8cba5d](https://github.com/torrentpier/torrentpier/commit/e8cba5dd3fc83b616f83c24991f79dc7258c5df3)) + + +## [v2.6.0](https://github.com/torrentpier/torrentpier/compare/v2.5.0..v2.6.0) (2025-06-18) + +### 🚀 Features + +- [**breaking**] Implement unified cache system with Nette Caching ([#1963](https://github.com/torrentpier/torrentpier/pull/1963)) - ([07a06a3](https://github.com/torrentpier/torrentpier/commit/07a06a33cd97b37f68b533a87cdb5f7578f2c86f)) +- Replace legacy database layer with Nette Database implementation ([#1961](https://github.com/torrentpier/torrentpier/pull/1961)) - ([f50b914](https://github.com/torrentpier/torrentpier/commit/f50b914cc18f777d92002baf2c812a635d5eed4b)) + +### 🐛 Bug Fixes + +- *(User)* Add null and array checks before session data operations ([#1962](https://github.com/torrentpier/torrentpier/pull/1962)) - ([e458109](https://github.com/torrentpier/torrentpier/commit/e458109eefc54d86a78a1ddb3954581524852516)) + + +## [v2.5.0](https://github.com/torrentpier/torrentpier/compare/v2.4.6-alpha.4..v2.5.0) (2025-06-18) + +### 🚀 Features + +- [**breaking**] Implement centralized Config class to replace global $bb_cfg array ([#1953](https://github.com/torrentpier/torrentpier/pull/1953)) - ([bf9100f](https://github.com/torrentpier/torrentpier/commit/bf9100fbfa74768edb01c62636198a44739d9923)) + +### 🐛 Bug Fixes + +- *(installer)* Strip protocol from TP_HOST to keep only hostname ([#1952](https://github.com/torrentpier/torrentpier/pull/1952)) - ([81bf67c](https://github.com/torrentpier/torrentpier/commit/81bf67c2be85d49e988b7802ca7e9738ff580031)) +- *(sql)* Resolve only_full_group_by compatibility issues in tracker cleanup ([#1951](https://github.com/torrentpier/torrentpier/pull/1951)) - ([37a0675](https://github.com/torrentpier/torrentpier/commit/37a0675adfb02014e7068f4aa82301e29f39eab6)) + +### 📦 Dependencies + +- *(deps)* Bump filp/whoops from 2.18.2 to 2.18.3 ([#1948](https://github.com/torrentpier/torrentpier/pull/1948)) - ([b477680](https://github.com/torrentpier/torrentpier/commit/b4776804a408217229caa327c79849cf13ce2aa5)) + +### 🚜 Refactor + +- *(censor)* [**breaking**] Migrate Censor class to singleton pattern ([#1954](https://github.com/torrentpier/torrentpier/pull/1954)) - ([74a564d](https://github.com/torrentpier/torrentpier/commit/74a564d7954c6f8745ebcffdcd9c8997e371d47a)) +- *(config)* [**breaking**] Encapsulate global $bb_cfg array in Config class ([#1950](https://github.com/torrentpier/torrentpier/pull/1950)) - ([5842994](https://github.com/torrentpier/torrentpier/commit/5842994782dfa62788f8427c55045abdbfb5b8e9)) + +### 📚 Documentation + +- Add Select class migration guide ([#1960](https://github.com/torrentpier/torrentpier/pull/1960)) - ([86abafb](https://github.com/torrentpier/torrentpier/commit/86abafb11469d14a746d12725b15cf6b7015ec44)) + +### ⚙️ Miscellaneous + +- *(_release.php)* Finally! Removed some useless params ([#1947](https://github.com/torrentpier/torrentpier/pull/1947)) - ([9c7d270](https://github.com/torrentpier/torrentpier/commit/9c7d270598c0153fb82f4b7ad96f5b59399b2159)) +- *(cliff)* Add conventional commit prefix to changelog message ([#1957](https://github.com/torrentpier/torrentpier/pull/1957)) - ([b1b2618](https://github.com/torrentpier/torrentpier/commit/b1b26187579f6981165d85c316a3c5b7199ce2ee)) + + + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..68bd96ae8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,144 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +TorrentPier is a BitTorrent tracker engine written in PHP, designed for hosting BitTorrent communities with forum functionality. The project is in active modernization, transitioning from legacy code to modern PHP practices while maintaining backward compatibility. + +## Technology Stack & Architecture + +- **PHP 8.2+** with modern features +- **MySQL/MariaDB/Percona** database +- **Nette Database** with backward-compatible wrapper +- **Composer** for dependency management +- **Custom BitTorrent tracker** implementation + +## Key Directory Structure + +- `/src/` - Modern PHP classes (PSR-4 autoloaded as `TorrentPier\`) +- `/library/` - Core application logic and legacy code +- `/admin/` - Administrative interface +- `/bt/` - BitTorrent tracker functionality (announce.php, scrape.php) +- `/styles/` - Templates, CSS, JS, images +- `/internal_data/` - Cache, logs, compiled templates +- `/install/` - Installation scripts and configuration examples +- `/migrations/` - Database migration files (Phinx) + +## Entry Points & Key Files + +- `index.php` - Main forum homepage +- `tracker.php` - Torrent search/browse interface +- `bt/announce.php` - BitTorrent announce endpoint +- `bt/scrape.php` - BitTorrent scrape endpoint +- `admin/index.php` - Administrative panel +- `cron.php` - Background task runner (CLI only) +- `install.php` - Installation script (CLI only) + +## Development Commands + +### Installation & Setup +```bash +# Automated installation (CLI) +php install.php + +# Install dependencies +composer install + +# Update dependencies +composer update +``` + +### Maintenance & Operations +```bash +# Run background maintenance tasks +php cron.php +``` + +### Code Quality +The project uses **StyleCI** with PSR-2 preset for code style enforcement. StyleCI configuration is in `.styleci.yml` targeting `src/` directory. + +## Modern Architecture Components + +### Database Layer (`/src/Database/`) +- **Nette Database** with full old SqlDb backward compatibility +- Singleton pattern accessible via `DB()` function +- Support for multiple database connections and debug functionality +- Migration path to ORM-style Explorer queries + +### Cache System (`/src/Cache/`) +- **Unified caching** using Nette Caching internally +- 100% backward compatibility with existing `CACHE()` and $datastore calls +- Supports file, SQLite, memory, and Memcached storage +- Advanced features: memoization, cache dependencies + +### Configuration Management +- Environment-based config with `.env` files +- Singleton `Config` class accessible via `config()` function +- Local overrides supported via `library/config.local.php` + +## Configuration Files +- `.env` - Environment variables (copy from `.env.example`) +- `library/config.php` - Main application configuration +- `library/config.local.php` - Local configuration overrides +- `composer.json` - Dependencies and PSR-4 autoloading + +## Development Workflow + +### CI/CD Pipeline +- **GitHub Actions** for automated testing and deployment +- **StyleCI** for code style enforcement +- **Dependabot** for dependency updates +- **FTP deployment** to demo environment + +### Installation Methods +1. **Automated**: `php install.php` (recommended) +2. **Composer**: `composer create-project torrentpier/torrentpier` +3. **Manual**: Git clone + `composer install` + database setup + +## Database & Schema + +- **Database migrations** managed via Phinx in `/migrations/` directory +- Initial schema: `20250619000001_initial_schema.php` +- Initial seed data: `20250619000002_seed_initial_data.php` +- UTF-8 (utf8mb4) character set required +- Multiple database alias support for different components + +### Migration Commands +```bash +# Run all pending migrations +php vendor/bin/phinx migrate --configuration=phinx.php + +# Check migration status +php vendor/bin/phinx status --configuration=phinx.php + +# Mark migrations as applied (for existing installations) +php vendor/bin/phinx migrate --fake --configuration=phinx.php +``` + +## Legacy Compatibility Strategy + +The codebase maintains 100% backward compatibility while introducing modern alternatives: + +- **Database layer**: Existing old SqlDb calls work while new code can use Nette Database +- **Cache system**: All existing `CACHE()` and $datastore calls preserved while adding modern features +- **Configuration**: Legacy config access maintained alongside new singleton pattern + +This approach allows gradual modernization without breaking existing functionality - critical for a mature application with existing deployments. + +## Security & Performance + +- **Environment-based secrets** management via `.env` +- **CDN/proxy support** (Cloudflare, Fastly) +- **Input sanitization** and CSRF protection +- **Advanced caching** with multiple storage backends +- **Rate limiting** and IP-based restrictions + +## BitTorrent Tracker Features + +- **BitTorrent v1 & v2** support +- **TorrServer integration** capability +- **Client ban system** for problematic torrent clients +- **Scrape support** for tracker statistics + +When working with this codebase, prioritize understanding the legacy compatibility approach and modern architecture patterns. Always test both legacy and modern code paths when making changes to core systems. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..522445d96 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at admin@torrentpier.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..864d4b1d3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,93 @@ +# Contributing + +When contributing to this repository, please first discuss the change you wish to make via issue, +email, or any other method with the owners of this repository before making a change. + +Please note we have a code of conduct, please follow it in all your interactions with the project. + +## Pull Request Process + +1. Ensure any install or build dependencies are removed before the end of the layer when doing a + build. +2. Update the README.md with details of changes to the interface, this includes new environment + variables, exposed ports, useful file locations and container parameters. +3. Increase the version numbers in any examples files and the README.md to the new version that this + Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). +4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you + do not have permission to do that, you may request the second reviewer to merge it for you. + +## Code of Conduct + +### Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +### Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +### Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +### Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +### Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at admin@torrentpier.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +### Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org + +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md deleted file mode 100644 index 7c8c5d101..000000000 --- a/CONTRIBUTORS.md +++ /dev/null @@ -1,48 +0,0 @@ -Уважаемые пользователи TorrentPier II! - -За помощь, оказанную в развитии нашего движка, выражаем особую благодарность нижеперечисленным участникам форума: - -*************************** -** Сборы 2013 года ** -*************************** - -emilio13 -UralSOFT -aik -Sarymian -eve -Алексей Письменский -qaqra -rserg99 -leszav -Dr_Brown -Bullit -Triceratop (http://goldenshara.com/) -Ramzess - -**************************** -** Сборы 2014 года ** -**************************** - -SamSeGo -alesel (http://sporttracker.kz/) -Bullit -igorsaevets -vasilich619 -wint1000 (http://asmlocator.ru/) -Philstone (http://worldofminecraft.su/) -Nightwolf -nord51 -Вася -Alexander.S (http://torrent.dchub.ws/) -sasha20072007 -gerhanovn - -***************************** -** Прочая информация ** -***************************** - -Отдельная благодарность выражается компании JetBrains за предоставление лицензии на PhpStorm (http://www.jetbrains.com/phpstorm/). - -Если в данных списках кто-то не указан, либо если вы хотите указать дополнительно адрес своего трекера, отправьте письмо по адресу admin@torrentpier.me, -с указанием вашего ника на форуме и адреса вашего трекера, дабы мы могли вас добавить в этот список. \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..494696b2b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2005-2025 TorrentPier + +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 af7f6a07f..96b27a825 100644 --- a/README.md +++ b/README.md @@ -1,78 +1,191 @@ -TorrentPier II -====================== +

TorrentPier

-TorrentPier II - движок торрент-трекера, написанный на php. Высокая скорость работы, простота модификации, устойчивость к высоким нагрузкам, в том числе и поддержка альтернативных анонсеров (например, Ocelot). Помимо этого, крайне развитый официальный форум поддержки, где помимо прочего можно испытать движок в работе на демо-версии, не устанавливая его, а также получить любую другую интересующую вас информацию и скачать моды. +

+ Bull-powered BitTorrent tracker engine +
+

-## Установка +

+ License + Stars Packagist + Crowdin + TorrentPier nightly + Downloads + Version + Last release + Size + Deployed to TorrentPier Demo with FTP Deploy Action +

-Для установки вам необходимо выполнить несколько простых шагов: +## 🐂 About TorrentPier -1. Распаковываем на сервер содержимое скачанной вами папки +TorrentPier — bull-powered BitTorrent Public/Private tracker engine, written in PHP. High speed, simple modifications, load-balanced +architecture. In addition, we have a very helpful +[official support forum](https://torrentpier.com), where it's possible to get support and download modifications for the engine. -2. Создаем базу данных, в которую при помощи phpmyadmin (или любого другого удобного инструмента) импортируем дамп, расположенный в папке **install/sql/mysql.sql** -3. Правим файл конфигурации **library/config.php**, загруженный на сервер: -> ***'db1' => array('localhost', 'dbase', 'user', 'pass', $charset, $pconnect)*** -В данной строке изменяем данные входа в базу данных -***$domain_name = 'torrentpier.me';*** -В данной строке указываем ваше доменное имя. Остальные правки в файле вносятся по усмотрению, исходя из необходимости из внесения (ориентируйтесь на описания, указанные у полей). +## 🌈 Current status -4. Редактируем указанные файлы: - + **favicon.ico** (меняем на свою иконку, если есть) - + **robots.txt** (меняем адреса в строках **Host** и **Sitemap** на свои) - + **opensearch_desc.xml** (меняем описание и адрес на свои) - + **opensearch_desc_bt.xml** (меняем описание и адрес на свои) +TorrentPier is currently in active development. The goal is to remove all legacy code and rewrite the existing code to +modern specifications. If you want to delve deep into the code, check our [issues](https://github.com/torrentpier/torrentpier/issues) +and go from there. The documentation will be translated to English in the near future, currently Russian is the main language. -## Права доступа на папки и файлы +## ✨ Features +* Rich forum with browsing/moderation tools +* High-load capable, heavily configurable announcer +* Scrape support +* FreeLeech +* [TorrServer integration](https://github.com/YouROK/TorrServer) support +* BitTorrent v2 support +* Event-based invite system +* Bonus points +* Polling system +* PM/DM system +* Multilingual support (Russian and English are currently fully supported, with others in the future) +* Atom/RSS feeds +* ... and so MUCH MORE! -Исходя из настроек вашего сервера, устанавливаем рекомендуемые права доступа (chmod) на указанные папки **777**, а на файлы внутри этих папок (кроме файлов **.htaccess** и **.keep**) **666**: -- data/avatars -- data/old_files -- data/torrent_files -- internal_data/ajax_html -- internal_data/atom -- internal_data/cache -- internal_data/captcha -- internal_data/log -- internal_data/sitemap -- internal_data/triggers +## 🖥️ Demo -## Необходимая версия php +* URL: https://torrentpier.duckdns.org +* Username: `admin` +* Password: `admin` -Минимально поддерживаемой версией в настоящий момент является 5.3. Существует поддержка вплоть до версии 5.5 (в данной версии в логах будет уведомление об использовании устаревших функций). Версия php 5.6 в настоящее время движком не поддерживается и его работа на ней не гарантируется. Мы делаем все возможное чтобы в самое ближайшее время добавить его поддержку. +> [!NOTE] +> Demo resets every 24 hours! -## Необходимые настройки php +## 🔧 Requirements - mbstring.internal_encoding = UTF-8 - magic_quotes_gpc = Off -Внести данные настройки необходимо в файл **php.ini**. Их вам может установить ваш хостер по запросу, если у вас возникают какие-либо проблемы с их самостоятельной установкой. Впрочем, эти настройки могут быть установлены на сервере по-умолчанию, поэтому их внесение требуется исключительно по необходимости. +* Apache / nginx ([example config](install/nginx.conf)) / caddy ([example config](install/Caddyfile)) +* MySQL 5.5.3 or above (including MySQL 8.0+) / MariaDB 10.0 or above / Percona +* PHP: 8.2 / 8.3 / 8.4 +* PHP Extensions: mbstring, gd, bcmath, intl, tidy (optional), xml, xmlwriter +* Crontab (Recommended) -## Необходимые модули php +## 💾 Installation - php5-tidy -Начиная с версии 2.0.9 (ревизия 592 в старой нумерации) данный модуль не является обязательным, но его установка крайне рекомендуется для повышения качества обработки html-кода тем и сообщений пользователей. +For the installation, select one of the installation variants below: -## Рекомендуемый способ запуска cron.php +### Quick (Clean install) 🚀 -Для значительного ускорения работы трекера может потребоваться отвязка встроенного форумного крона. С более подробной информацией об отвязке крона, вы можете ознакомиться в данной теме https://torrentpier.me/threads/52/ на нашем форуме поддержки. +Check out our [autoinstall](https://github.com/torrentpier/autoinstall) repository with detailed instructions. -## Локальный файл конфигурации +> [!NOTE] +> Thanks to [Sergei Solovev](https://github.com/SeAnSolovev) for this installation script ❤️ -Начиная с ревизии 599 была добавлена поддерка автоматического подключения файла config.local.php, при создании его вами. В данном файле вы можете переопределять настройки файла config.php для конкретного сервера, на котором запущен трекер или в целом менять стандартные значения файла config.php, для более простого обновления файлов движка в дальнейшем. +### Quick (For web-panels) ☕️ -## Установка Ocelot +1. Select the folder where you want TorrentPier installed + ```shell + cd /path/to/public_html + ``` +2. Download the latest version of TorrentPier + ```shell + sudo git clone https://github.com/torrentpier/torrentpier.git . + ``` +3. After completing, execute the command below and follow the instructions + ```shell + php install.php + ``` +4. Voila! ✨ -В движок встроена по-умолчанию поддержка альтернативного компилируемого анонсера - Ocelot. Настройка производится в файле **library/config.php**, сам анонсер находится в репозитории https://github.com/torrentpier/ocelot +### Manual 🔩 -Инструкция по сборке приведена на нашем форуме: https://torrentpier.me/threads/sborka-ocelot-pod-debian-7-1.26078/ -Для работы анонсера требуется замена двух таблиц в базе данных - дамп в файле: **install/sql/ocelot.sql** +1. Install [Composer](https://getcomposer.org/) +2. Run the following command to create the TorrentPier project + ```shell + composer create-project torrentpier/torrentpier + ``` +3. [Check our system requirements](#-requirements) +4. After, run this command in the project directory to install Composer dependencies + ```shell + composer install + ``` +5. Edit database configuration settings in the environment (`.env.example`), after, rename to `.env` +6. Create a database and run migrations to set up the schema + ```shell + php vendor/bin/phinx migrate --configuration=phinx.php + ``` +7. Provide write permissions to the specified folders: + * `data/avatars`, `data/uploads`, `data/uploads/thumbs` + * `internal_data/atom`, `internal_data/cache`, `internal_data/log`, `internal_data/triggers` + * `sitemap` +8. Voila! ✨ -## Папка install +> [!TIP] +> You can automate steps 4-7 by running `php install.php` instead, which will guide you through the setup process interactively. -В корне движка присутствует папка **install**, в которой находятся служебные файлы, необходимые для его установки (дамп базы, примеры конфигов) и обновления (дамперы, скрипты конвертации). Доступ к данной папке по-умолчанию закрыт, но если ее присутствие вам мешает - вы можете ее удалить. На файлы **README.md** и **CONTRIBUTORS.md** это также распространяется. +> [!IMPORTANT] +> The specific settings depend on the server you are using, but in general we recommend chmod **0755** for folders, and chmod **0644** for the files in them. -## Полезные ссылки +### Additional steps 👣 -+ Наш форум https://torrentpier.me/ -+ Центр загрузки https://get.torrentpier.me/ -+ Часто задаваемые вопросы https://faq.torrentpier.me/ -+ Где задать вопрос https://torrentpier.me/forums/10/ +1. Edit these files: + * `favicon.png` (change to your own) + * `robots.txt` (change the addresses in lines `Host` and `Sitemap` to your own) +2. Log in to the forum using the **admin/admin** login/password, and finish setting up via admin panel. Don't forget to change your password! + +## 🔐 Security vulnerabilities + +If you discover a security vulnerability within TorrentPier, please follow our [security policy](https://github.com/torrentpier/torrentpier/security/policy), so we can address it promptly. + +## 🧪 Testing + +TorrentPier includes a comprehensive testing suite built with **Pest PHP**. Run tests to ensure code quality and system reliability: + +```shell +# Run all tests +./vendor/bin/pest + +# Run with coverage +./vendor/bin/pest --coverage +``` + +For detailed testing documentation, see [tests/README.md](tests/README.md). + +## 📌 Our recommendations + +* *It's recommended to run `cron.php`.* - For significant tracker speed increase it may be required to replace the built-in cron.php with an operating system daemon. +* *Local configuration copy.* - You can override the settings using the local configuration file `library/config.local.php`. + +## 💚 Contributing / Contributors + +Please read our [contributing policy](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md) for details, and the process for +submitting pull requests to us. But we are always ready to review your pull-request for compliance with +these requirements. Just send it! + + + Contributors + + +Made with [contrib.rocks](https://contrib.rocks). + +## 💞 Sponsoring + +Support this project by becoming a sponsor or a backer. + +[![OpenCollective sponsors](https://opencollective.com/torrentpier/sponsors/badge.svg)](https://opencollective.com/torrentpier) +[![OpenCollective backers](https://opencollective.com/torrentpier/backers/badge.svg)](https://opencollective.com/torrentpier) + +
+ Monero + +``` +42zJE3FDvN8foP9QYgDrBjgtd7h2FipGCGmAcmG5VFQuRkJBGMbCvoLSmivepmAMEgik2E8MPWUzKaoYsGCtmhvL7ZN73jh +``` +
+ +
+ YooMoney + +``` +4100118022415720 +``` +
+ +## 📦 Versioning + +We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/torrentpier/torrentpier/tags). + +## 📖 License + +This project is licensed under the MIT License - see the [LICENSE](https://github.com/torrentpier/torrentpier/blob/master/LICENSE) file for details. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..73d867596 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Versions + +Due to the nature of our project - being open source - we have decided to patch only the latest major release (currently v2.4.x) for security vulnerabilities. + +## How to disclose + +Please disclose security issues by mailing [admin@torrentpier.com](mailto:admin@torrentpier.com). + +## What we do + +Any submitted security issue will be checked thoroughly by our development team. A fix for the issue and a transparent information on GitHub about the issue existing will be released. You can view any previously identified issues on our [GitHub Security Page](https://github.com/torrentpier/torrentpier/security/advisories). New major versions of TorrentPier will also receive a security audit to verify our efforts on providing a secure application. diff --git a/UPGRADE_GUIDE.md b/UPGRADE_GUIDE.md new file mode 100644 index 000000000..2305e8bba --- /dev/null +++ b/UPGRADE_GUIDE.md @@ -0,0 +1,1261 @@ +# 🚀 TorrentPier Upgrade Guide + +This guide helps you upgrade your TorrentPier installation to the latest version, covering breaking changes, new features, and migration strategies. + +## 📖 Table of Contents + +- [Database Migration System](#database-migration-system) +- [Database Layer Migration](#database-layer-migration) +- [Unified Cache System Migration](#unified-cache-system-migration) +- [Configuration System Migration](#configuration-system-migration) +- [Language System Migration](#language-system-migration) +- [Censor System Migration](#censor-system-migration) +- [Select System Migration](#select-system-migration) +- [Development System Migration](#development-system-migration) +- [Breaking Changes](#breaking-changes) +- [Best Practices](#best-practices) + +## 🗄️ Database Migration System + +TorrentPier now includes a modern database migration system using **Phinx** (from CakePHP), replacing the legacy direct SQL import approach. This provides version-controlled database schema management with rollback capabilities. + +### Key Benefits + +- **Version Control**: Database schema changes are tracked in code +- **Environment Consistency**: Same database structure across development, staging, and production +- **Safe Rollbacks**: Ability to safely revert schema changes +- **Team Collaboration**: No more merge conflicts on database changes +- **Automated Deployments**: Database updates as part of deployment process + +### Migration Architecture + +#### Engine Strategy +- **InnoDB**: Used for all tables for maximum data integrity and reliability +- **ACID Compliance**: Full transaction support and crash recovery for all data +- **Row-Level Locking**: Better concurrency for high-traffic operations + +#### Directory Structure +``` +/migrations/ + ├── 20250619000001_initial_schema.php # Complete database schema + ├── 20250619000002_seed_initial_data.php # Essential data seeding + └── future_migrations... # Your custom migrations +/phinx.php # Migration configuration +``` + +### For New Installations + +New installations automatically use migrations instead of the legacy SQL dump: + +```bash +# Fresh installation now uses migrations +php install.php +``` + +The installer will: +1. Set up environment configuration +2. Create the database +3. Run all migrations automatically +4. Seed initial data (admin user, configuration, etc.) + +### For Existing Installations + +Existing installations continue to work without changes. The migration system is designed for new installations and development workflows. + +**Important**: Existing installations should **not** attempt to migrate to the new system without proper backup and testing procedures. + +### Developer Workflow + +#### Creating Migrations +```bash +# Create a new migration +php vendor/bin/phinx create AddNewFeatureTable + +# Edit the generated migration file +# /migrations/YYYYMMDDHHMMSS_add_new_feature_table.php +``` + +#### Running Migrations +```bash +# Run all pending migrations +php vendor/bin/phinx migrate + +# Check migration status +php vendor/bin/phinx status + +# Rollback last migration +php vendor/bin/phinx rollback +``` + +#### Migration Template +```php +table('bb_new_feature', [ + 'engine' => 'InnoDB', + 'collation' => 'utf8mb4_unicode_ci' + ]); + + $table->addColumn('name', 'string', ['limit' => 100]) + ->addColumn('created_at', 'timestamp', ['default' => 'CURRENT_TIMESTAMP']) + ->addIndex('name') + ->create(); + } + + // Optional: explicit up/down methods for complex operations + public function up() + { + // Complex data migration logic + } + + public function down() + { + // Rollback logic + } +} +``` + +#### Engine Guidelines +```php +// Use InnoDB for all tables for maximum reliability +$table = $this->table('bb_user_posts', [ + 'engine' => 'InnoDB', + 'collation' => 'utf8mb4_unicode_ci' +]); + +// All tracker tables also use InnoDB for data integrity +$table = $this->table('bb_bt_peer_stats', [ + 'engine' => 'InnoDB', + 'collation' => 'utf8mb4_unicode_ci' +]); + +// Buffer tables use InnoDB for consistency and reliability +public function up() { + $this->execute('DROP TABLE IF EXISTS buf_temp_data'); + // Recreate with new structure using InnoDB +} +``` + +### Admin Panel Integration + +The admin panel includes a read-only migration status page at `/admin/admin_migrations.php`: + +- **Current migration version** +- **Applied migrations history** +- **Pending migrations list** +- **Database statistics** +- **Clear instructions for CLI operations** + +**Important**: The admin panel is **read-only** for security. All migration operations must be performed via CLI. + +### Complex Migration Handling + +For complex data transformations, create external scripts: + +```php +// migrations/YYYYMMDDHHMMSS_complex_data_migration.php +class ComplexDataMigration extends AbstractMigration +{ + public function up() + { + $this->output->writeln('Running complex data migration...'); + + // Call external script for complex operations + $result = shell_exec('php ' . __DIR__ . '/../scripts/migrate_torrent_data.php'); + $this->output->writeln($result); + + if (strpos($result, 'ERROR') !== false) { + throw new Exception('Complex migration failed'); + } + } +} +``` + +### Best Practices + +#### Migration Development +```bash +# 1. Create migration +php vendor/bin/phinx create MyFeature + +# 2. Edit migration file +# 3. Test locally +php vendor/bin/phinx migrate -e development + +# 4. Test rollback +php vendor/bin/phinx rollback -e development + +# 5. Commit to version control +git add migrations/ +git commit -m "Add MyFeature migration" +``` + +#### Production Deployment +```bash +# Always backup database first +mysqldump tracker_db > backup_$(date +%Y%m%d_%H%M%S).sql + +# Run migrations +php vendor/bin/phinx migrate -e production + +# Verify application functionality +# Monitor error logs +``` + +#### Team Collaboration +- **Never modify existing migrations** that have been deployed +- **Always create new migrations** for schema changes +- **Test migrations on production-like data** before deployment +- **Coordinate with team** before major schema changes + +### Configuration + +The migration system uses your existing `.env` configuration: + +```php +// phinx.php automatically reads from .env +'production' => [ + 'adapter' => 'mysql', + 'host' => env('DB_HOST', 'localhost'), + 'port' => (int) env('DB_PORT', 3306), + 'name' => env('DB_DATABASE'), + 'user' => env('DB_USERNAME'), + 'pass' => env('DB_PASSWORD', ''), + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci' +] +``` + +### Troubleshooting + +#### Common Issues +```bash +# Migration table doesn't exist +php vendor/bin/phinx init # Re-run if needed + +# Migration fails mid-way +php vendor/bin/phinx rollback # Rollback to previous state + +# Check what would be applied +php vendor/bin/phinx status # See pending migrations +``` + +#### Migration Recovery +```bash +# If migration fails, check status first +php vendor/bin/phinx status + +# Rollback to known good state +php vendor/bin/phinx rollback -t 20250619000002 + +# Fix the migration code and re-run +php vendor/bin/phinx migrate +``` + +### Legacy SQL Import Removal + +The legacy `install/sql/mysql.sql` approach has been replaced by migrations: + +- ✅ **New installations**: Use migrations automatically +- ✅ **Development workflow**: Create migrations for all schema changes +- ✅ **Version control**: All schema changes tracked in Git +- ❌ **Direct SQL imports**: No longer used for new installations + +### Security Considerations + +- **CLI-only execution**: Migrations run via command line only +- **Read-only admin interface**: Web interface shows status only +- **Backup requirements**: Always backup before production migrations +- **Access control**: Restrict migration command access to authorized personnel + +### Migration Setup for Existing Installations + +If you have an **existing TorrentPier installation** and want to adopt the migration system, you need to mark the initial migrations as already applied to avoid recreating your existing database schema. + +#### Detection: Do You Need This? + +You need migration setup if: +- ✅ You have an existing TorrentPier installation with data +- ✅ Your database already has tables like `bb_users`, `bb_forums`, etc. +- ✅ The admin migration panel shows "Migration System: ✗ Not Initialized" + +#### Step-by-Step Setup Process + +**1. Backup Your Database** +```bash +mysqldump -u username -p database_name > backup_$(date +%Y%m%d_%H%M%S).sql +``` + +**2. Initialize Migration Table** +```bash +# This creates the bb_migrations table without running any migrations +php vendor/bin/phinx init +``` + +**3. Mark Initial Migrations as Applied (Fake Run)** +```bash +# Mark the schema migration as applied without running it +php vendor/bin/phinx migrate --fake --target=20250619000001 + +# Mark the data seeding migration as applied without running it +php vendor/bin/phinx migrate --fake --target=20250619000002 +``` + +**4. Verify Setup** +```bash +# Check migration status +php vendor/bin/phinx status +``` + +You should see both initial migrations marked as "up" (applied). + +#### Alternative: Manual SQL Method + +If you prefer manual control, you can directly insert migration records: + +```sql +-- Create migration table (if phinx init didn't work) +CREATE TABLE IF NOT EXISTS bb_migrations ( + version bigint(20) NOT NULL, + migration_name varchar(100) DEFAULT NULL, + start_time timestamp NULL DEFAULT NULL, + end_time timestamp NULL DEFAULT NULL, + breakpoint tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (version) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Mark initial migrations as applied +INSERT INTO bb_migrations (version, migration_name, start_time, end_time, breakpoint) +VALUES +('20250619000001', 'InitialSchema', NOW(), NOW(), 0), +('20250619000002', 'SeedInitialData', NOW(), NOW(), 0); +``` + +#### Post-Setup Workflow + +After setup, your existing installation will work exactly like a fresh installation: + +```bash +# Create new migrations +php vendor/bin/phinx create AddNewFeature + +# Run new migrations +php vendor/bin/phinx migrate + +# Check status +php vendor/bin/phinx status +``` + +#### Troubleshooting + +**Migration table already exists:** +- Check if you've already set up migrations: `php vendor/bin/phinx status` +- If it shows errors, you may need to recreate: `DROP TABLE bb_migrations;` then restart + +**"Nothing to migrate" message:** +- This is normal after fake runs - it means setup was successful +- New migrations will appear when you create them + +**Admin panel shows "Needs Setup":** +- Follow the setup process above +- Refresh the admin panel after completion + +## 🗄️ Database Layer Migration + +TorrentPier has completely replaced its legacy database layer (SqlDb/Dbs) with a modern implementation using Nette Database while maintaining 100% backward compatibility. + +### No Code Changes Required + +**Important**: All existing `DB()->method()` calls continue to work exactly as before. This is an internal modernization that requires **zero code changes** in your application. + +```php +// ✅ All existing code continues to work unchanged +$user = DB()->fetch_row("SELECT * FROM users WHERE id = ?", 123); +$users = DB()->fetch_rowset("SELECT * FROM users"); +$affected = DB()->affected_rows(); +$result = DB()->sql_query("UPDATE users SET status = ? WHERE id = ?", 1, 123); +$escaped = DB()->escape($userInput); +``` + +### Key Improvements + +#### Modern Foundation +- **Nette Database v3.2**: Modern, actively maintained database layer +- **PDO-based**: Improved security and performance +- **Type Safety**: Better error detection and IDE support +- **Singleton Pattern**: Efficient connection management + +#### Enhanced Reliability +- **Automatic Resource Cleanup**: Better memory management +- **Improved Error Handling**: More detailed error information +- **Connection Stability**: Better handling of connection issues +- **Performance Optimizations**: Reduced overhead and improved query execution + +#### Debugging and Development +- **Enhanced Explain Support**: Improved query analysis +- **Better Query Logging**: More detailed performance tracking +- **Debug Information**: Comprehensive debugging features +- **Memory Tracking**: Better resource usage monitoring + +### Multiple Database Support + +Multiple database servers continue to work exactly as before: + +```php +// ✅ Multiple database access unchanged +$main_db = DB('db'); // Main database +$tracker_db = DB('tr'); // Tracker database +$stats_db = DB('stats'); // Statistics database +``` + +### Error Handling + +All error handling patterns remain identical: + +```php +// ✅ Error handling works exactly as before +$result = DB()->sql_query("SELECT * FROM users"); +if (!$result) { + $error = DB()->sql_error(); + echo "Error: " . $error['message']; +} +``` + +### Debug and Explain Features + +All debugging functionality is preserved and enhanced: + +```php +// ✅ Debug features work as before +DB()->debug('start'); +// ... run queries ... +DB()->debug('stop'); + +// ✅ Explain functionality unchanged +DB()->explain('start'); +DB()->explain('display'); +``` + +### Performance Benefits + +While maintaining compatibility, you get: +- **Faster Connection Handling**: Singleton pattern prevents connection overhead +- **Modern Query Execution**: Nette Database optimizations +- **Better Resource Management**: Automatic cleanup and proper connection handling +- **Reduced Memory Usage**: More efficient object management + +### 📖 Detailed Documentation + +For comprehensive information about the database layer changes, implementation details, and technical architecture, see: + +**[src/Database/README.md](src/Database/README.md)** + +This documentation covers: +- Complete architecture overview +- Technical implementation details +- Migration notes and compatibility information +- Debugging features and usage examples +- Performance benefits and benchmarks + +### Legacy Code Cleanup + +The following legacy files have been removed from the codebase: +- `src/Legacy/SqlDb.php` - Original database class +- `src/Legacy/Dbs.php` - Original database factory + +These were completely replaced by: +- `src/Database/Database.php` - Modern database class with Nette Database (renamed from `DB.php`) +- `src/Database/DatabaseFactory.php` - Modern factory with backward compatibility (renamed from `DbFactory.php`) +- `src/Database/DatabaseDebugger.php` - Dedicated debug functionality extracted from Database class +- `src/Database/DebugSelection.php` - Debug-enabled wrapper for Nette Database Selection + +### Verification + +To verify the migration is working correctly: + +```php +// ✅ Test basic database operations +$version = DB()->server_version(); +$testQuery = DB()->fetch_row("SELECT 1 as test"); +echo "Database version: $version, Test: " . $testQuery['test']; + +// ✅ Test error handling +$result = DB()->sql_query("SELECT invalid_column FROM non_existent_table"); +if (!$result) { + $error = DB()->sql_error(); + echo "Error handling works: " . $error['message']; +} +``` + +## 💾 Unified Cache System Migration + +TorrentPier has replaced its legacy Cache and Datastore systems with a modern unified implementation using Nette Caching while maintaining 100% backward compatibility. + +### No Code Changes Required + +**Important**: All existing `CACHE()` and `$datastore` calls continue to work exactly as before. This is an internal modernization that requires **zero code changes** in your application. + +```php +// ✅ All existing code continues to work unchanged +$cache = CACHE('bb_cache'); +$value = $cache->get('key'); +$cache->set('key', $value, 3600); + +$datastore = datastore(); +$forums = $datastore->get('cat_forums'); +$datastore->store('custom_data', $data); +``` + +### Key Improvements + +#### Modern Foundation +- **Nette Caching v3.3**: Modern, actively maintained caching library +- **Unified System**: Single caching implementation instead of duplicate Cache/Datastore code +- **Singleton Pattern**: Efficient memory usage and consistent TorrentPier architecture +- **Advanced Features**: Dependencies, tags, bulk operations, memoization + +#### Enhanced Performance +- **456,647+ operations per second**: Verified production performance +- **Memory Optimization**: Shared storage and efficient instance management +- **Debug Compatibility**: Full compatibility with Dev.php debugging features + +### Enhanced Capabilities + +New code can leverage advanced Nette Caching features: + +```php +// ✅ Enhanced caching with dependencies +$cache = CACHE('bb_cache'); +$forums = $cache->load('forums', function() { + return build_forums_data(); +}, [ + \Nette\Caching\Cache::Expire => '1 hour', + \Nette\Caching\Cache::Files => ['/path/to/config.php'] +]); + +// ✅ Function memoization +$result = $cache->call('expensive_function', $param); +``` + +### 📖 Detailed Documentation + +For comprehensive information about the unified cache system, advanced features, and technical architecture, see: + +**[src/Cache/README.md](src/Cache/README.md)** + +This documentation covers: +- Complete architecture overview and singleton pattern +- Advanced Nette Caching features and usage examples +- Performance benchmarks and storage type comparisons +- Critical compatibility issues resolved during implementation + +### Verification + +To verify the migration is working correctly: + +```php +// ✅ Test basic cache operations +$cache = CACHE('test_cache'); +$cache->set('test_key', 'test_value', 60); +$value = $cache->get('test_key'); +echo "Cache test: " . ($value === 'test_value' ? 'PASSED' : 'FAILED'); + +// ✅ Test datastore operations +$datastore = datastore(); +$datastore->store('test_item', ['status' => 'verified']); +$item = $datastore->get('test_item'); +echo "Datastore test: " . ($item['status'] === 'verified' ? 'PASSED' : 'FAILED'); +``` + +## ⚙️ Configuration System Migration + +The new TorrentPier features a modern, centralized configuration system with full backward compatibility. + +### Quick Migration Overview + +```php +// ❌ Old way (still works, but not recommended) +global $bb_cfg; +$announceUrl = $bb_cfg['bt_announce_url']; +$dbHost = $bb_cfg['database']['host']; + +// ✅ New way (recommended) +$announceUrl = config()->get('bt_announce_url'); +$dbHost = config()->get('database.host'); +``` + +### Key Configuration Changes + +#### Basic Usage +```php +// Get configuration values using dot notation +$siteName = config()->get('sitename'); +$dbHost = config()->get('database.host'); +$cacheTimeout = config()->get('cache.timeout'); + +// Get with default value if key doesn't exist +$maxUsers = config()->get('max_users_online', 100); +$debugMode = config()->get('debug.enabled', false); +``` + +#### Setting Values +```php +// Set configuration values +config()->set('sitename', 'My Awesome Tracker'); +config()->set('database.port', 3306); +config()->set('cache.enabled', true); +``` + +#### Working with Sections +```php +// Get entire configuration section +$dbConfig = config()->getSection('database'); +$trackerConfig = config()->getSection('tracker'); + +// Check if configuration exists +if (config()->has('bt_announce_url')) { + $announceUrl = config()->get('bt_announce_url'); +} +``` + +### Common Configuration Mappings + +| Old Syntax | New Syntax | +|------------|------------| +| `$bb_cfg['sitename']` | `config()->get('sitename')` | +| `$bb_cfg['database']['host']` | `config()->get('database.host')` | +| `$bb_cfg['tracker']['enabled']` | `config()->get('tracker.enabled')` | +| `$bb_cfg['cache']['timeout']` | `config()->get('cache.timeout')` | +| `$bb_cfg['torr_server']['url']` | `config()->get('torr_server.url')` | + +### Magic Methods Support +```php +// Magic getter +$siteName = config()->sitename; +$dbHost = config()->{'database.host'}; + +// Magic setter +config()->sitename = 'New Site Name'; +config()->{'database.port'} = 3306; + +// Magic isset +if (isset(config()->bt_announce_url)) { + // Configuration exists +} +``` + +## 🌐 Language System Migration + +TorrentPier has modernized its language system with a singleton pattern while maintaining 100% backward compatibility with existing global `$lang` variable. + +### No Code Changes Required + +**Important**: All existing `global $lang` calls continue to work exactly as before. This is an internal modernization that requires **zero code changes** in your application. + +```php +// ✅ All existing code continues to work unchanged +global $lang; +echo $lang['FORUM']; +echo $lang['DATETIME']['TODAY']; +``` + +### Key Improvements + +#### Modern Foundation +- **Singleton Pattern**: Efficient memory usage and consistent TorrentPier architecture +- **Centralized Management**: Single point of control for language loading and switching +- **Type Safety**: Better error detection and IDE support +- **Dot Notation Support**: Access nested language arrays with simple syntax + +#### Enhanced Functionality +- **Automatic Fallback**: Source language fallback for missing translations +- **Dynamic Loading**: Load additional language files for modules/extensions +- **Runtime Modification**: Add or modify language strings at runtime +- **Locale Management**: Automatic locale setting based on language selection + +### Enhanced Capabilities + +New code can leverage the modern Language singleton features with convenient shorthand functions: + +```php +// ✅ Convenient shorthand functions (recommended for frequent use) +echo __('FORUM'); // Same as lang()->get('FORUM') +echo __('DATETIME.TODAY'); // Dot notation for nested arrays +_e('WELCOME_MESSAGE'); // Echo shorthand +$message = __('CUSTOM_MESSAGE', 'Default'); // With default value + +// ✅ Full singleton access (for advanced features) +echo lang()->get('FORUM'); +echo lang()->get('DATETIME.TODAY'); // Dot notation for nested arrays + +// ✅ Check if language key exists +if (lang()->has('ADVANCED_FEATURE')) { + echo __('ADVANCED_FEATURE'); +} + +// ✅ Get current language information +$currentLang = lang()->getCurrentLanguage(); +$langName = lang()->getLanguageName(); +$langLocale = lang()->getLanguageLocale(); + +// ✅ Load additional language files for modules +lang()->loadAdditionalFile('custom_module', 'en'); + +// ✅ Runtime language modifications +lang()->set('CUSTOM_KEY', 'Custom Value'); +lang()->set('NESTED.KEY', 'Nested Value'); +``` + +### Language Management + +#### Available Languages +```php +// Get all available languages from configuration +$availableLanguages = lang()->getAvailableLanguages(); + +// Get language display name +$englishName = lang()->getLanguageName('en'); // Returns: "English" +$currentName = lang()->getLanguageName(); // Current language name + +// Get language locale for formatting +$locale = lang()->getLanguageLocale('ru'); // Returns: "ru_RU.UTF-8" +``` + +#### Dynamic Language Loading +```php +// Load additional language files (useful for modules/plugins) +$success = lang()->loadAdditionalFile('torrent_management'); +if ($success) { + echo lang()->get('TORRENT_UPLOADED'); +} + +// Load from specific language +lang()->loadAdditionalFile('admin_panel', 'de'); +``` + +#### Runtime Modifications +```php +// Set custom language strings +lang()->set('SITE_WELCOME', 'Welcome to Our Tracker!'); +lang()->set('ERRORS.INVALID_TORRENT', 'Invalid torrent file'); + +// Modify existing strings +lang()->set('LOGIN', 'Sign In'); +``` + +### Backward Compatibility Features + +The singleton automatically maintains all global variables: + +```php +// Global variable is automatically updated by the singleton +global $lang; + +// When you call lang()->set(), global is updated +lang()->set('CUSTOM', 'Value'); +echo $lang['CUSTOM']; // Outputs: "Value" + +// When language is initialized, $lang is populated +// $lang contains user language + source language fallbacks +``` + +### Integration with User System + +The Language singleton integrates seamlessly with the User system: + +```php +// User language is automatically detected and initialized +// Based on user preferences, browser detection, or defaults + +// In User->init_userprefs(), language is now initialized with: +lang()->initializeLanguage($userLanguage); + +// This replaces the old manual language file loading +// while maintaining exact same functionality +``` + +### Convenient Shorthand Functions + +For frequent language access, TorrentPier provides convenient shorthand functions: + +```php +// ✅ __() - Get language string (most common) +echo __('FORUM'); // Returns: "Forum" +echo __('DATETIME.TODAY'); // Nested access: "Today" +$msg = __('MISSING_KEY', 'Default'); // With default value + +// ✅ _e() - Echo language string directly +_e('WELCOME_MESSAGE'); // Same as: echo __('WELCOME_MESSAGE') +_e('USER_ONLINE', 'Online'); // With default value + +// ✅ Common usage patterns +$title = __('PAGE_TITLE', config()->get('sitename')); +$error = __('ERROR.INVALID_INPUT', 'Invalid input'); +``` + +These functions make language access much more convenient compared to the full `lang()->get()` syntax: + +```php +// Before (verbose) +echo lang()->get('FORUM'); +echo lang()->get('DATETIME.TODAY'); +$msg = lang()->get('WELCOME', 'Welcome'); + +// After (concise) +echo __('FORUM'); +echo __('DATETIME.TODAY'); +$msg = __('WELCOME', 'Welcome'); +``` + +### Magic Methods Support +```php +// Magic getter (same as lang()->get()) +$welcome = lang()->WELCOME; +$today = lang()->{'DATETIME.TODAY'}; + +// Magic setter (same as lang()->set()) +lang()->CUSTOM_MESSAGE = 'Hello World'; +lang()->{'NESTED.KEY'} = 'Nested Value'; + +// Magic isset +if (isset(lang()->ADVANCED_FEATURE)) { + // Language key exists +} +``` + +### Performance Benefits + +While maintaining compatibility, you get: +- **Single Language Loading**: Languages loaded once and cached in singleton +- **Memory Efficiency**: No duplicate language arrays across application +- **Automatic Locale Setting**: Proper locale configuration for date/time formatting +- **Fallback Chain**: Source language → Default language → Requested language + +### Verification + +To verify the migration is working correctly: + +```php +// ✅ Test convenient shorthand functions +echo "Forum text: " . __('FORUM'); +echo "Today text: " . __('DATETIME.TODAY'); +_e('INFORMATION'); // Echo directly + +// ✅ Test with default values +echo "Custom: " . __('CUSTOM_KEY', 'Default Value'); + +// ✅ Test full singleton access +echo "Current language: " . lang()->getCurrentLanguage(); +echo "Language name: " . lang()->getLanguageName(); + +// ✅ Test backward compatibility +global $lang; +echo "Global access: " . $lang['FORUM']; + +// ✅ Verify globals are synchronized +lang()->set('TEST_KEY', 'Test Value'); +echo "Sync test: " . $lang['TEST_KEY']; // Should output: "Test Value" +``` + +## 🛡️ Censor System Migration + +The word censoring system has been refactored to use a singleton pattern, similar to the Configuration system, providing better performance and consistency. + +### Quick Migration Overview + +```php +// ❌ Old way (still works, but not recommended) +global $wordCensor; +$censored = $wordCensor->censorString($text); + +// ✅ New way (recommended) +$censored = censor()->censorString($text); +``` + +### Key Censor Changes + +#### Basic Usage +```php +// Censor a string +$text = "This contains badword content"; +$censored = censor()->censorString($text); + +// Check if censoring is enabled +if (censor()->isEnabled()) { + $censored = censor()->censorString($text); +} else { + $censored = $text; +} + +// Get count of loaded censored words +$wordCount = censor()->getWordsCount(); +``` + +#### Advanced Usage +```php +// Add runtime censored words (temporary, not saved to database) +censor()->addWord('badword', '***'); +censor()->addWord('anotherbad*', 'replaced'); // Wildcards supported + +// Reload censored words from database (useful after admin updates) +censor()->reload(); + +// Check if censoring is enabled +$isEnabled = censor()->isEnabled(); +``` + +### Backward Compatibility + +The global `$wordCensor` variable is still available and works exactly as before: + +```php +// This still works - backward compatibility maintained +global $wordCensor; +$censored = $wordCensor->censorString($text); + +// But this is now preferred +$censored = censor()->censorString($text); +``` + +### Performance Benefits + +- **Single Instance**: Only one censor instance loads words from database +- **Automatic Reloading**: Words are automatically reloaded when updated in admin panel +- **Memory Efficient**: Shared instance across entire application +- **Lazy Loading**: Words only loaded when censoring is enabled + +### Admin Panel Updates + +When you update censored words in the admin panel, the system now automatically: +1. Updates the datastore cache +2. Reloads the singleton instance with fresh words +3. Applies changes immediately without requiring page refresh + +## 📋 Select System Migration + +The Select class has been moved and reorganized for better structure and consistency within the legacy system organization. + +### Quick Migration Overview + +```php +// ❌ Old way (deprecated) +\TorrentPier\Legacy\Select::language($new['default_lang'], 'default_lang'); +\TorrentPier\Legacy\Select::timezone('', 'timezone_type'); +\TorrentPier\Legacy\Select::template($pr_data['tpl_name'], 'tpl_name'); + +// ✅ New way (recommended) +\TorrentPier\Legacy\Common\Select::language($new['default_lang'], 'default_lang'); +\TorrentPier\Legacy\Common\Select::timezone('', 'timezone_type'); +\TorrentPier\Legacy\Common\Select::template($pr_data['tpl_name'], 'tpl_name'); +``` + +#### Namespace Update +The Select class has been moved from `\TorrentPier\Legacy\Select` to `\TorrentPier\Legacy\Common\Select` to better organize legacy components. + +#### Method Usage Remains Unchanged +```php +// Language selection dropdown +$languageSelect = \TorrentPier\Legacy\Common\Select::language($currentLang, 'language_field'); + +// Timezone selection dropdown +$timezoneSelect = \TorrentPier\Legacy\Common\Select::timezone($currentTimezone, 'timezone_field'); + +// Template selection dropdown +$templateSelect = \TorrentPier\Legacy\Common\Select::template($currentTemplate, 'template_field'); +``` + +#### Available Select Methods +```php +// All existing methods remain available: +\TorrentPier\Legacy\Common\Select::language($selected, $name); +\TorrentPier\Legacy\Common\Select::timezone($selected, $name); +\TorrentPier\Legacy\Common\Select::template($selected, $name); +``` + +### Backward Compatibility + +The old class path is deprecated but still works through class aliasing: + +```php +// This still works but is deprecated +\TorrentPier\Legacy\Select::language($lang, 'default_lang'); + +// This is the new recommended way +\TorrentPier\Legacy\Common\Select::language($lang, 'default_lang'); +``` + +### Migration Strategy + +1. **Search and Replace**: Update all references to the old namespace +2. **Import Statements**: Update use statements if you're using them +3. **Configuration Files**: Update any configuration that references the old class path + +```php +// Update use statements +// Old +use TorrentPier\Legacy\Select; + +// New +use TorrentPier\Legacy\Common\Select; +``` + +## 🛠️ Development System Migration + +The development and debugging system has been refactored to use a singleton pattern, providing better resource management and consistency across the application. + +### Quick Migration Overview + +```php +// ❌ Old way (still works, but not recommended) +$sqlLog = \TorrentPier\Dev::getSqlLog(); +$isDebugAllowed = \TorrentPier\Dev::sqlDebugAllowed(); +$shortQuery = \TorrentPier\Dev::shortQuery($sql); + +// ✅ New way (recommended) +$sqlLog = dev()->getSqlDebugLog(); +$isDebugAllowed = dev()->checkSqlDebugAllowed(); +$shortQuery = dev()->formatShortQuery($sql); +``` + +### Key Development System Changes + +#### Basic Usage +```php +// Get SQL debug log +$sqlLog = dev()->getSqlDebugLog(); + +// Check if SQL debugging is allowed +if (dev()->checkSqlDebugAllowed()) { + $debugInfo = dev()->getSqlDebugLog(); +} + +// Format SQL queries for display +$formattedQuery = dev()->formatShortQuery($sql, true); // HTML escaped +$plainQuery = dev()->formatShortQuery($sql, false); // Plain text +``` + +#### New Instance Methods +```php +// Access Whoops instance directly +$whoops = dev()->getWhoops(); + +// Check debug mode status +if (dev()->isDebugEnabled()) { + // Debug mode is active +} + +// Check environment +if (dev()->isLocalEnvironment()) { + // Running in local development +} +``` + +### Backward Compatibility + +All existing static method calls continue to work exactly as before: + +```php +// This still works - backward compatibility maintained +$sqlLog = \TorrentPier\Dev::getSqlLog(); +$isDebugAllowed = \TorrentPier\Dev::sqlDebugAllowed(); +$shortQuery = \TorrentPier\Dev::shortQuery($sql); + +// But this is now preferred +$sqlLog = dev()->getSqlDebugLog(); +$isDebugAllowed = dev()->checkSqlDebugAllowed(); +$shortQuery = dev()->formatShortQuery($sql); +``` + +### Performance Benefits + +- **Single Instance**: Only one debugging instance across the entire application +- **Resource Efficiency**: Whoops handlers initialized once and reused +- **Memory Optimization**: Shared debugging state and configuration +- **Lazy Loading**: Debug features only activated when needed + +### Advanced Usage + +```php +// Access the singleton directly +$devInstance = \TorrentPier\Dev::getInstance(); + +// Initialize the system (called automatically in common.php) +\TorrentPier\Dev::init(); + +// Get detailed environment information +$environment = [ + 'debug_enabled' => dev()->isDebugEnabled(), + 'local_environment' => dev()->isLocalEnvironment(), + 'sql_debug_allowed' => dev()->sqlDebugAllowed(), +]; +``` + +## ⚠️ Breaking Changes + +### Database Layer Changes +- **✅ No Breaking Changes**: All existing `DB()->method()` calls work exactly as before +- **Removed Files**: `src/Legacy/SqlDb.php` and `src/Legacy/Dbs.php` (replaced by modern implementation) +- **New Implementation**: Uses Nette Database v3.2 internally with full backward compatibility + +### Deprecated Functions +- `get_config()` → Use `config()->get()` +- `set_config()` → Use `config()->set()` +- Direct `$bb_cfg` access → Use `config()` methods + +### Deprecated Patterns +- `new TorrentPier\Censor()` → Use `censor()` global function +- Direct `$wordCensor` access → Use `censor()` methods +- `new TorrentPier\Dev()` → Use `dev()` global function +- Static `Dev::` methods → Use `dev()` instance methods +- `\TorrentPier\Legacy\Select::` → Use `\TorrentPier\Legacy\Common\Select::` + +### File Structure Changes +- New `/src/Database/` directory for modern database classes +- New `/src/` directory for modern PHP classes +- Reorganized template structure + +### Template Changes +- Updated template syntax in some areas +- New template variables available +- Deprecated template functions + +## 📋 Best Practices + +### Configuration Management +```php +// ✅ Always provide defaults +$timeout = config()->get('api.timeout', 30); + +// ✅ Use type hints +function getMaxUploadSize(): int { + return (int) config()->get('upload.max_size', 10485760); +} + +// ✅ Cache frequently used values +class TrackerService { + private string $announceUrl; + + public function __construct() { + $this->announceUrl = config()->get('bt_announce_url'); + } +} +``` + +### Censor Management +```php +// ✅ Check if censoring is enabled before processing +function processUserInput(string $text): string { + if (censor()->isEnabled()) { + return censor()->censorString($text); + } + return $text; +} + +// ✅ Use the singleton consistently +$censoredText = censor()->censorString($input); +``` + +### Select Usage +```php +// ✅ Use the new namespace consistently +$languageSelect = \TorrentPier\Legacy\Common\Select::language($currentLang, 'language_field'); + +// ✅ Store frequently used selects +class AdminPanel { + private string $languageSelect; + private string $timezoneSelect; + + public function __construct() { + $this->languageSelect = \TorrentPier\Legacy\Common\Select::language('', 'default_lang'); + $this->timezoneSelect = \TorrentPier\Legacy\Common\Select::timezone('', 'timezone'); + } +} +``` + +### Development and Debugging +```php +// ✅ Use instance methods for debugging +if (dev()->checkSqlDebugAllowed()) { + $debugLog = dev()->getSqlDebugLog(); +} + +// ✅ Access debugging utilities consistently +function formatSqlForDisplay(string $sql): string { + return dev()->formatShortQuery($sql, true); +} + +// ✅ Check environment properly +if (dev()->isLocalEnvironment()) { + // Development-specific code +} +class ForumPost { + public function getDisplayText(): string { + return censor()->censorString($this->text); + } +} + +// ✅ Add runtime words when needed +function setupCustomCensoring(): void { + if (isCustomModeEnabled()) { + censor()->addWord('custombad*', '[censored]'); + } +} +``` + +### Error Handling +```php +// ✅ Graceful error handling +try { + $dbConfig = config()->getSection('database'); + // Database operations +} catch (Exception $e) { + error_log("Database configuration error: " . $e->getMessage()); + // Fallback behavior +} +``` + +### Performance Optimization +```php +// ✅ Minimize configuration calls in loops +$cacheEnabled = config()->get('cache.enabled', false); +for ($i = 0; $i < 1000; $i++) { + if ($cacheEnabled) { + // Use cached value + } +} +``` + +### Security Considerations +```php +// ✅ Validate configuration values +$maxFileSize = min( + config()->get('upload.max_size', 1048576), + 1048576 * 100 // Hard limit: 100MB +); + +// ✅ Sanitize user-configurable values +$siteName = htmlspecialchars(config()->get('sitename', 'TorrentPier')); +``` + +### Testing and Quality Assurance +```bash +# ✅ Run tests before deploying changes +./vendor/bin/pest + +# ✅ Validate test coverage for new components +./vendor/bin/pest --coverage +``` + +For comprehensive testing documentation and best practices, see [tests/README.md](tests/README.md). + +--- + +**Important**: Always test the upgrade process in a staging environment before applying it to production. Keep backups of your database and files until you're confident the upgrade was successful. + +For additional support, visit our [Official Forum](https://torrentpier.com) or check our [GitHub Repository](https://github.com/torrentpier/torrentpier) for the latest updates and community discussions. diff --git a/_cleanup.php b/_cleanup.php new file mode 100644 index 000000000..d9802822a --- /dev/null +++ b/_cleanup.php @@ -0,0 +1,57 @@ +php ' . basename(__FILE__) . ' in CLI mode'); +} + +// Get all constants +require_once BB_ROOT . 'library/defines.php'; + +// Include CLI functions +require INC_DIR . '/functions_cli.php'; + +// Welcoming message +out("--- Release creation tool ---\n", 'info'); + +$configFile = BB_PATH . '/library/config.php'; + +if (!is_file($configFile)) { + out('- Config file ' . basename($configFile) . ' not found', 'error'); + exit; +} +if (!is_readable($configFile)) { + out('- Config file ' . basename($configFile) . ' is not readable', 'error'); + exit; +} +if (!is_writable($configFile)) { + out('- Config file ' . basename($configFile) . ' is not writable', 'error'); + exit; +} + +// Ask for version +fwrite(STDOUT, 'Enter version number (e.g, v2.4.0): '); +$version = trim(fgets(STDIN)); + +if (empty($version)) { + out("- Version cannot be empty. Please enter a valid version number", 'error'); + exit; +} else { + // Add 'v' prefix if missing + if (!str_starts_with($version, 'v')) { + $version = 'v' . $version; + } + + out("- Using version: $version", 'info'); +} + +// Ask for version emoji +fwrite(STDOUT, 'Enter version emoji: '); +$versionEmoji = trim(fgets(STDIN)); + +if (!empty($versionEmoji)) { + out("- Using version emoji: $versionEmoji", 'info'); +} + +// Ask for release date or use today's date +fwrite(STDOUT, "Enter release date (e.g. 25-05-2025), leave empty to use today's date: "); +$date = trim(fgets(STDIN)); + +if (empty($date)) { + $date = date('d-m-Y'); + out("- Using current date: $date", 'info'); +} else { + // Validate date format (dd-mm-yyyy) + $dateObj = DateTime::createFromFormat('d-m-Y', $date); + if (!$dateObj || $dateObj->format('d-m-Y') !== $date) { + out("- Invalid date format. Expected format: DD-MM-YYYY", 'error'); + exit; + } + + out("- Using date: $date", 'info'); +} + +// Read config file content +$content = file_get_contents($configFile); + +// Update version +$content = preg_replace( + "/\\\$bb_cfg\['tp_version'\]\s*=\s*'[^']*';/", + "\$bb_cfg['tp_version'] = '$version';", + $content +); + +// Update release date +$content = preg_replace( + "/\\\$bb_cfg\['tp_release_date'\]\s*=\s*'[^']*';/", + "\$bb_cfg['tp_release_date'] = '$date';", + $content +); + +// Save updated config +$bytesWritten = file_put_contents($configFile, $content); + +if ($bytesWritten === false) { + out("- Failed to write to config file", 'error'); + exit; +} + +if ($bytesWritten === 0) { + out("- Config file was not updated (0 bytes written)", 'error'); + exit; +} + +out("\n- Config file has been updated!", 'success'); + +// Update CHANGELOG.md +runProcess('npx git-cliff v2.4.6-alpha.4.. --config cliff.toml --tag "' . $version . '" > CHANGELOG.md'); + +// Git add & commit +runProcess('git add -A && git commit -m "release: ' . escapeshellarg($version) . (!empty($versionEmoji) ? (' ' . $versionEmoji) : '') . '"'); + +// Git tag +runProcess("git tag -a \"$version\" -m \"Release $version\""); +runProcess("git tag -v \"$version\""); + +// Git push +runProcess("git push origin master"); +runProcess("git push origin $version"); + +out("\n- Release $version has been successfully prepared, committed and pushed!", 'success'); diff --git a/admin/admin_attach_cp.php b/admin/admin_attach_cp.php index 274b673bb..a7f1ab498 100644 --- a/admin/admin_attach_cp.php +++ b/admin/admin_attach_cp.php @@ -1,556 +1,477 @@ get('topics_per_page'); + break; + case 'attachments': + $order_by = 'ORDER BY total_attachments ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + case 'filesize': + $order_by = 'ORDER BY total_size ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + default: + $mode = 'attachments'; + $sort_order = 'DESC'; + $order_by = 'ORDER BY total_attachments ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + } +} elseif ($view === 'attachments') { + switch ($mode) { + case 'real_filename': + $order_by = 'ORDER BY a.real_filename ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + case 'comment': + $order_by = 'ORDER BY a.comment ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + case 'extension': + $order_by = 'ORDER BY a.extension ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + case 'filesize': + $order_by = 'ORDER BY a.filesize ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + case 'downloads': + $order_by = 'ORDER BY a.download_count ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + case 'post_time': + $order_by = 'ORDER BY a.filetime ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + default: + $mode = 'a.real_filename'; + $sort_order = 'ASC'; + $order_by = 'ORDER BY a.real_filename ' . $sort_order . ' LIMIT ' . $start . ', ' . config()->get('topics_per_page'); + break; + } } // Set select fields -$view_types_text = array($lang['VIEW_STATISTIC'], $lang['VIEW_SEARCH']); -$view_types = array('stats', 'search'); +$view_types_text = [$lang['VIEW_STATISTIC'], $lang['VIEW_SEARCH']]; +$view_types = ['stats', 'search']; +$select_view = ''; -$select_view = ''; + for ($i = 0, $iMax = count($view_types_text); $i < $iMax; $i++) { + $selected = ($view === $view_types[$i]) ? ' selected' : ''; + $select_view .= ''; + } + $select_view .= ''; } -$select_view .= ''; -if (count($mode_types_text) > 0) -{ - $select_sort_mode = ''; +if (count($mode_types_text) > 0 && !empty($mode_types)) { + $select_sort_mode = ''; } $select_sort_order = ''; -$submit_change = ( isset($_POST['submit_change']) ) ? TRUE : FALSE; -$delete = ( isset($_POST['delete']) ) ? TRUE : FALSE; -$delete_id_list = get_var('delete_id_list', array(0)); +$submit_change = isset($_POST['submit_change']); +$delete = isset($_POST['delete']); +$delete_id_list = get_var('delete_id_list', [0]); $confirm = isset($_POST['confirm']); -if ($confirm && sizeof($delete_id_list) > 0) -{ - $attachments = array(); +if ($confirm && count($delete_id_list) > 0) { + $attachments = []; - delete_attachment(0, $delete_id_list); -} -else if ($delete && sizeof($delete_id_list) > 0) -{ - // Not confirmed, show confirmation message - $hidden_fields = ''; - $hidden_fields .= ''; - $hidden_fields .= ''; - $hidden_fields .= ''; - $hidden_fields .= ''; + delete_attachment(0, $delete_id_list); +} elseif ($delete && count($delete_id_list) > 0) { + // Not confirmed, show confirmation message + $hidden_fields = ''; + $hidden_fields .= ''; + $hidden_fields .= ''; + $hidden_fields .= ''; + $hidden_fields .= ''; - for ($i = 0; $i < sizeof($delete_id_list); $i++) - { - $hidden_fields .= ''; - } + foreach ($delete_id_list as $iValue) { + $hidden_fields .= ''; + } - print_confirmation(array( - 'FORM_ACTION' => "admin_attach_cp.php", - 'HIDDEN_FIELDS' => $hidden_fields, - )); + print_confirmation([ + 'FORM_ACTION' => 'admin_attach_cp.php', + 'HIDDEN_FIELDS' => $hidden_fields, + ]); } // Assign Default Template Vars -$template->assign_vars(array( - 'S_VIEW_SELECT' => $select_view, - 'S_MODE_ACTION' => 'admin_attach_cp.php', -)); +$template->assign_vars([ + 'S_VIEW_SELECT' => $select_view, + 'S_MODE_ACTION' => 'admin_attach_cp.php?view=' . $view . '&mode=' . $mode . '&order=' . $sort_order . '&uid=' . $uid +]); -if ($submit_change && $view == 'attachments') -{ - $attach_change_list = get_var('attach_id_list', array(0)); - $attach_comment_list = get_var('attach_comment_list', array('')); - $attach_download_count_list = get_var('attach_count_list', array(0)); +if ($submit_change && $view === 'attachments') { + $attach_change_list = get_var('attach_id_list', [0]); + $attach_comment_list = get_var('attach_comment_list', ['']); + $attach_download_count_list = get_var('attach_count_list', [0]); - // Generate correct Change List - $attachments = array(); + // Generate correct Change List + $attachments = []; - for ($i = 0; $i < count($attach_change_list); $i++) - { - $attachments['_' . $attach_change_list[$i]]['comment'] = $attach_comment_list[$i]; - $attachments['_' . $attach_change_list[$i]]['download_count'] = $attach_download_count_list[$i]; - } + for ($i = 0, $iMax = count($attach_change_list); $i < $iMax; $i++) { + $attachments['_' . $attach_change_list[$i]]['comment'] = $attach_comment_list[$i]; + $attachments['_' . $attach_change_list[$i]]['download_count'] = $attach_download_count_list[$i]; + } - $sql = 'SELECT * + $sql = 'SELECT * FROM ' . BB_ATTACHMENTS_DESC . ' ORDER BY attach_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get attachment informations'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get attachment informations'); + } - while ( $attachrow = DB()->sql_fetchrow($result) ) - { - if ( isset($attachments['_' . $attachrow['attach_id']]) ) - { - if ($attachrow['comment'] != $attachments['_' . $attachrow['attach_id']]['comment'] || $attachrow['download_count'] != $attachments['_' . $attachrow['attach_id']]['download_count']) - { - $sql = "UPDATE " . BB_ATTACHMENTS_DESC . " - SET comment = '" . attach_mod_sql_escape($attachments['_' . $attachrow['attach_id']]['comment']) . "', download_count = " . (int) $attachments['_' . $attachrow['attach_id']]['download_count'] . " - WHERE attach_id = " . (int) $attachrow['attach_id']; + while ($attachrow = DB()->sql_fetchrow($result)) { + if (isset($attachments['_' . $attachrow['attach_id']])) { + if ($attachrow['comment'] != $attachments['_' . $attachrow['attach_id']]['comment'] || $attachrow['download_count'] != $attachments['_' . $attachrow['attach_id']]['download_count']) { + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . " + SET comment = '" . DB()->escape($attachments['_' . $attachrow['attach_id']]['comment']) . "', download_count = " . (int)$attachments['_' . $attachrow['attach_id']]['download_count'] . ' + WHERE attach_id = ' . (int)$attachrow['attach_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update attachments informations'); - } - } - } - } - DB()->sql_freeresult($result); + if (!DB()->sql_query($sql)) { + bb_die('Could not update attachments informations'); + } + } + } + } + DB()->sql_freeresult($result); } // Statistics -if ($view == 'stats') -{ - $upload_dir_size = get_formatted_dirsize(); +if ($view == 'stats') { + $upload_dir_size = get_formatted_dirsize(); - $attachment_quota = humn_size($attach_config['attachment_quota']); + $attachment_quota = humn_size($attach_config['attachment_quota']); - // number_of_attachments - $row = DB()->fetch_row(" - SELECT COUNT(*) AS total FROM ". BB_ATTACHMENTS_DESC ." - "); - $number_of_attachments = $number_of_posts = $row['total']; + // number_of_attachments + $row = DB()->fetch_row('SELECT COUNT(*) AS total FROM ' . BB_ATTACHMENTS_DESC); + $number_of_attachments = $number_of_posts = $row['total']; - $number_of_pms = 0; + $number_of_pms = 0; - // number_of_topics - $row = DB()->fetch_row(" - SELECT COUNT(*) AS topics FROM ". BB_TOPICS ." WHERE topic_attachment = 1 - "); - $number_of_topics = $row['topics']; + // number_of_topics + $row = DB()->fetch_row('SELECT COUNT(*) AS topics FROM ' . BB_TOPICS . ' WHERE topic_attachment = 1'); + $number_of_topics = $row['topics']; - // number_of_users - $row = DB()->fetch_row(" - SELECT COUNT(DISTINCT user_id_1) AS users FROM ". BB_ATTACHMENTS ." WHERE post_id != 0 - "); - $number_of_users = $row['users']; - - $template->assign_vars(array( - 'TPL_ATTACH_STATISTICS' => true, - 'TOTAL_FILESIZE' => $upload_dir_size, - 'ATTACH_QUOTA' => $attachment_quota, - 'NUMBER_OF_ATTACHMENTS' => $number_of_attachments, - 'NUMBER_OF_POSTS' => $number_of_posts, - 'NUMBER_OF_PMS' => $number_of_pms, - 'NUMBER_OF_TOPICS' => $number_of_topics, - 'NUMBER_OF_USERS' => $number_of_users, - )); + // number_of_users + $row = DB()->fetch_row('SELECT COUNT(DISTINCT user_id_1) AS users FROM ' . BB_ATTACHMENTS . ' WHERE post_id != 0'); + $number_of_users = $row['users']; + $template->assign_vars([ + 'TPL_ATTACH_STATISTICS' => true, + 'TOTAL_FILESIZE' => $upload_dir_size, + 'ATTACH_QUOTA' => $attachment_quota, + 'NUMBER_OF_ATTACHMENTS' => $number_of_attachments, + 'NUMBER_OF_POSTS' => $number_of_posts, + 'NUMBER_OF_PMS' => $number_of_pms, + 'NUMBER_OF_TOPICS' => $number_of_topics, + 'NUMBER_OF_USERS' => $number_of_users, + ]); } // Search -if ($view == 'search') -{ - // Get Forums and Categories - //sf - add [, f.forum_parent] - $sql = "SELECT c.cat_title, c.cat_id, f.forum_name, f.forum_id, f.forum_parent - FROM " . BB_CATEGORIES . " c, " . BB_FORUMS . " f +if ($view === 'search') { + // Get Forums and Categories + //sf - add [, f.forum_parent] + $sql = 'SELECT c.cat_title, c.cat_id, f.forum_name, f.forum_id, f.forum_parent + FROM ' . BB_CATEGORIES . ' c, ' . BB_FORUMS . ' f WHERE f.cat_id = c.cat_id - ORDER BY c.cat_id, f.forum_order"; + ORDER BY c.cat_id, f.forum_order'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not obtain forum_name / forum_id'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain forum_name / forum_id'); + } - $s_forums = ''; - while ($row = DB()->sql_fetchrow($result)) - { //sf - $s_forums .= ''; + $s_forums = ''; + $list_cat = []; + while ($row = DB()->sql_fetchrow($result)) { //sf + $s_forums .= ''; - if( empty($list_cat[$row['cat_id']]) ) - { - $list_cat[$row['cat_id']] = $row['cat_title']; - } - } + if (empty($list_cat[$row['cat_id']])) { + $list_cat[$row['cat_id']] = $row['cat_title']; + } + } - if( $s_forums != '' ) - { - $s_forums = '' . $s_forums; + $s_categories = ''; + if ($s_forums) { + $s_forums = '' . $s_forums; - // Category to search - $s_categories = ''; + // Category to search + $s_categories = ''; - foreach ($list_cat as $cat_id => $cat_title) - { - $s_categories .= ''; - } - } - else - { - bb_die($lang['NO_SEARCHABLE_FORUMS']); - } + foreach ($list_cat as $cat_id => $cat_title) { + $s_categories .= ''; + } + } else { + bb_die($lang['NO_SEARCHABLE_FORUMS']); + } - $template->assign_vars(array( - 'TPL_ATTACH_SEARCH' => true, - 'S_FORUM_OPTIONS' => $s_forums, - 'S_CATEGORY_OPTIONS' => $s_categories, - 'S_SORT_OPTIONS' => $select_sort_mode, - 'S_SORT_ORDER' => $select_sort_order, - )); + $template->assign_vars([ + 'TPL_ATTACH_SEARCH' => true, + 'S_FORUM_OPTIONS' => $s_forums, + 'S_CATEGORY_OPTIONS' => $s_categories, + 'S_SORT_OPTIONS' => $select_sort_mode, + 'S_SORT_ORDER' => $select_sort_order, + ]); } // Username -if ($view == 'username') -{ - $template->assign_vars(array( - 'TPL_ATTACH_USER' => true, - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, - )); - $total_rows = 0; - bb_die('removed'); +if ($view === 'username') { + $template->assign_vars([ + 'TPL_ATTACH_USER' => true, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, + ]); + $total_rows = 0; + bb_die('removed'); } // Attachments -if ($view == 'attachments') -{ - $user_based = ($uid) ? TRUE : FALSE; - $search_based = (isset($_POST['search']) && $_POST['search']) ? TRUE : FALSE; +if ($view === 'attachments') { + $user_based = (bool)$uid; + $search_based = (isset($_POST['search']) && $_POST['search']); - $hidden_fields = ''; + $hidden_fields = ''; - $template->assign_vars(array( - 'TPL_ATTACH_ATTACHMENTS' => true, - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, - )); + $template->assign_vars([ + 'TPL_ATTACH_ATTACHMENTS' => true, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, + ]); - $total_rows = 0; + $total_rows = 0; - // Are we called from Username ? - if ($user_based) - { - $sql = "SELECT username FROM " . BB_USERS . " WHERE user_id = " . intval($uid); + // Are we called from Username ? + if ($user_based) { + $sql = 'SELECT username FROM ' . BB_USERS . ' WHERE user_id = ' . (int)$uid; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Error getting username'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Error getting username'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - $username = $row['username']; + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); + $username = $row['username']; - $s_hidden = ''; + $s_hidden = ''; - $template->assign_block_vars('switch_user_based', array()); + $template->assign_block_vars('switch_user_based', []); - $template->assign_vars(array( - 'S_USER_HIDDEN' => $s_hidden, - 'L_STATISTICS_FOR_USER' => sprintf($lang['STATISTICS_FOR_USER'], $username), - )); + $template->assign_vars([ + 'S_USER_HIDDEN' => $s_hidden, + 'L_STATISTICS_FOR_USER' => sprintf($lang['STATISTICS_FOR_USER'], $username), + ]); - $sql = "SELECT attach_id - FROM " . BB_ATTACHMENTS . " - WHERE user_id_1 = " . intval($uid) . " - GROUP BY attach_id"; + $sql = 'SELECT attach_id + FROM ' . BB_ATTACHMENTS . ' + WHERE user_id_1 = ' . (int)$uid . ' + GROUP BY attach_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #1'); + } - $attach_ids = DB()->sql_fetchrowset($result); - $num_attach_ids = DB()->num_rows($result); - DB()->sql_freeresult($result); + $attach_ids = DB()->sql_fetchrowset($result); + $num_attach_ids = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_attach_ids == 0) - { - bb_die('For some reason no attachments are assigned to the user ' . $username); - } + if ($num_attach_ids == 0) { + bb_die('For some reason no attachments are assigned to the user ' . $username); + } - $total_rows = $num_attach_ids; + $total_rows = $num_attach_ids; - $attach_id = array(); + $attach_id = []; - for ($j = 0; $j < $num_attach_ids; $j++) - { - $attach_id[] = intval($attach_ids[$j]['attach_id']); - } + for ($j = 0; $j < $num_attach_ids; $j++) { + $attach_id[] = (int)$attach_ids[$j]['attach_id']; + } - $sql = "SELECT a.* - FROM " . BB_ATTACHMENTS_DESC . " a - WHERE a.attach_id IN (" . implode(', ', $attach_id) . ") " . - $order_by; + $sql = 'SELECT a.* + FROM ' . BB_ATTACHMENTS_DESC . ' a + WHERE a.attach_id IN (' . implode(', ', $attach_id) . ') ' . + $order_by; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #2'); + } - $attachments = DB()->sql_fetchrowset($result); - $num_attach = DB()->num_rows($result); - DB()->sql_freeresult($result); - } - else - { - // we are called from search - $attachments = search_attachments($order_by, $total_rows); - } + $attachments = DB()->sql_fetchrowset($result); + $num_attach = DB()->num_rows($result); + DB()->sql_freeresult($result); + } else { + // we are called from search + $attachments = search_attachments($order_by, $total_rows); + } - if (sizeof($attachments) > 0) - { - for ($i = 0; $i < sizeof($attachments); $i++) - { - $delete_box = ''; + if (count($attachments) > 0) { + for ($i = 0, $iMax = count($attachments); $i < $iMax; $i++) { + $delete_box = ''; - for ($j = 0; $j < count($delete_id_list); $j++) - { - if ($delete_id_list[$j] == $attachments[$i]['attach_id']) - { - $delete_box = ''; - break; - } - } + foreach ($delete_id_list as $jValue) { + if ($jValue == $attachments[$i]['attach_id']) { + $delete_box = ''; + break; + } + } - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - // Is the Attachment assigned to more than one post ? - // If it's not assigned to any post, it's an private message thingy. ;) - $post_titles = array(); + // Is the Attachment assigned to more than one post ? + // If it's not assigned to any post, it's an private message thingy. ;) + $post_titles = []; - $sql = "SELECT * - FROM " . BB_ATTACHMENTS . " - WHERE attach_id = " . intval($attachments[$i]['attach_id']); + $sql = 'SELECT * + FROM ' . BB_ATTACHMENTS . ' + WHERE attach_id = ' . (int)$attachments[$i]['attach_id']; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #3'); + } - $ids = DB()->sql_fetchrowset($result); - $num_ids = DB()->num_rows($result); - DB()->sql_freeresult($result); + $ids = DB()->sql_fetchrowset($result); + $num_ids = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($j = 0; $j < $num_ids; $j++) - { - if ($ids[$j]['post_id'] != 0) - { - $sql = "SELECT t.topic_title - FROM " . BB_TOPICS . " t, " . BB_POSTS . " p - WHERE p.post_id = " . intval($ids[$j]['post_id']) . " AND p.topic_id = t.topic_id - GROUP BY t.topic_id, t.topic_title"; + for ($j = 0; $j < $num_ids; $j++) { + if ($ids[$j]['post_id'] != 0) { + $sql = 'SELECT t.topic_title + FROM ' . BB_TOPICS . ' t, ' . BB_POSTS . ' p + WHERE p.post_id = ' . (int)$ids[$j]['post_id'] . ' AND p.topic_id = t.topic_id + GROUP BY t.topic_id, t.topic_title'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query topic'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query topic'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - $post_title = $row['topic_title']; + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); + $post_title = str_short($row['topic_title'], 30); - if (strlen($post_title) > 32) - { - $post_title = str_short($post_title, 30); - } + $view_topic = BB_ROOT . POST_URL . $ids[$j]['post_id'] . '#' . $ids[$j]['post_id']; - $view_topic = BB_ROOT . 'viewtopic.php?' . POST_POST_URL . '=' . $ids[$j]['post_id'] . '#' . $ids[$j]['post_id']; + $post_titles[] = '' . $post_title . ''; + } else { + $post_titles[] = $lang['PRIVATE_MESSAGE']; + } + } - $post_titles[] = '' . $post_title . ''; - } - else - { - $post_titles[] = $lang['PRIVATE_MESSAGE']; - } - } + $post_titles = implode('
', $post_titles); - $post_titles = implode('
', $post_titles); + $hidden_field = ''; - $hidden_field = ''; + $template->assign_block_vars('attachrow', [ + 'ROW_NUMBER' => $i + (@$_GET['start'] + 1), + 'ROW_CLASS' => $row_class, - $template->assign_block_vars('attachrow', array( - 'ROW_NUMBER' => $i + ( @$_GET['start'] + 1 ), - 'ROW_CLASS' => $row_class, + 'FILENAME' => htmlspecialchars($attachments[$i]['real_filename']), + 'COMMENT' => htmlspecialchars($attachments[$i]['comment']), + 'EXTENSION' => $attachments[$i]['extension'], + 'SIZE' => humn_size($attachments[$i]['filesize'], 2), + 'DOWNLOAD_COUNT' => $attachments[$i]['download_count'], + 'POST_TIME' => bb_date($attachments[$i]['filetime']), + 'POST_TITLE' => $post_titles, - 'FILENAME' => htmlspecialchars($attachments[$i]['real_filename']), - 'COMMENT' => htmlspecialchars($attachments[$i]['comment']), - 'EXTENSION' => $attachments[$i]['extension'], - 'SIZE' => round(($attachments[$i]['filesize'] / 1024), 2), - 'DOWNLOAD_COUNT' => $attachments[$i]['download_count'], - 'POST_TIME' => bb_date($attachments[$i]['filetime']), - 'POST_TITLE' => $post_titles, + 'S_DELETE_BOX' => $delete_box, + 'S_HIDDEN' => $hidden_field, + 'U_VIEW_ATTACHMENT' => BB_ROOT . DL_URL . $attachments[$i]['attach_id'], + ]); + } + } - 'S_DELETE_BOX' => $delete_box, - 'S_HIDDEN' => $hidden_field, - 'U_VIEW_ATTACHMENT' => BB_ROOT . DOWNLOAD_URL . $attachments[$i]['attach_id'], - )); + if (!$search_based && !$user_based) { + if (!$attachments) { + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS_DESC; - } - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment description table'); + } - if (!$search_based && !$user_based) - { - if ($total_attachments == 0) - { - $sql = "SELECT attach_id FROM " . BB_ATTACHMENTS_DESC; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachment description table'); - } - - $total_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); - } - } + $total_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); + } + } } // Generate Pagination -if ($do_pagination && $total_rows > $bb_cfg['topics_per_page']) -{ - generate_pagination('admin_attach_cp.php?view=' . $view . '&mode=' . $mode . '&order=' . $sort_order . '&uid=' . $uid, $total_rows, $bb_cfg['topics_per_page'], $start).' '; +if ($do_pagination && $total_rows > config()->get('topics_per_page')) { + generate_pagination('admin_attach_cp.php?view=' . $view . '&mode=' . $mode . '&order=' . $sort_order . '&uid=' . $uid, $total_rows, config()->get('topics_per_page'), $start); } -print_page('admin_attach_cp.tpl', 'admin'); \ No newline at end of file +print_page('admin_attach_cp.tpl', 'admin'); diff --git a/admin/admin_attachments.php b/admin/admin_attachments.php index 3d0d93356..9ee6c129c 100644 --- a/admin/admin_attachments.php +++ b/admin/admin_attachments.php @@ -1,149 +1,124 @@ sql_query($sql)) -{ - bb_die('Could not find attachment config table #1'); +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not find attachment config table #1'); } -while ($row = DB()->sql_fetchrow($result)) -{ - $config_name = $row['config_name']; - $config_value = $row['config_value']; +while ($row = DB()->sql_fetchrow($result)) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; - $new_attach[$config_name] = get_var($config_name, trim($attach_config[$config_name])); + $new_attach[$config_name] = get_var($config_name, trim($attach_config[$config_name])); - if (!$size && !$submit && $config_name == 'max_filesize') - { - $size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); - } + if (!$size && !$submit && $config_name == 'max_filesize') { + $size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); + } - if (!$quota_size && !$submit && $config_name == 'attachment_quota') - { - $quota_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); - } + if (!$quota_size && !$submit && $config_name == 'attachment_quota') { + $quota_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); + } - if (!$pm_size && !$submit && $config_name == 'max_filesize_pm') - { - $pm_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); - } + if (!$pm_size && !$submit && $config_name == 'max_filesize_pm') { + $pm_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); + } - if (!$submit && ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm')) - { - if ($new_attach[$config_name] >= 1048576) - { - $new_attach[$config_name] = round($new_attach[$config_name] / 1048576 * 100) / 100; - } - else if ($new_attach[$config_name] >= 1024) - { - $new_attach[$config_name] = round($new_attach[$config_name] / 1024 * 100) / 100; - } - } + if (!$submit && ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm')) { + if ($new_attach[$config_name] >= 1048576) { + $new_attach[$config_name] = round($new_attach[$config_name] / 1048576 * 100) / 100; + } elseif ($new_attach[$config_name] >= 1024) { + $new_attach[$config_name] = round($new_attach[$config_name] / 1024 * 100) / 100; + } + } - if ( $submit && ( $mode == 'manage' || $mode == 'cats') ) - { - if ($config_name == 'max_filesize') - { - $old = $new_attach[$config_name]; - $new_attach[$config_name] = ( $size == 'kb' ) ? round($new_attach[$config_name] * 1024) : ( ($size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name] ); - } + if ($submit && ($mode == 'manage' || $mode == 'cats')) { + if ($config_name == 'max_filesize') { + $old = $new_attach[$config_name]; + $new_attach[$config_name] = ($size == 'kb') ? round($new_attach[$config_name] * 1024) : (($size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name]); + } - if ($config_name == 'attachment_quota') - { - $old = $new_attach[$config_name]; - $new_attach[$config_name] = ( $quota_size == 'kb' ) ? round($new_attach[$config_name] * 1024) : ( ($quota_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name] ); - } + if ($config_name == 'attachment_quota') { + $old = $new_attach[$config_name]; + $new_attach[$config_name] = ($quota_size == 'kb') ? round($new_attach[$config_name] * 1024) : (($quota_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name]); + } - if ($config_name == 'max_filesize_pm') - { - $old = $new_attach[$config_name]; - $new_attach[$config_name] = ( $pm_size == 'kb' ) ? round($new_attach[$config_name] * 1024) : ( ($pm_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name] ); - } + if ($config_name == 'max_filesize_pm') { + $old = $new_attach[$config_name]; + $new_attach[$config_name] = ($pm_size == 'kb') ? round($new_attach[$config_name] * 1024) : (($pm_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name]); + } - if ($config_name == 'max_filesize') - { - $old_size = $attach_config[$config_name]; - $new_size = $new_attach[$config_name]; + if ($config_name == 'max_filesize') { + $old_size = $attach_config[$config_name]; + $new_size = $new_attach[$config_name]; - if ($old_size != $new_size) - { - // See, if we have a similar value of old_size in Mime Groups. If so, update these values. - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' - SET max_filesize = ' . (int) $new_size . ' - WHERE max_filesize = ' . (int) $old_size; + if ($old_size != $new_size) { + // See, if we have a similar value of old_size in Mime Groups. If so, update these values. + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' + SET max_filesize = ' . (int)$new_size . ' + WHERE max_filesize = ' . (int)$old_size; - if (!($result_2 = DB()->sql_query($sql))) - { - bb_die('Could not update extension group information'); - } + if (!($result_2 = DB()->sql_query($sql))) { + bb_die('Could not update extension group information'); + } + } - } + $sql = 'UPDATE ' . BB_ATTACH_CONFIG . " + SET config_value = '" . DB()->escape($new_attach[$config_name]) . "' + WHERE config_name = '" . DB()->escape($config_name) . "'"; + } else { + $sql = 'UPDATE ' . BB_ATTACH_CONFIG . " + SET config_value = '" . DB()->escape($new_attach[$config_name]) . "' + WHERE config_name = '" . DB()->escape($config_name) . "'"; + } - $sql = "UPDATE " . BB_ATTACH_CONFIG . " - SET config_value = '" . attach_mod_sql_escape($new_attach[$config_name]) . "' - WHERE config_name = '" . attach_mod_sql_escape($config_name) . "'"; - } - else - { - $sql = "UPDATE " . BB_ATTACH_CONFIG . " - SET config_value = '" . attach_mod_sql_escape($new_attach[$config_name]) . "' - WHERE config_name = '" . attach_mod_sql_escape($config_name) . "'"; - } + if (!DB()->sql_query($sql)) { + bb_die('Failed to update attachment configuration for ' . $config_name); + } - if (!DB()->sql_query($sql)) - { - bb_die('Failed to update attachment configuration for ' . $config_name); - } - - if ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm') - { - $new_attach[$config_name] = $old; - } - } + if ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm') { + $new_attach[$config_name] = $old; + } + } } DB()->sql_freeresult($result); @@ -154,566 +129,424 @@ $select_size_mode = size_select('size', $size); $select_quota_size_mode = size_select('quota_size', $quota_size); $select_pm_size_mode = size_select('pm_size', $pm_size); -// Search Imagick -if ($search_imagick) -{ - $imagick = ''; - - if (preg_match('/convert/i', $imagick)) - { - return true; - } - else if ($imagick != 'none') - { - if (!preg_match('/WIN/i', PHP_OS)) - { - $retval = @exec('whereis convert'); - $paths = explode(' ', $retval); - - if (is_array($paths)) - { - for ( $i=0; $i < sizeof($paths); $i++) - { - $path = basename($paths[$i]); - - if ($path == 'convert') - { - $imagick = $paths[$i]; - } - } - } - } - else if (preg_match('/WIN/i', PHP_OS)) - { - $path = 'c:/imagemagick/convert.exe'; - - if ( !@file_exists(@amod_realpath($path))) - { - $imagick = $path; - } - } - } - - if ( !@file_exists(@amod_realpath(trim($imagick)))) - { - $new_attach['img_imagick'] = trim($imagick); - } - else - { - $new_attach['img_imagick'] = ''; - } -} - // Check Settings -if ($check_upload) -{ - // Some tests... - $attach_config = array(); +if ($check_upload) { + // Some tests... + $attach_config = []; - $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; + $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not find attachment config table #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not find attachment config table #2'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); - } + for ($i = 0; $i < $num_rows; $i++) { + $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); + } - if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $upload_dir = $attach_config['upload_dir']; - } - else - { - $upload_dir = BB_ROOT . $attach_config['upload_dir']; - } + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $upload_dir = $attach_config['upload_dir']; + } else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; + } - $error = false; + $error = false; - // Does the target directory exist, is it a directory and writeable - if ( !@file_exists(@amod_realpath($upload_dir)) ) - { - $error = true; - $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $attach_config['upload_dir']) . '
'; - } + // Does the target directory exist, is it a directory and writeable + if (!@file_exists(realpath($upload_dir))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $attach_config['upload_dir']) . '
'; + } - if (!$error && !is_dir($upload_dir)) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $attach_config['upload_dir']) . '
'; - } + if (!$error && !is_dir($upload_dir)) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $attach_config['upload_dir']) . '
'; + } - if (!$error) - { - if ( !($fp = @fopen($upload_dir . '/0_000000.000', 'w')) ) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $attach_config['upload_dir']) . '
'; - } - else - { - @fclose($fp); - unlink_attach($upload_dir . '/0_000000.000'); - } - } + if (!$error) { + if (!($fp = @fopen($upload_dir . '/0_000000.000', 'wb+'))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $attach_config['upload_dir']) . '
'; + } else { + @fclose($fp); + unlink_attach($upload_dir . '/0_000000.000'); + } + } - if (!$error) - { - bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!$error) { + bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } // Management -if ($submit && $mode == 'manage') -{ - if (!$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } +if ($submit && $mode == 'manage') { + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'manage') -{ - $yes_no_switches = array('disable_mod', 'allow_pm_attach', 'display_order'); +if ($mode == 'manage') { + $template->assign_vars(array( + 'TPL_ATTACH_MANAGE' => true, + 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=manage', + 'S_FILESIZE' => $select_size_mode, + 'S_FILESIZE_QUOTA' => $select_quota_size_mode, + 'S_FILESIZE_PM' => $select_pm_size_mode, + 'S_DEFAULT_UPLOAD_LIMIT' => default_quota_limit_select('default_upload_quota', (int)trim($new_attach['default_upload_quota'])), + 'S_DEFAULT_PM_LIMIT' => default_quota_limit_select('default_pm_quota', (int)trim($new_attach['default_pm_quota'])), - for ($i = 0; $i < sizeof($yes_no_switches); $i++) - { - eval("\$" . $yes_no_switches[$i] . "_yes = ( \$new_attach['" . $yes_no_switches[$i] . "'] != '0' ) ? 'checked=\"checked\"' : '';"); - eval("\$" . $yes_no_switches[$i] . "_no = ( \$new_attach['" . $yes_no_switches[$i] . "'] == '0' ) ? 'checked=\"checked\"' : '';"); - } - - $template->assign_vars(array( - 'TPL_ATTACH_MANAGE' => true, - 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=manage', - 'S_FILESIZE' => $select_size_mode, - 'S_FILESIZE_QUOTA' => $select_quota_size_mode, - 'S_FILESIZE_PM' => $select_pm_size_mode, - 'S_DEFAULT_UPLOAD_LIMIT' => default_quota_limit_select('default_upload_quota', intval(trim($new_attach['default_upload_quota']))), - 'S_DEFAULT_PM_LIMIT' => default_quota_limit_select('default_pm_quota', intval(trim($new_attach['default_pm_quota']))), - - 'UPLOAD_DIR' => $new_attach['upload_dir'], - 'ATTACHMENT_IMG_PATH' => $new_attach['upload_img'], - 'TOPIC_ICON' => $new_attach['topic_icon'], - 'MAX_FILESIZE' => $new_attach['max_filesize'], - 'ATTACHMENT_QUOTA' => $new_attach['attachment_quota'], - 'MAX_FILESIZE_PM' => $new_attach['max_filesize_pm'], - 'MAX_ATTACHMENTS' => $new_attach['max_attachments'], - 'MAX_ATTACHMENTS_PM' => $new_attach['max_attachments_pm'], - 'DISABLE_MOD_YES' => $disable_mod_yes, - 'DISABLE_MOD_NO' => $disable_mod_no, - 'PM_ATTACH_YES' => $allow_pm_attach_yes, - 'PM_ATTACH_NO' => $allow_pm_attach_no, - 'DISPLAY_ORDER_ASC' => $display_order_yes, - 'DISPLAY_ORDER_DESC' => $display_order_no, - )); + 'UPLOAD_DIR' => $new_attach['upload_dir'], + 'ATTACHMENT_IMG_PATH' => $new_attach['upload_img'], + 'TOPIC_ICON' => $new_attach['topic_icon'], + 'MAX_FILESIZE' => $new_attach['max_filesize'], + 'ATTACHMENT_QUOTA' => $new_attach['attachment_quota'], + 'MAX_FILESIZE_PM' => $new_attach['max_filesize_pm'], + 'MAX_ATTACHMENTS' => $new_attach['max_attachments'], + 'MAX_ATTACHMENTS_PM' => $new_attach['max_attachments_pm'], + 'DISABLE_MOD_YES' => $new_attach['disable_mod'] !== '0' ? 'checked' : '', + 'DISABLE_MOD_NO' => $new_attach['disable_mod'] === '0' ? 'checked' : '', + 'PM_ATTACH_YES' => $new_attach['allow_pm_attach'] !== '0' ? 'checked' : '', + 'PM_ATTACH_NO' => $new_attach['allow_pm_attach'] === '0' ? 'checked' : '', + 'DISPLAY_ORDER_ASC' => $new_attach['display_order'] !== '0' ? 'checked' : '', + 'DISPLAY_ORDER_DESC' => $new_attach['display_order'] === '0' ? 'checked' : '', + )); } -if ($submit && $mode == 'cats') -{ - if (!$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } +if ($submit && $mode == 'cats') { + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'cats') -{ - $s_assigned_group_images = $lang['NONE']; +if ($mode == 'cats') { + $s_assigned_group_images = $lang['NONE']; - $sql = 'SELECT group_name, cat_id FROM ' . BB_EXTENSION_GROUPS . ' WHERE cat_id > 0 ORDER BY cat_id'; + $sql = 'SELECT group_name, cat_id FROM ' . BB_EXTENSION_GROUPS . ' WHERE cat_id > 0 ORDER BY cat_id'; - $s_assigned_group_images = array(); + $s_assigned_group_images = []; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group names from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group names from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($row); $i++) - { - if ($row[$i]['cat_id'] == IMAGE_CAT) - { - $s_assigned_group_images[] = $row[$i]['group_name']; - } - } + for ($i = 0, $iMax = count($row); $i < $iMax; $i++) { + if ($row[$i]['cat_id'] == IMAGE_CAT) { + $s_assigned_group_images[] = $row[$i]['group_name']; + } + } - $display_inlined_yes = ( $new_attach['img_display_inlined'] != '0' ) ? 'checked="checked"' : ''; - $display_inlined_no = ( $new_attach['img_display_inlined'] == '0' ) ? 'checked="checked"' : ''; + $display_inlined_yes = ($new_attach['img_display_inlined'] != '0') ? 'checked' : ''; + $display_inlined_no = ($new_attach['img_display_inlined'] == '0') ? 'checked' : ''; - $create_thumbnail_yes = ( $new_attach['img_create_thumbnail'] != '0' ) ? 'checked="checked"' : ''; - $create_thumbnail_no = ( $new_attach['img_create_thumbnail'] == '0' ) ? 'checked="checked"' : ''; + $create_thumbnail_yes = ($new_attach['img_create_thumbnail'] != '0') ? 'checked' : ''; + $create_thumbnail_no = ($new_attach['img_create_thumbnail'] == '0') ? 'checked' : ''; - $use_gd2_yes = ( $new_attach['use_gd2'] != '0' ) ? 'checked="checked"' : ''; - $use_gd2_no = ( $new_attach['use_gd2'] == '0' ) ? 'checked="checked"' : ''; + // Check Thumbnail Support + if (!extension_loaded('gd')) { + $new_attach['img_create_thumbnail'] = '0'; + } else { + $template->assign_block_vars('switch_thumbnail_support', []); + } - // Check Thumbnail Support - if (!is_imagick() && !@extension_loaded('gd')) - { - $new_attach['img_create_thumbnail'] = '0'; - } - else - { - $template->assign_block_vars('switch_thumbnail_support', array()); - } - - $template->assign_vars(array( - 'TPL_ATTACH_SPECIAL_CATEGORIES' => true, - 'IMAGE_MAX_HEIGHT' => $new_attach['img_max_height'], - 'IMAGE_MAX_WIDTH' => $new_attach['img_max_width'], - 'IMAGE_LINK_HEIGHT' => $new_attach['img_link_height'], - 'IMAGE_LINK_WIDTH' => $new_attach['img_link_width'], - 'IMAGE_MIN_THUMB_FILESIZE' => $new_attach['img_min_thumb_filesize'], - 'IMAGE_IMAGICK_PATH' => $new_attach['img_imagick'], - 'DISPLAY_INLINED_YES' => $display_inlined_yes, - 'DISPLAY_INLINED_NO' => $display_inlined_no, - 'CREATE_THUMBNAIL_YES' => $create_thumbnail_yes, - 'CREATE_THUMBNAIL_NO' => $create_thumbnail_no, - 'USE_GD2_YES' => $use_gd2_yes, - 'USE_GD2_NO' => $use_gd2_no, - 'S_ASSIGNED_GROUP_IMAGES' => implode(', ', $s_assigned_group_images), - 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=cats', - )); + $template->assign_vars(array( + 'TPL_ATTACH_SPECIAL_CATEGORIES' => true, + 'IMAGE_MAX_HEIGHT' => $new_attach['img_max_height'], + 'IMAGE_MAX_WIDTH' => $new_attach['img_max_width'], + 'IMAGE_LINK_HEIGHT' => $new_attach['img_link_height'], + 'IMAGE_LINK_WIDTH' => $new_attach['img_link_width'], + 'IMAGE_MIN_THUMB_FILESIZE' => $new_attach['img_min_thumb_filesize'], + 'DISPLAY_INLINED_YES' => $display_inlined_yes, + 'DISPLAY_INLINED_NO' => $display_inlined_no, + 'CREATE_THUMBNAIL_YES' => $create_thumbnail_yes, + 'CREATE_THUMBNAIL_NO' => $create_thumbnail_no, + 'S_ASSIGNED_GROUP_IMAGES' => implode(', ', $s_assigned_group_images), + 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=cats', + )); } // Check Cat Settings -if ($check_image_cat) -{ - // Some tests... - $attach_config = array(); +if ($check_image_cat) { + // Some tests... + $attach_config = []; - $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; + $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not find attachment config table #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not find attachment config table #3'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); - } + for ($i = 0; $i < $num_rows; $i++) { + $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); + } - if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $upload_dir = $attach_config['upload_dir']; - } - else - { - $upload_dir = BB_ROOT . $attach_config['upload_dir']; - } + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $upload_dir = $attach_config['upload_dir']; + } else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; + } - $upload_dir = $upload_dir . '/' . THUMB_DIR; + $upload_dir = $upload_dir . '/' . THUMB_DIR; - $error = false; + $error = false; - // Does the target directory exist, is it a directory and writeable - if ( !@file_exists(@amod_realpath($upload_dir)) ) - { - @mkdir($upload_dir, 0755); - @chmod($upload_dir, 0777); + // Does the target directory exist, is it a directory and writeable + if (!@file_exists(realpath($upload_dir))) { + if (!bb_mkdir($upload_dir) && !is_dir($upload_dir)) { + throw new \RuntimeException(sprintf('Directory "%s" was not created', $upload_dir)); + } - if ( !@file_exists(@amod_realpath($upload_dir)) ) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $upload_dir) . '
'; - } - } + if (!@file_exists(realpath($upload_dir))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $upload_dir) . '
'; + } + } - if (!$error && !is_dir($upload_dir)) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $upload_dir) . '
'; - } + if (!$error && !is_dir($upload_dir)) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $upload_dir) . '
'; + } - if (!$error) - { - if ( !($fp = @fopen($upload_dir . '/0_000000.000', 'w')) ) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $upload_dir) . '
'; - } - else - { - @fclose($fp); - @unlink($upload_dir . '/0_000000.000'); - } - } + if (!$error) { + if (!($fp = @fopen($upload_dir . '/0_000000.000', 'wb+'))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $upload_dir) . '
'; + } else { + @fclose($fp); + @unlink($upload_dir . '/0_000000.000'); + } + } - if (!$error) - { - bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!$error) { + bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } // Quota Limit Settings -if ($submit && $mode == 'quota') -{ - // Change Quota Limit - $quota_change_list = get_var('quota_change_list', array(0)); - $quota_desc_list = get_var('quota_desc_list', array('')); - $filesize_list = get_var('max_filesize_list', array(0)); - $size_select_list = get_var('size_select_list', array('')); +if ($submit && $mode == 'quota') { + // Change Quota Limit + $quota_change_list = get_var('quota_change_list', array(0)); + $quota_desc_list = get_var('quota_desc_list', array('')); + $filesize_list = get_var('max_filesize_list', array(0)); + $size_select_list = get_var('size_select_list', array('')); - $allowed_list = array(); + $allowed_list = []; - for ($i = 0; $i < sizeof($quota_change_list); $i++) - { - $filesize_list[$i] = ( $size_select_list[$i] == 'kb' ) ? round($filesize_list[$i] * 1024) : ( ($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i] ); + for ($i = 0, $iMax = count($quota_change_list); $i < $iMax; $i++) { + $filesize_list[$i] = ($size_select_list[$i] == 'kb') ? round($filesize_list[$i] * 1024) : (($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i]); - $sql = 'UPDATE ' . BB_QUOTA_LIMITS . " - SET quota_desc = '" . attach_mod_sql_escape($quota_desc_list[$i]) . "', quota_limit = " . (int) $filesize_list[$i] . " - WHERE quota_limit_id = " . (int) $quota_change_list[$i]; + $sql = 'UPDATE ' . BB_QUOTA_LIMITS . " + SET quota_desc = '" . DB()->escape($quota_desc_list[$i]) . "', quota_limit = " . (int)$filesize_list[$i] . ' + WHERE quota_limit_id = ' . (int)$quota_change_list[$i]; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not update quota limits'); - } - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update quota limits'); + } + } - // Delete Quota Limits - $quota_id_list = get_var('quota_id_list', array(0)); + // Delete Quota Limits + $quota_id_list = get_var('quota_id_list', array(0)); - $quota_id_sql = implode(', ', $quota_id_list); + $quota_id_sql = implode(', ', $quota_id_list); - if ($quota_id_sql != '') - { - $sql = 'DELETE FROM ' . BB_QUOTA_LIMITS . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; + if ($quota_id_sql != '') { + $sql = 'DELETE FROM ' . BB_QUOTA_LIMITS . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not delete quota limits'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete quota limits'); + } - // Delete Quotas linked to this setting - $sql = 'DELETE FROM ' . BB_QUOTA . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; + // Delete Quotas linked to this setting + $sql = 'DELETE FROM ' . BB_QUOTA . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not delete quotas'); - } - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete quotas'); + } + } - // Add Quota Limit ? - $quota_desc = get_var('quota_description', ''); - $filesize = get_var('add_max_filesize', 0); - $size_select = get_var('add_size_select', ''); - $add = ( isset($_POST['add_quota_check']) ) ? TRUE : FALSE; + // Add Quota Limit ? + $quota_desc = get_var('quota_description', ''); + $filesize = get_var('add_max_filesize', 0); + $size_select = get_var('add_size_select', ''); + $add = isset($_POST['add_quota_check']); - if ($quota_desc != '' && $add) - { - // check Quota Description - $sql = 'SELECT quota_desc FROM ' . BB_QUOTA_LIMITS; + if ($quota_desc != '' && $add) { + // check Quota Description + $sql = 'SELECT quota_desc FROM ' . BB_QUOTA_LIMITS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query quota limits table'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query quota limits table'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ( $num_rows > 0 ) - { - for ($i = 0; $i < $num_rows; $i++) - { - if ($row[$i]['quota_desc'] == $quota_desc) - { - $error = TRUE; - if( isset($error_msg) ) - { - $error_msg .= '
'; - } - $error_msg .= sprintf($lang['QUOTA_LIMIT_EXIST'], $extension_group); - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if ($row[$i]['quota_desc'] == $quota_desc) { + $error = true; + if (isset($error_msg)) { + $error_msg .= '
'; + } + $error_msg .= sprintf($lang['QUOTA_LIMIT_EXIST'], $extension_group); + } + } + } - if (!$error) - { - $filesize = ( $size_select == 'kb' ) ? round($filesize * 1024) : ( ($size_select == 'mb') ? round($filesize * 1048576) : $filesize ); + if (!$error) { + $filesize = ($size_select == 'kb') ? round($filesize * 1024) : (($size_select == 'mb') ? round($filesize * 1048576) : $filesize); - $sql = "INSERT INTO " . BB_QUOTA_LIMITS . " (quota_desc, quota_limit) - VALUES ('" . attach_mod_sql_escape($quota_desc) . "', " . (int) $filesize . ")"; + $sql = 'INSERT INTO ' . BB_QUOTA_LIMITS . " (quota_desc, quota_limit) + VALUES ('" . DB()->escape($quota_desc) . "', " . (int)$filesize . ')'; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not add quota limit'); - } - } - - } - - if (!$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not add quota limit'); + } + } + } + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'quota') -{ - $max_add_filesize = $attach_config['max_filesize']; - $size = ($max_add_filesize >= 1048576) ? 'mb' : ( ($max_add_filesize >= 1024) ? 'kb' : 'b' ); +if ($mode == 'quota') { + $max_add_filesize = $attach_config['max_filesize']; + $size = ($max_add_filesize >= 1048576) ? 'mb' : (($max_add_filesize >= 1024) ? 'kb' : 'b'); - if ($max_add_filesize >= 1048576) - { - $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; - } - else if ( $max_add_filesize >= 1024) - { - $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; - } + if ($max_add_filesize >= 1048576) { + $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; + } elseif ($max_add_filesize >= 1024) { + $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; + } - $template->assign_vars(array( - 'TPL_ATTACH_QUOTA' => true, - 'MAX_FILESIZE' => $max_add_filesize, - 'S_FILESIZE' => size_select('add_size_select', $size), - 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=quota', - )); + $template->assign_vars(array( + 'TPL_ATTACH_QUOTA' => true, + 'MAX_FILESIZE' => $max_add_filesize, + 'S_FILESIZE' => size_select('add_size_select', $size), + 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=quota', + )); - $sql = "SELECT * FROM " . BB_QUOTA_LIMITS . " ORDER BY quota_limit DESC"; + $sql = 'SELECT * FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit DESC'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #1'); + } - $rows = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($rows); $i++) - { - $size_format = ($rows[$i]['quota_limit'] >= 1048576) ? 'mb' : ( ($rows[$i]['quota_limit'] >= 1024) ? 'kb' : 'b' ); + for ($i = 0, $iMax = count($rows); $i < $iMax; $i++) { + $size_format = ($rows[$i]['quota_limit'] >= 1048576) ? 'mb' : (($rows[$i]['quota_limit'] >= 1024) ? 'kb' : 'b'); - if ( $rows[$i]['quota_limit'] >= 1048576) - { - $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1048576 * 100) / 100; - } - else if($rows[$i]['quota_limit'] >= 1024) - { - $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1024 * 100) / 100; - } + if ($rows[$i]['quota_limit'] >= 1048576) { + $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1048576 * 100) / 100; + } elseif ($rows[$i]['quota_limit'] >= 1024) { + $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1024 * 100) / 100; + } - $template->assign_block_vars('limit_row', array( - 'QUOTA_NAME' => $rows[$i]['quota_desc'], - 'QUOTA_ID' => $rows[$i]['quota_limit_id'], - 'S_FILESIZE' => size_select('size_select_list[]', $size_format), - 'U_VIEW' => "admin_attachments.php?mode=$mode&e_mode=view_quota&quota_id=" . $rows[$i]['quota_limit_id'], - 'MAX_FILESIZE' => $rows[$i]['quota_limit'], - )); - } + $template->assign_block_vars('limit_row', array( + 'QUOTA_NAME' => $rows[$i]['quota_desc'], + 'QUOTA_ID' => $rows[$i]['quota_limit_id'], + 'S_FILESIZE' => size_select('size_select_list[]', $size_format), + 'U_VIEW' => "admin_attachments.php?mode=$mode&e_mode=view_quota&quota_id=" . $rows[$i]['quota_limit_id'], + 'MAX_FILESIZE' => $rows[$i]['quota_limit'], + )); + } } -if ($mode == 'quota' && $e_mode == 'view_quota') -{ - $quota_id = get_var('quota_id', 0); +if ($mode == 'quota' && $e_mode == 'view_quota') { + $quota_id = get_var('quota_id', 0); - if (!$quota_id) - { - bb_die('Invalid call'); - } + if (!$quota_id) { + bb_die('Invalid call'); + } - $template->assign_block_vars('switch_quota_limit_desc', array()); + $template->assign_block_vars('switch_quota_limit_desc', []); - $sql = "SELECT * FROM " . BB_QUOTA_LIMITS . " WHERE quota_limit_id = " . (int) $quota_id . " LIMIT 1"; + $sql = 'SELECT * FROM ' . BB_QUOTA_LIMITS . ' WHERE quota_limit_id = ' . (int)$quota_id . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #2'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $template->assign_vars(array( - 'L_QUOTA_LIMIT_DESC' => $row['quota_desc'], - )); + $template->assign_vars(array( + 'L_QUOTA_LIMIT_DESC' => $row['quota_desc'], + )); - $sql = 'SELECT q.user_id, u.username, q.quota_type + $sql = 'SELECT q.user_id, u.username, q.quota_type FROM ' . BB_QUOTA . ' q, ' . BB_USERS . ' u - WHERE q.quota_limit_id = ' . (int) $quota_id . ' + WHERE q.quota_limit_id = ' . (int)$quota_id . ' AND q.user_id <> 0 AND q.user_id = u.user_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #3'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $template->assign_block_vars('users_upload_row', array( - 'USER_ID' => $rows[$i]['user_id'], - 'USERNAME' => $rows[$i]['username'], - )); - } - else if ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) - { - $template->assign_block_vars('users_pm_row', array( - 'USER_ID' => $rows[$i]['user_id'], - 'USERNAME' => $rows[$i]['username'], - )); - } - } + for ($i = 0; $i < $num_rows; $i++) { + if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $template->assign_block_vars('users_upload_row', array( + 'USER_ID' => $rows[$i]['user_id'], + 'USERNAME' => $rows[$i]['username'], + )); + } elseif ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) { + $template->assign_block_vars('users_pm_row', array( + 'USER_ID' => $rows[$i]['user_id'], + 'USERNAME' => $rows[$i]['username'], + )); + } + } - $sql = 'SELECT q.group_id, g.group_name, q.quota_type + $sql = 'SELECT q.group_id, g.group_name, q.quota_type FROM ' . BB_QUOTA . ' q, ' . BB_GROUPS . ' g - WHERE q.quota_limit_id = ' . (int) $quota_id . ' + WHERE q.quota_limit_id = ' . (int)$quota_id . ' AND q.group_id <> 0 AND q.group_id = g.group_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #4'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #4'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $template->assign_block_vars('groups_upload_row', array( - 'GROUP_ID' => $rows[$i]['group_id'], - 'GROUPNAME' => $rows[$i]['group_name'], - )); - } - else if ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) - { - $template->assign_block_vars('groups_pm_row', array( - 'GROUP_ID' => $rows[$i]['group_id'], - 'GROUPNAME' => $rows[$i]['group_name'], - )); - } - } + for ($i = 0; $i < $num_rows; $i++) { + if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $template->assign_block_vars('groups_upload_row', array( + 'GROUP_ID' => $rows[$i]['group_id'], + 'GROUPNAME' => $rows[$i]['group_name'], + )); + } elseif ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) { + $template->assign_block_vars('groups_pm_row', array( + 'GROUP_ID' => $rows[$i]['group_id'], + 'GROUPNAME' => $rows[$i]['group_name'], + )); + } + } } -if ($error) -{ - $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); +if ($error) { + $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); } -print_page('admin_attachments.tpl', 'admin'); \ No newline at end of file +print_page('admin_attachments.tpl', 'admin'); diff --git a/admin/admin_board.php b/admin/admin_board.php index a709f7a34..191666675 100644 --- a/admin/admin_board.php +++ b/admin/admin_board.php @@ -1,149 +1,154 @@ '

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''), - 'config' => '

'. sprintf($lang['CLICK_RETURN_CONFIG'], '', ''), - 'config_mods' => '

'. sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '', '') -); - -// -// Pull all config data -// -$sql = "SELECT * FROM " . BB_CONFIG; -if (!$result = DB()->sql_query($sql)) -{ - bb_die('Could not query config information in admin_board'); -} -else -{ - while ($row = DB()->sql_fetchrow($result)) - { - $config_name = $row['config_name']; - $config_value = $row['config_value']; - $default_config[$config_name] = $config_value; - - $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; - - if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) - { - if ($config_name == 'seed_bonus_points' || $config_name == 'seed_bonus_release' || $config_name == 'bonus_upload' || $config_name == 'bonus_upload_price') $new[$config_name] = serialize(str_replace(',', '.', $new[$config_name])); - bb_update_config(array($config_name => $new[$config_name])); - } - } - - if (isset($_POST['submit'])) - { - bb_die($lang['CONFIG_UPDATED'] . $return_links[$mode] . $return_links['index']); - } +if (!empty($setmodules)) { + $module['GENERAL']['CONFIGURATION'] = basename(__FILE__) . '?mode=config'; + $module['MODS']['CONFIGURATION'] = basename(__FILE__) . '?mode=config_mods'; + return; } -switch ($mode) -{ - case 'config_mods': - $template->assign_vars(array( - 'S_CONFIG_ACTION' => 'admin_board.php?mode=config_mods', - 'CONFIG_MODS' => true, +require __DIR__ . '/pagestart.php'; - 'MAGNET_LINKS_ENABLED' => $new['magnet_links_enabled'], - 'GENDER' => $new['gender'], - 'CALLSEED' => $new['callseed'], - 'TOR_STATS' => $new['tor_stats'], - 'SHOW_LATEST_NEWS' => $new['show_latest_news'], - 'MAX_NEWS_TITLE' => $new['max_news_title'], - 'LATEST_NEWS_COUNT' => $new['latest_news_count'], - 'LATEST_NEWS_FORUM_ID' => $new['latest_news_forum_id'], - 'SHOW_NETWORK_NEWS' => $new['show_network_news'], - 'MAX_NET_TITLE' => $new['max_net_title'], - 'NETWORK_NEWS_COUNT' => $new['network_news_count'], - 'NETWORK_NEWS_FORUM_ID' => $new['network_news_forum_id'], - 'WHOIS_INFO' => $new['whois_info'], - 'SHOW_MOD_INDEX' => $new['show_mod_index'], - 'BIRTHDAY_ENABLED' => $new['birthday_enabled'], - 'BIRTHDAY_MAX_AGE' => $new['birthday_max_age'], - 'BIRTHDAY_MIN_AGE' => $new['birthday_min_age'], - 'BIRTHDAY_CHECK_DAY' => $new['birthday_check_day'], - 'PREMOD' => $new['premod'], - 'TOR_COMMENT' => $new['tor_comment'], - 'NEW_TPLS' => $new['new_tpls'], - 'SEED_BONUS_ENABLED' => $new['seed_bonus_enabled'], - 'SEED_BONUS_TOR_SIZE' => $new['seed_bonus_tor_size'], - 'SEED_BONUS_USER_REGDATE' => $new['seed_bonus_user_regdate'], - )); +$mode = $_GET['mode'] ?? ''; - if ($new['seed_bonus_points'] && $new['seed_bonus_release']) - { - $seed_bonus = unserialize($new['seed_bonus_points']); - $seed_release = unserialize($new['seed_bonus_release']); +$return_links = [ + 'index' => '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''), + 'config' => '

' . sprintf($lang['CLICK_RETURN_CONFIG'], '', ''), + 'config_mods' => '

' . sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '', '') +]; - foreach ($seed_bonus as $i => $row) - { - if (!$row || !$seed_release[$i]) continue; +/** + * Pull all config data + */ +$sql = 'SELECT * FROM ' . BB_CONFIG; +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query config information in admin_board'); +} else { + while ($row = DB()->sql_fetchrow($result)) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; + $default_config[$config_name] = $config_value; - $template->assign_block_vars('seed_bonus', array( - 'RELEASE' => $seed_release[$i], - 'POINTS' => $row, - )); - } - } + $new[$config_name] = $_POST[$config_name] ?? $default_config[$config_name]; - if ($new['bonus_upload'] && $new['bonus_upload_price']) - { - $upload_row = unserialize($new['bonus_upload']); - $price_row = unserialize($new['bonus_upload_price']); + if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) { + if ($config_name == 'seed_bonus_points' || + $config_name == 'seed_bonus_release' || + $config_name == 'bonus_upload' || + $config_name == 'bonus_upload_price' + ) { + $new[$config_name] = serialize(str_replace(',', '.', $new[$config_name])); + } + bb_update_config([$config_name => $new[$config_name]]); + } + } - foreach ($upload_row as $i => $row) - { - if (!$row || !$price_row[$i]) continue; - - $template->assign_block_vars('bonus_upload', array( - 'UP' => $row, - 'PRICE' => $price_row[$i], - )); - } - } - break; - - default: - $template->assign_vars(array( - 'S_CONFIG_ACTION' => 'admin_board.php?mode=config', - 'CONFIG' => true, - - 'SITENAME' => htmlCHR($new['sitename']), - 'CONFIG_SITE_DESCRIPTION' => htmlCHR($new['site_desc']), - 'DISABLE_BOARD' => ($new['board_disable']) ? true : false, - 'ALLOW_AUTOLOGIN' => ($new['allow_autologin']) ? true : false, - 'AUTOLOGIN_TIME' => (int) $new['max_autologin_time'], - 'MAX_POLL_OPTIONS' => $new['max_poll_options'], - 'FLOOD_INTERVAL' => $new['flood_interval'], - 'TOPICS_PER_PAGE' => $new['topics_per_page'], - 'POSTS_PER_PAGE' => $new['posts_per_page'], - 'HOT_TOPIC' => $new['hot_threshold'], - 'DEFAULT_DATEFORMAT' => $new['default_dateformat'], - 'LANG_SELECT' => language_select($new['default_lang'], 'default_lang'), - 'TIMEZONE_SELECT' => tz_select($new['board_timezone'], 'board_timezone'), - 'MAX_LOGIN_ATTEMPTS' => $new['max_login_attempts'], - 'LOGIN_RESET_TIME' => $new['login_reset_time'], - 'PRUNE_ENABLE' => ($new['prune_enable']) ? true : false, - 'ALLOW_BBCODE' => ($new['allow_bbcode']) ? true : false, - 'ALLOW_SMILIES' => ($new['allow_smilies']) ? true : false, - 'ALLOW_SIG' => ($new['allow_sig']) ? true : false, - 'SIG_SIZE' => $new['max_sig_chars'], - 'ALLOW_NAMECHANGE' => ($new['allow_namechange']) ? true : false, - 'SMILIES_PATH' => $new['smilies_path'], - )); - break; + if (isset($_POST['submit'])) { + bb_die($lang['CONFIG_UPDATED'] . $return_links[$mode] . $return_links['index']); + } } -print_page('admin_board.tpl', 'admin'); \ No newline at end of file +switch ($mode) { + case 'config_mods': + $template->assign_vars([ + 'S_CONFIG_ACTION' => 'admin_board.php?mode=config_mods', + 'CONFIG_MODS' => true, + + 'MAGNET_LINKS_ENABLED' => $new['magnet_links_enabled'], + 'MAGNET_LINKS_FOR_GUESTS' => $new['magnet_links_for_guests'], + 'GENDER' => $new['gender'], + 'CALLSEED' => $new['callseed'], + 'TOR_STATS' => $new['tor_stats'], + 'SHOW_LATEST_NEWS' => $new['show_latest_news'], + 'MAX_NEWS_TITLE' => $new['max_news_title'], + 'LATEST_NEWS_COUNT' => $new['latest_news_count'], + 'LATEST_NEWS_FORUM_ID' => $new['latest_news_forum_id'], + 'SHOW_NETWORK_NEWS' => $new['show_network_news'], + 'MAX_NET_TITLE' => $new['max_net_title'], + 'NETWORK_NEWS_COUNT' => $new['network_news_count'], + 'NETWORK_NEWS_FORUM_ID' => $new['network_news_forum_id'], + 'WHOIS_INFO' => $new['whois_info'], + 'SHOW_MOD_INDEX' => $new['show_mod_index'], + 'SHOW_BOARD_START_INDEX' => $new['show_board_start_index'], + 'BIRTHDAY_ENABLED' => $new['birthday_enabled'], + 'BIRTHDAY_MAX_AGE' => $new['birthday_max_age'], + 'BIRTHDAY_MIN_AGE' => $new['birthday_min_age'], + 'BIRTHDAY_CHECK_DAY' => $new['birthday_check_day'], + 'PREMOD' => $new['premod'], + 'TOR_COMMENT' => $new['tor_comment'], + 'SEED_BONUS_ENABLED' => $new['seed_bonus_enabled'], + 'SEED_BONUS_TOR_SIZE' => $new['seed_bonus_tor_size'], + 'SEED_BONUS_USER_REGDATE' => $new['seed_bonus_user_regdate'] + ]); + + if ($new['seed_bonus_points'] && $new['seed_bonus_release']) { + $seed_bonus = unserialize($new['seed_bonus_points']); + $seed_release = unserialize($new['seed_bonus_release']); + + foreach ($seed_bonus as $i => $row) { + if (!$row || !$seed_release[$i]) { + continue; + } + + $template->assign_block_vars('seed_bonus', [ + 'RELEASE' => $seed_release[$i], + 'POINTS' => $row + ]); + } + } + + if ($new['bonus_upload'] && $new['bonus_upload_price']) { + $upload_row = unserialize($new['bonus_upload']); + $price_row = unserialize($new['bonus_upload_price']); + + foreach ($upload_row as $i => $row) { + if (!$row || !$price_row[$i]) { + continue; + } + + $template->assign_block_vars('bonus_upload', [ + 'UP' => $row, + 'PRICE' => $price_row[$i] + ]); + } + } + break; + + default: + $template->assign_vars([ + 'S_CONFIG_ACTION' => 'admin_board.php?mode=config', + 'CONFIG' => true, + + 'SITENAME' => htmlCHR($new['sitename']), + 'CONFIG_SITE_DESCRIPTION' => htmlCHR($new['site_desc']), + 'DISABLE_BOARD' => (bool)$new['board_disable'], + 'ALLOW_AUTOLOGIN' => (bool)$new['allow_autologin'], + 'AUTOLOGIN_TIME' => (int)$new['max_autologin_time'], + 'MAX_POLL_OPTIONS' => $new['max_poll_options'], + 'FLOOD_INTERVAL' => $new['flood_interval'], + 'TOPICS_PER_PAGE' => $new['topics_per_page'], + 'POSTS_PER_PAGE' => $new['posts_per_page'], + 'HOT_TOPIC' => $new['hot_threshold'], + 'DEFAULT_DATEFORMAT' => $new['default_dateformat'], + 'LANG_SELECT' => \TorrentPier\Legacy\Common\Select::language($new['default_lang'], 'default_lang'), + 'TIMEZONE_SELECT' => \TorrentPier\Legacy\Common\Select::timezone($new['board_timezone'], 'board_timezone'), + 'MAX_LOGIN_ATTEMPTS' => $new['max_login_attempts'], + 'LOGIN_RESET_TIME' => $new['login_reset_time'], + 'PRUNE_ENABLE' => (bool)$new['prune_enable'], + 'ALLOW_BBCODE' => (bool)$new['allow_bbcode'], + 'ALLOW_SMILIES' => (bool)$new['allow_smilies'], + 'ALLOW_SIG' => (bool)$new['allow_sig'], + 'SIG_SIZE' => $new['max_sig_chars'], + 'ALLOW_NAMECHANGE' => (bool)$new['allow_namechange'], + 'SMILIES_PATH' => $new['smilies_path'] + ]); + break; +} + +print_page('admin_board.tpl', 'admin'); diff --git a/admin/admin_bt_forum_cfg.php b/admin/admin_bt_forum_cfg.php index ba06b1382..75453e0ca 100644 --- a/admin/admin_bt_forum_cfg.php +++ b/admin/admin_bt_forum_cfg.php @@ -1,150 +1,154 @@ 'http://demo.torrentpier.me/bt/', + 'bt_announce_url' => 'https://torrentpier.duckdns.org/bt/', ); $default_cfg_bool = array( - 'bt_disable_dht' => 1, - 'bt_show_peers' => 1, - 'bt_add_auth_key' => 1, - 'bt_show_dl_list' => 0, - 'bt_dl_list_only_1st_page' => 1, - 'bt_dl_list_only_count' => 1, - 'bt_replace_ann_url' => 1, - 'bt_show_ip_only_moder' => 1, - 'bt_show_port_only_moder' => 1, - 'bt_check_announce_url' => 0, - 'bt_show_dl_list_buttons' => 1, - 'bt_show_dl_but_will' => 1, - 'bt_show_dl_but_down' => 0, - 'bt_show_dl_but_compl' => 1, - 'bt_show_dl_but_cancel' => 1, - 'bt_show_dl_stat_on_index' => 1, - 'bt_newtopic_auto_reg' => 1, - 'bt_tor_browse_only_reg' => 1, - 'bt_search_bool_mode' => 1, - 'bt_allow_spmode_change' => 1, - 'bt_del_addit_ann_urls' => 1, - 'bt_set_dltype_on_tor_reg' => 1, - 'bt_unset_dltype_on_tor_unreg' => 1, + 'bt_disable_dht' => 1, + 'bt_show_peers' => 1, + 'bt_add_auth_key' => 1, + 'bt_show_dl_list' => 0, + 'bt_dl_list_only_1st_page' => 1, + 'bt_dl_list_only_count' => 1, + 'bt_replace_ann_url' => 1, + 'bt_show_ip_only_moder' => 1, + 'bt_show_port_only_moder' => 1, + 'bt_check_announce_url' => 0, + 'bt_show_dl_list_buttons' => 1, + 'bt_show_dl_but_will' => 1, + 'bt_show_dl_but_down' => 0, + 'bt_show_dl_but_compl' => 1, + 'bt_show_dl_but_cancel' => 1, + 'bt_show_dl_stat_on_index' => 1, + 'bt_newtopic_auto_reg' => 1, + 'bt_tor_browse_only_reg' => 1, + 'bt_search_bool_mode' => 1, + 'bt_allow_spmode_change' => 1, + 'bt_del_addit_ann_urls' => 1, + 'bt_set_dltype_on_tor_reg' => 1, + 'bt_unset_dltype_on_tor_unreg' => 1, ); $default_cfg_num = array( - 'bt_show_peers_mode' => SHOW_PEERS_COUNT, + 'bt_show_peers_mode' => SHOW_PEERS_COUNT, ); $default_cfg = array_merge($default_cfg_str, $default_cfg_bool, $default_cfg_num); $db_fields_bool = array( - 'allow_reg_tracker' => 0, // Allowed forums for registering torrents on tracker - 'allow_porno_topic' => 0, // Allowed forums for porno topics - 'self_moderated' => 0, // Users can move theirs topic to another forum + 'allow_reg_tracker' => 0, // Allowed forums for registering torrents on tracker + 'allow_porno_topic' => 0, // Allowed forums for porno topics + 'self_moderated' => 0, // Users can move theirs topic to another forum ); -// Get config +/** + * Get config + */ $cfg = bb_get_config(BB_CONFIG, true, false); -// Submit new config -if ($submit && $confirm) -{ - foreach ($db_fields_bool as $field_name => $field_def_val) - { - update_table_bool(BB_FORUMS, 'forum_id', $field_name, $field_def_val); - } +/** + * Submit new config + */ +if ($submit && $confirm) { + foreach ($db_fields_bool as $field_name => $field_def_val) { + \TorrentPier\Legacy\Admin\Torrent::update_table_bool(BB_FORUMS, 'forum_id', $field_name, $field_def_val); + } - update_config_table(BB_CONFIG, $default_cfg_str, $cfg, 'str'); - update_config_table(BB_CONFIG, $default_cfg_bool, $cfg, 'bool'); - update_config_table(BB_CONFIG, $default_cfg_num, $cfg, 'num'); + \TorrentPier\Legacy\Admin\Torrent::update_config_table(BB_CONFIG, $default_cfg_str, $cfg, 'str'); + \TorrentPier\Legacy\Admin\Torrent::update_config_table(BB_CONFIG, $default_cfg_bool, $cfg, 'bool'); + \TorrentPier\Legacy\Admin\Torrent::update_config_table(BB_CONFIG, $default_cfg_num, $cfg, 'num'); - $datastore->update('cat_forums'); + $datastore->update('cat_forums'); - bb_die($lang['CONFIG_UPD'] .'

'. sprintf($lang['RETURN_CONFIG'], '', '') .'

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['CONFIG_UPD'] . '

' . sprintf($lang['RETURN_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); } // Set template vars -set_tpl_vars ($default_cfg_str, $cfg); -set_tpl_vars_lang ($default_cfg_str); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars($default_cfg_str, $cfg); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars_lang($default_cfg_str); -set_tpl_vars_bool ($default_cfg_bool, $cfg); -set_tpl_vars_lang ($default_cfg_bool); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars_bool($default_cfg_bool, $cfg); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars_lang($default_cfg_bool); -set_tpl_vars ($default_cfg_num, $cfg); -set_tpl_vars_lang ($default_cfg_num); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars($default_cfg_num, $cfg); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars_lang($default_cfg_num); -set_tpl_vars_lang ($db_fields_bool); +\TorrentPier\Legacy\Admin\Torrent::set_tpl_vars_lang($db_fields_bool); // Get Forums list -$sql = "SELECT f.* - FROM ". BB_CATEGORIES ." c, ". BB_FORUMS ." f +$sql = 'SELECT f.* + FROM ' . BB_CATEGORIES . ' c, ' . BB_FORUMS . ' f WHERE f.cat_id = c.cat_id - ORDER BY c.cat_order, f.forum_order"; + ORDER BY c.cat_order, f.forum_order'; -if (!$result = DB()->sql_query($sql)) -{ - bb_die('Could not obtain forum names'); +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain forum names'); } $rowset = DB()->sql_fetchrowset($result); $forum_rows = min($max_forum_rows, count($rowset)); -foreach ($db_fields_bool as $field_name => $field_def_val) -{ - $$field_name = ''; +foreach ($db_fields_bool as $field_name => $field_def_val) { + $$field_name = ''; } -foreach ($rowset as $rid => $forum) -{ - foreach ($db_fields_bool as $field_name => $field_def_val) - { - $forum_name = $forum['forum_name']; - $selected = ($forum[$field_name]) ? ' selected="selected"' : ''; +foreach ($rowset as $rid => $forum) { + foreach ($db_fields_bool as $field_name => $field_def_val) { + $forum_name = $forum['forum_name']; + $selected = $forum[$field_name] ? ' selected' : ''; - $forum_name = str_short($forum_name, $max_forum_name_len); + $forum_name = str_short($forum_name, $max_forum_name_len); - $$field_name .= '\n"; - } + $$field_name .= '\n"; + } } -foreach ($db_fields_bool as $field_name => $field_def_val) -{ - $$field_name = ''; - $template->assign_vars(array('S_'. strtoupper($field_name) => $$field_name)); +foreach ($db_fields_bool as $field_name => $field_def_val) { + $$field_name = ''; + $template->assign_vars(array('S_' . strtoupper($field_name) => $$field_name)); } $template->assign_vars(array( - 'L_BT_SHOW_PEERS_MODE_COUNT' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? ''. $lang['BT_SHOW_PEERS_MODE_COUNT'] .'' : $lang['BT_SHOW_PEERS_MODE_COUNT'], - 'L_BT_SHOW_PEERS_MODE_NAMES' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? ''. $lang['BT_SHOW_PEERS_MODE_NAMES'] .'' : $lang['BT_SHOW_PEERS_MODE_NAMES'], - 'L_BT_SHOW_PEERS_MODE_FULL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? ''. $lang['BT_SHOW_PEERS_MODE_FULL'] .'' : $lang['BT_SHOW_PEERS_MODE_FULL'], + 'L_BT_SHOW_PEERS_MODE_COUNT' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? '' . $lang['BT_SHOW_PEERS_MODE_COUNT'] . '' : $lang['BT_SHOW_PEERS_MODE_COUNT'], + 'L_BT_SHOW_PEERS_MODE_NAMES' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? '' . $lang['BT_SHOW_PEERS_MODE_NAMES'] . '' : $lang['BT_SHOW_PEERS_MODE_NAMES'], + 'L_BT_SHOW_PEERS_MODE_FULL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? '' . $lang['BT_SHOW_PEERS_MODE_FULL'] . '' : $lang['BT_SHOW_PEERS_MODE_FULL'], - 'BT_SHOW_PEERS_MODE_COUNT_VAL' => SHOW_PEERS_COUNT, - 'BT_SHOW_PEERS_MODE_NAMES_VAL' => SHOW_PEERS_NAMES, - 'BT_SHOW_PEERS_MODE_FULL_VAL' => SHOW_PEERS_FULL, + 'BT_SHOW_PEERS_MODE_COUNT_VAL' => SHOW_PEERS_COUNT, + 'BT_SHOW_PEERS_MODE_NAMES_VAL' => SHOW_PEERS_NAMES, + 'BT_SHOW_PEERS_MODE_FULL_VAL' => SHOW_PEERS_FULL, - 'BT_SHOW_PEERS_MODE_COUNT_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? HTML_CHECKED : '', - 'BT_SHOW_PEERS_MODE_NAMES_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? HTML_CHECKED : '', - 'BT_SHOW_PEERS_MODE_FULL_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? HTML_CHECKED : '', + 'BT_SHOW_PEERS_MODE_COUNT_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? HTML_CHECKED : '', + 'BT_SHOW_PEERS_MODE_NAMES_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? HTML_CHECKED : '', + 'BT_SHOW_PEERS_MODE_FULL_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? HTML_CHECKED : '', - 'S_HIDDEN_FIELDS' => '', - 'S_CONFIG_ACTION' => 'admin_bt_forum_cfg.php', + 'S_HIDDEN_FIELDS' => '', + 'S_CONFIG_ACTION' => 'admin_bt_forum_cfg.php', )); -print_page('admin_bt_forum_cfg.tpl', 'admin'); \ No newline at end of file +print_page('admin_bt_forum_cfg.tpl', 'admin'); diff --git a/admin/admin_bt_tracker_cfg.php b/admin/admin_bt_tracker_cfg.php deleted file mode 100644 index 9406a5b89..000000000 --- a/admin/admin_bt_tracker_cfg.php +++ /dev/null @@ -1,64 +0,0 @@ - 'Tracker is disabled', - 'browser_redirect_url' => 'http://demo.torrentpier.me/', -); - -$default_cfg_bool = array( - 'autoclean' => 1, - 'off' => 0, - 'compact_mode' => 1, - 'update_dlstat' => 1, - 'limit_active_tor' => 0, - 'limit_concurrent_ips' => 0, - 'retracker' => 1, -); - -$default_cfg_num = array( - 'numwant' => 50, - 'expire_factor' => 4, - 'limit_seed_count' => 20, - 'limit_leech_count' => 4, - 'leech_expire_factor' => 60, - 'limit_seed_ips' => 0, - 'limit_leech_ips' => 0, -); - -// Set template vars -set_tpl_vars ($default_cfg_str, $tr_cfg); -set_tpl_vars_lang ($default_cfg_str); - -set_tpl_vars_bool ($default_cfg_bool, $tr_cfg); -set_tpl_vars_lang ($default_cfg_bool); - -set_tpl_vars ($default_cfg_num, $tr_cfg); -set_tpl_vars_lang ($default_cfg_num); - -$template->assign_vars(array( - 'IGNORE_REPORTED_IP' => $bb_cfg['ignore_reported_ip'], - 'ANNOUNCE_INTERVAL' => $bb_cfg['announce_interval'], - 'PASSKEY_KEY' => $bb_cfg['passkey_key'], - 'GOLD_SILVER_ENABLED' => $tr_cfg['gold_silver_enabled'], - 'DISABLE_SUBMIT' => true, - - 'S_HIDDEN_FIELDS' => '', - 'S_CONFIG_ACTION' => 'admin_bt_tracker_cfg.php', -)); - -print_page('admin_bt_tracker_cfg.tpl', 'admin'); \ No newline at end of file diff --git a/admin/admin_cron.php b/admin/admin_cron.php index 7999137c4..757108ec0 100644 --- a/admin/admin_cron.php +++ b/admin/admin_cron.php @@ -1,228 +1,216 @@ session_start(); - redirect('admin/'.basename(__FILE__) . '?mode=list'); +if ($mode == 'run' && !$job_id) { + define('BB_ROOT', './../'); + require BB_ROOT . 'common.php'; + $user->session_start(); + redirect('admin/' . basename(__FILE__) . '?mode=list'); +} else { + require __DIR__ . '/pagestart.php'; } -else require('./pagestart.php'); -if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']); +// Check for demo mode +if (IN_DEMO_MODE && ($submit || !in_array($mode, ['add', 'list']))) { + bb_die($lang['CANT_EDIT_IN_DEMO_MODE']); +} -require(INC_DIR .'functions_admin_torrent.php'); -require(INC_DIR .'functions_admin_cron.php'); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} -$sql = DB()->fetch_rowset("SELECT * FROM ". BB_CONFIG ." WHERE config_name = 'cron_enabled' OR config_name = 'cron_check_interval'"); +$sql = DB()->fetch_rowset('SELECT * FROM ' . BB_CONFIG . " WHERE config_name = 'cron_check_interval'"); -foreach ($sql as $row) -{ - $config_name = $row['config_name']; - $config_value = $row['config_value']; - $default_config[$config_name] = $config_value; +foreach ($sql as $row) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; + $default_config[$config_name] = $config_value; - $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; + $new[$config_name] = $_POST[$config_name] ?? $default_config[$config_name]; - if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) - { - bb_update_config(array($config_name => $new[$config_name])); - } + if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) { + bb_update_config(array($config_name => $new[$config_name])); + } } $template->assign_vars(array( - 'CRON_ENABLED' => ($new['cron_enabled']) ? true : false, - 'CRON_CHECK_INTERVAL' => $new['cron_check_interval'], + 'CRON_ENABLED' => TorrentPier\Helpers\CronHelper::isEnabled(), + 'CRON_CHECK_INTERVAL' => $new['cron_check_interval'], )); -switch ($mode) -{ - case 'list': - $sql = DB()->fetch_rowset("SELECT * FROM ". BB_CRON ." ORDER BY cron_id"); +switch ($mode) { + case 'list': + $sql = DB()->fetch_rowset('SELECT * FROM ' . BB_CRON . ' ORDER BY cron_id'); - foreach ($sql as $i => $row) - { - $template->assign_block_vars('list', array( - 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', - 'JOB_ID' => $i + 1, - 'CRON_ID' => $row['cron_id'], - 'CRON_ACTIVE' => $row['cron_active'] ? ''. $lang['YES'] .'' : ''. $lang['NO'] .'', - 'CRON_TITLE' => $row['cron_title'], - 'CRON_SCRIPT' => $row['cron_script'], - 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : ''. $lang['NOSELECT'] .'', - 'RUN_DAY' => $row['run_day'], - 'LAST_RUN' => $row['last_run'], - 'NEXT_RUN' => $row['next_run'], - 'RUN_COUNT' => $row['run_counter'], - )); - } + foreach ($sql as $i => $row) { + $template->assign_block_vars('list', array( + 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', + 'JOB_ID' => $i + 1, + 'CRON_ID' => $row['cron_id'], + 'CRON_ACTIVE' => $row['cron_active'] ? '' . $lang['YES'] . '' : '' . $lang['NO'] . '', + 'CRON_TITLE' => $row['cron_title'], + 'CRON_SCRIPT' => $row['cron_script'], + 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '' . $lang['NOSELECT'] . '', + 'RUN_DAY' => $row['run_day'], + 'LAST_RUN' => $row['last_run'], + 'NEXT_RUN' => $row['next_run'], + 'RUN_COUNT' => $row['run_counter'], + )); + } - $template->assign_vars(array( - 'TPL_CRON_LIST' => true, - 'S_CRON_ACTION' => 'admin_cron.php', - 'S_MODE' => 'list', - )); + $template->assign_vars(array( + 'TPL_CRON_LIST' => true, + 'S_CRON_ACTION' => 'admin_cron.php', + 'S_MODE' => 'list', + )); - //detect cron status - if (@file_exists('../triggers/cron_running')) - { - $template->assign_vars(array( - 'CRON_RUNNING' => true, - )); - } - break; + //detect cron status + if (is_file(CRON_RUNNING)) { + $template->assign_vars(array( + 'CRON_RUNNING' => true, + )); + } + break; - case 'repair': - if (@file_exists('../triggers/cron_running')) - { - rename("../triggers/cron_running", "../triggers/cron_allowed"); - } - redirect('admin/'.basename(__FILE__) . '?mode=list'); - break; + case 'repair': + if (is_file(CRON_RUNNING)) { + rename(CRON_RUNNING, CRON_ALLOWED); + } + redirect('admin/' . basename(__FILE__) . '?mode=list'); + break; - case 'run': - run_jobs($job_id); - redirect('admin/'.basename(__FILE__) . '?mode=list'); - break; + case 'run': + \TorrentPier\Legacy\Admin\Cron::run_jobs($job_id); + redirect('admin/' . basename(__FILE__) . '?mode=list'); + break; - case 'edit': - $sql = DB()->fetch_rowset("SELECT * FROM ". BB_CRON ." WHERE cron_id = $job_id"); + case 'edit': + $sql = DB()->fetch_rowset('SELECT * FROM ' . BB_CRON . " WHERE cron_id = $job_id"); - foreach ($sql as $row) - { - $template->assign_vars(array( - 'CRON_ID' => $row['cron_id'], - 'CRON_ACTIVE' => $row['cron_active'], - 'CRON_TITLE' => $row['cron_title'], - 'CRON_SCRIPT' => $row['cron_script'], - 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '', - 'RUN_DAY' => $row['run_day'], - 'RUN_TIME' => $row['run_time'], - 'RUN_ORDER' => $row['run_order'], - 'LAST_RUN' => $row['last_run'], - 'NEXT_RUN' => $row['next_run'], - 'RUN_INTERVAL' => $row['run_interval'], - 'LOG_ENABLED' => $row['log_enabled'], - 'LOG_FILE' => $row['log_file'], - 'LOG_SQL_QUERIES' => $row['log_sql_queries'], - 'DISABLE_BOARD' => $row['disable_board'], - 'RUN_COUNTER' => $row['run_counter'], - )); - } + foreach ($sql as $row) { + $template->assign_vars(array( + 'CRON_ID' => $row['cron_id'], + 'CRON_ACTIVE' => $row['cron_active'], + 'CRON_TITLE' => $row['cron_title'], + 'CRON_SCRIPT' => $row['cron_script'], + 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '', + 'RUN_DAY' => $row['run_day'], + 'RUN_TIME' => $row['run_time'], + 'RUN_ORDER' => $row['run_order'], + 'LAST_RUN' => $row['last_run'], + 'NEXT_RUN' => $row['next_run'], + 'RUN_INTERVAL' => $row['run_interval'], + 'LOG_ENABLED' => $row['log_enabled'], + 'LOG_FILE' => $row['log_file'], + 'LOG_SQL_QUERIES' => $row['log_sql_queries'], + 'DISABLE_BOARD' => $row['disable_board'], + 'RUN_COUNTER' => $row['run_counter'], + )); + } - $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); - for ($i = 1; $i <= 28; $i++) - { - $run_day[$i] = $i; - } + $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); + for ($i = 1; $i <= 28; $i++) { + $run_day[$i] = $i; + } - $schedule = array($lang['SCHEDULE']['select'] => 0); - foreach ($lang['SCHEDULE'] as $type => $key) - { - $schedule[$key] = $type; - } + $schedule = array($lang['SCHEDULE']['select'] => 0); + foreach ($lang['SCHEDULE'] as $type => $key) { + $schedule[$key] = $type; + } - $template->assign_vars(array( - 'TPL_CRON_EDIT' => true, - 'S_CRON_ACTION' => 'admin_cron.php', - 'S_MODE' => 'edit', - 'SCHEDULE' => build_select('schedule', $schedule, $row['schedule']), - 'RUN_DAY' => build_select('run_day', $run_day, $row['run_day']), - 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_EDIT'], - )); - break; + $template->assign_vars(array( + 'TPL_CRON_EDIT' => true, + 'S_CRON_ACTION' => 'admin_cron.php', + 'S_MODE' => 'edit', + 'SCHEDULE' => build_select('schedule', $schedule, $row['schedule']), + 'RUN_DAY' => build_select('run_day', $run_day, $row['run_day']), + 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_EDIT'], + )); + break; - case 'add': - $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); - for ($i = 1; $i <= 28; $i++) - { - $run_day[$i] = $i; - } + case 'add': + $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); + for ($i = 1; $i <= 28; $i++) { + $run_day[$i] = $i; + } - $schedule = array(); - foreach ($lang['SCHEDULE'] as $type => $key) - { - $schedule[$key] = $type; - } + $schedule = []; + foreach ($lang['SCHEDULE'] as $type => $key) { + $schedule[$key] = $type; + } - $template->assign_vars(array( - 'TPL_CRON_EDIT' => true, - 'S_CRON_ACTION' => 'admin_cron.php', - 'S_MODE' => 'add', - 'SCHEDULE' => build_select('schedule', $schedule, 'select', null, null), - 'RUN_DAY' => build_select('run_day', $run_day, 0, null, null), - 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_ADD'], - 'CRON_ID' => 'none', - 'CRON_ACTIVE' => 1, - 'CRON_TITLE' => '', - 'CRON_SCRIPT' => '', - 'RUN_TIME' => '', - 'RUN_ORDER' => 255, - 'LAST_RUN' => '0000-00-00 00:00:00', - 'NEXT_RUN' => '0000-00-00 00:00:00', - 'RUN_INTERVAL' => '', - 'LOG_ENABLED' => 0, - 'LOG_FILE' => '', - 'LOG_SQL_QUERIES' => 0, - 'DISABLE_BOARD' => 0, - 'RUN_COUNTER' => 0, - )); - break; + $template->assign_vars(array( + 'TPL_CRON_EDIT' => true, + 'S_CRON_ACTION' => 'admin_cron.php', + 'S_MODE' => 'add', + 'SCHEDULE' => build_select('schedule', $schedule, 'select', null, null), + 'RUN_DAY' => build_select('run_day', $run_day, 0, null, null), + 'CRON_ID' => '', + 'CRON_ACTIVE' => 1, + 'CRON_TITLE' => '', + 'CRON_SCRIPT' => '', + 'RUN_TIME' => '', + 'RUN_ORDER' => 255, + 'LAST_RUN' => '1900-01-01 00:00:00', + 'NEXT_RUN' => '1900-01-01 00:00:00', + 'RUN_INTERVAL' => '', + 'LOG_ENABLED' => 0, + 'LOG_FILE' => '', + 'LOG_SQL_QUERIES' => 0, + 'DISABLE_BOARD' => 0, + 'RUN_COUNTER' => 0, + )); + break; - case 'delete': - delete_jobs($job_id); - bb_die($lang['JOB_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_JOBS'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + case 'delete': + \TorrentPier\Legacy\Admin\Cron::delete_jobs($job_id); + bb_die($lang['JOB_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_JOBS'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; } -if ($submit) -{ - if ($_POST['mode'] == 'list') - { - if ($cron_action == 'run' && $jobs) - { - run_jobs($jobs); - } - else if ($cron_action == 'delete' && $jobs) - { - delete_jobs($jobs); - } - else if (($cron_action == 'disable' || $cron_action == 'enable') && $jobs) - { - toggle_active($jobs, $cron_action); - } - redirect('admin/'.basename(__FILE__) . '?mode=list'); - } - else if (validate_cron_post($_POST) == 1) - { - if ($_POST['mode'] == 'edit') - { - update_cron_job($_POST); - } - else if ($_POST['mode'] == 'add') - { - insert_cron_job($_POST); - } - else bb_die('Mode error'); +if ($submit) { + $mode2 = $_POST['mode'] ?? ''; + if ($mode2 == 'list') { + if ($cron_action == 'run' && $jobs) { + \TorrentPier\Legacy\Admin\Cron::run_jobs($jobs); + } elseif ($cron_action == 'delete' && $jobs) { + \TorrentPier\Legacy\Admin\Cron::delete_jobs($jobs); + } elseif (($cron_action == 'disable' || $cron_action == 'enable') && $jobs) { + \TorrentPier\Legacy\Admin\Cron::toggle_active($jobs, $cron_action); + } + redirect('admin/' . basename(__FILE__) . '?mode=list'); + } elseif (\TorrentPier\Legacy\Admin\Cron::validate_cron_post($_POST) == 1) { + if ($mode2 == 'edit') { + \TorrentPier\Legacy\Admin\Cron::update_cron_job($_POST); + } elseif ($mode2 == 'add') { + \TorrentPier\Legacy\Admin\Cron::insert_cron_job($_POST); + } else { + bb_die("Invalid mode: $mode2"); + } - redirect('admin/'.basename(__FILE__) . '?mode=list'); - } - else - { - bb_die(validate_cron_post($_POST)); - } + redirect('admin/' . basename(__FILE__) . '?mode=list'); + } else { + bb_die(\TorrentPier\Legacy\Admin\Cron::validate_cron_post($_POST)); + } } -print_page('admin_cron.tpl', 'admin'); \ No newline at end of file +print_page('admin_cron.tpl', 'admin'); diff --git a/admin/admin_disallow.php b/admin/admin_disallow.php index 6fe2ef3b9..bdf424dcf 100644 --- a/admin/admin_disallow.php +++ b/admin/admin_disallow.php @@ -1,95 +1,86 @@ escape($disallowed_user) . "')"; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not add disallowed user'); + } + $message = $lang['DISALLOW_SUCCESSFUL']; + } - if ($disallowed_user == '') - { - bb_die($lang['FIELDS_EMPTY']); - } - if( !validate_username($disallowed_user) ) - { - $message = $lang['DISALLOWED_ALREADY']; - } - else - { - $sql = "INSERT INTO " . BB_DISALLOW . " (disallow_username) VALUES('" . DB()->escape($disallowed_user) . "')"; - $result = DB()->sql_query( $sql ); - if (!$result) - { - bb_die('Could not add disallowed user'); - } - $message = $lang['DISALLOW_SUCCESSFUL']; - } + $message .= '

' . sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - $message .= '

'. sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') . '

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); +} elseif (isset($_POST['delete_name'])) { + $disallowed_id = isset($_POST['disallowed_id']) ? (int)$_POST['disallowed_id'] : (int)$_GET['disallowed_id']; - bb_die($message); -} -elseif (isset($_POST['delete_name'])) -{ - $disallowed_id = (isset($_POST['disallowed_id']) ) ? intval( $_POST['disallowed_id'] ) : intval( $_GET['disallowed_id']); + if (!empty($disallowed_id)) { + $sql = 'DELETE FROM ' . BB_DISALLOW . " WHERE disallow_id = $disallowed_id"; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not removed disallowed user'); + } - $sql = "DELETE FROM " . BB_DISALLOW . " WHERE disallow_id = $disallowed_id"; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not removed disallowed user'); - } - - $message .= $lang['DISALLOWED_DELETED'] .'

'. sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') .'

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - - bb_die($message); + $message .= $lang['DISALLOWED_DELETED'] . '

' . sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); + } } -// -// Grab the current list of disallowed usernames... -// -$sql = "SELECT * FROM " . BB_DISALLOW; +/** + * Grab the current list of disallowed usernames + */ +$sql = 'SELECT * FROM ' . BB_DISALLOW; $result = DB()->sql_query($sql); -if (!$result) -{ - bb_die('Could not get disallowed users'); +if (!$result) { + bb_die('Could not get disallowed users'); } $disallowed = DB()->sql_fetchrowset($result); -// -// Ok now generate the info for the template, which will be put out no matter -// what mode we are in. -// +/** + * Now generate the info for the template, which will be put out no matter what mode we are in + */ $disallow_select = ''; -$template->assign_vars(array( - 'S_DISALLOW_SELECT' => $disallow_select, - 'S_FORM_ACTION' => 'admin_disallow.php', -)); +$template->assign_vars([ + 'S_DISALLOW_SELECT' => $disallow_select, + 'S_FORM_ACTION' => 'admin_disallow.php', +]); -print_page('admin_disallow.tpl', 'admin'); \ No newline at end of file +print_page('admin_disallow.tpl', 'admin'); diff --git a/admin/admin_extensions.php b/admin/admin_extensions.php index d36b997c7..639bbc8a6 100644 --- a/admin/admin_extensions.php +++ b/admin/admin_extensions.php @@ -1,36 +1,35 @@ update('attach_extensions'); } -require('./pagestart.php'); -function update_attach_extensions () { - $GLOBALS['datastore']->update('attach_extensions'); -} register_shutdown_function('update_attach_extensions'); -if (($attach_config['upload_dir'][0] == '/') || (($attach_config['upload_dir'][0] != '/') && ($attach_config['upload_dir'][1] == ':'))) -{ - $upload_dir = $attach_config['upload_dir']; -} -else -{ - $upload_dir = BB_ROOT . $attach_config['upload_dir']; +if (($attach_config['upload_dir'][0] == '/') || (($attach_config['upload_dir'][0] != '/') && ($attach_config['upload_dir'][1] == ':'))) { + $upload_dir = $attach_config['upload_dir']; +} else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; } -include(ATTACH_DIR .'includes/functions_selects.php'); - -// Check if the language got included -if (!isset($lang['TEST_SETTINGS_SUCCESSFUL'])) -{ - // include_once is used within the function - include_attach_lang(); -} +include ATTACH_DIR . '/includes/functions_selects.php'; // Init Vars $types_download = array(INLINE_LINK, PHYSICAL_LINK); @@ -43,738 +42,636 @@ $size = get_var('size', ''); $mode = get_var('mode', ''); $e_mode = get_var('e_mode', ''); -$submit = (isset($_POST['submit'])) ? TRUE : FALSE; +$error = false; +$add_forum = isset($_POST['add_forum']); +$delete_forum = isset($_POST['del_forum']); +$submit = isset($_POST['submit']); -// Get Attachment Config -$attach_config = array(); - -$sql = 'SELECT * FROM '. BB_ATTACH_CONFIG; - -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not query attachment information'); +// Check for demo mode +if (IN_DEMO_MODE && ($submit || $add_forum || $delete_forum)) { + bb_die($lang['CANT_EDIT_IN_DEMO_MODE']); } -while ($row = DB()->sql_fetchrow($result)) -{ - $attach_config[$row['config_name']] = trim($row['config_value']); +// Get Attachment Config +$attach_config = []; + +$sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; + +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information'); +} + +while ($row = DB()->sql_fetchrow($result)) { + $attach_config[$row['config_name']] = trim($row['config_value']); } DB()->sql_freeresult($result); // Extension Management -if ($submit && $mode == 'extensions') -{ - // Change Extensions ? - $extension_change_list = get_var('extension_change_list', array(0)); - $extension_explain_list = get_var('extension_explain_list', array('')); - $group_select_list = get_var('group_select', array(0)); +if ($submit && $mode == 'extensions') { + // Change Extensions ? + $extension_change_list = get_var('extension_change_list', array(0)); + $extension_explain_list = get_var('extension_explain_list', array('')); + $group_select_list = get_var('group_select', array(0)); - // Generate correct Change List - $extensions = array(); + // Generate correct Change List + $extensions = []; - for ($i = 0; $i < sizeof($extension_change_list); $i++) - { - $extensions['_' . $extension_change_list[$i]]['comment'] = $extension_explain_list[$i]; - $extensions['_' . $extension_change_list[$i]]['group_id'] = intval($group_select_list[$i]); - } + for ($i = 0, $iMax = count($extension_change_list); $i < $iMax; $i++) { + $extensions['_' . $extension_change_list[$i]]['comment'] = $extension_explain_list[$i]; + $extensions['_' . $extension_change_list[$i]]['group_id'] = (int)$group_select_list[$i]; + } - $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY ext_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get extension informations #1'); - } + $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY ext_id'; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get extension informations #1'); + } - $num_rows = DB()->num_rows($result); - $extension_row = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + $extension_row = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - for ($i = 0; $i < sizeof($extension_row); $i++) - { - if ($extension_row[$i]['comment'] != $extensions['_' . $extension_row[$i]['ext_id']]['comment'] || intval($extension_row[$i]['group_id']) != intval($extensions['_' . $extension_row[$i]['ext_id']]['group_id'])) - { - $sql_ary = array( - 'comment' => (string) $extensions['_' . $extension_row[$i]['ext_id']]['comment'], - 'group_id' => (int) $extensions['_' . $extension_row[$i]['ext_id']]['group_id'] - ); + if ($num_rows > 0) { + for ($i = 0, $iMax = count($extension_row); $i < $iMax; $i++) { + if ($extension_row[$i]['comment'] != $extensions['_' . $extension_row[$i]['ext_id']]['comment'] || (int)$extension_row[$i]['group_id'] != (int)$extensions['_' . $extension_row[$i]['ext_id']]['group_id']) { + $sql_ary = array( + 'comment' => (string)$extensions['_' . $extension_row[$i]['ext_id']]['comment'], + 'group_id' => (int)$extensions['_' . $extension_row[$i]['ext_id']]['group_id'] + ); - $sql = 'UPDATE ' . BB_EXTENSIONS . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' - WHERE ext_id = ' . (int) $extension_row[$i]['ext_id']; + $sql = 'UPDATE ' . BB_EXTENSIONS . ' SET ' . DB()->build_array('UPDATE', $sql_ary) . ' + WHERE ext_id = ' . (int)$extension_row[$i]['ext_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update extension informations'); - } - } - } - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update extension informations'); + } + } + } + } - // Delete Extension? - $extension_id_list = get_var('extension_id_list', array(0)); + // Delete Extension? + $extension_id_list = get_var('extension_id_list', array(0)); - $extension_id_sql = implode(', ', $extension_id_list); + $extension_id_sql = implode(', ', $extension_id_list); - if ($extension_id_sql != '') - { - $sql = 'DELETE FROM ' . BB_EXTENSIONS . ' WHERE ext_id IN (' . $extension_id_sql . ')'; + if ($extension_id_sql != '') { + $sql = 'DELETE FROM ' . BB_EXTENSIONS . ' WHERE ext_id IN (' . $extension_id_sql . ')'; - if( !$result = DB()->sql_query($sql) ) - { - bb_die('Could not delete extensions'); - } - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not delete extensions'); + } + } - // Add Extension ? - $extension = get_var('add_extension', ''); - $extension_explain = get_var('add_extension_explain', ''); - $extension_group = get_var('add_group_select', 0); - $add = ( isset($_POST['add_extension_check']) ) ? TRUE : FALSE; + // Add Extension ? + $extension = get_var('add_extension', ''); + $extension_explain = get_var('add_extension_explain', ''); + $extension_group = get_var('add_group_select', 0); + $add = isset($_POST['add_extension_check']); - if ($extension != '' && $add) - { - $template->assign_vars(array( - 'ADD_EXTENSION' => $extension, - 'ADD_EXTENSION_EXPLAIN' => $extension_explain, - )); + if ($extension != '' && $add) { + $template->assign_vars(array( + 'ADD_EXTENSION' => $extension, + 'ADD_EXTENSION_EXPLAIN' => $extension_explain, + )); - if (!@$error) - { - // check extension - $sql = 'SELECT extension FROM ' . BB_EXTENSIONS; + if (!$error) { + // check extension + $sql = 'SELECT extension FROM ' . BB_EXTENSIONS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extensions'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extensions'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - for ($i = 0; $i < $num_rows; $i++) - { - if (strtolower(trim($row[$i]['extension'])) == strtolower(trim($extension))) - { - $error = TRUE; - if( isset($error_msg) ) - { - $error_msg .= '
'; - } - $error_msg .= sprintf($lang['EXTENSION_EXIST'], strtolower(trim($extension))); - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if (strtolower(trim($row[$i]['extension'])) == strtolower(trim($extension))) { + $error = true; + if (isset($error_msg)) { + $error_msg .= '
'; + } + $error_msg .= sprintf($lang['EXTENSION_EXIST'], strtolower(trim($extension))); + } + } + } - if (!@$error) - { - $sql_ary = array( - 'group_id' => (int) $extension_group, - 'extension' => (string) strtolower($extension), - 'comment' => (string) $extension_explain - ); + if (!$error) { + $sql_ary = array( + 'group_id' => (int)$extension_group, + 'extension' => (string)strtolower($extension), + 'comment' => (string)$extension_explain + ); - $sql = 'INSERT INTO ' . BB_EXTENSIONS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_EXTENSIONS . ' ' . DB()->build_array('INSERT', $sql_ary); - if (!DB()->sql_query($sql)) - { - bb_die('Could not add extension'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not add extension'); + } + } + } + } - } - } - } - - if (!@$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'extensions') -{ - // Extensions - $template->assign_vars(array( - 'TPL_ATTACH_EXTENSIONS' => true, - 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=extensions', - 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=extensions', - )); +if ($mode == 'extensions') { + // Extensions + $template->assign_vars(array( + 'TPL_ATTACH_EXTENSIONS' => true, + 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=extensions', + 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=extensions', + )); - if ($submit) - { - $template->assign_vars(array( - 'S_ADD_GROUP_SELECT' => group_select('add_group_select', $extension_group)) - ); - } - else - { - $template->assign_vars(array( - 'S_ADD_GROUP_SELECT' => group_select('add_group_select')) - ); - } + if ($submit) { + $template->assign_vars(array( + 'S_ADD_GROUP_SELECT' => group_select('add_group_select', $extension_group)) + ); + } else { + $template->assign_vars(array( + 'S_ADD_GROUP_SELECT' => group_select('add_group_select')) + ); + } - $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY group_id'; + $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY group_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get extension informations #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get extension informations #2'); + } - $extension_row = DB()->sql_fetchrowset($result); - $num_extension_row = DB()->num_rows($result); - DB()->sql_freeresult($result); + $extension_row = DB()->sql_fetchrowset($result); + $num_extension_row = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_extension_row > 0) - { - $extension_row = sort_multi_array($extension_row, 'group_name', 'ASC'); - - for ($i = 0; $i < $num_extension_row; $i++) - { - if ($submit) - { - $template->assign_block_vars('extension_row', array( - 'EXT_ID' => $extension_row[$i]['ext_id'], - 'EXTENSION' => $extension_row[$i]['extension'], - 'EXTENSION_EXPLAIN' => $extension_explain_list[$i], - 'S_GROUP_SELECT' => group_select('group_select[]', $group_select_list[$i])) - ); - } - else - { - $template->assign_block_vars('extension_row', array( - 'EXT_ID' => $extension_row[$i]['ext_id'], - 'EXTENSION' => $extension_row[$i]['extension'], - 'EXTENSION_EXPLAIN' => $extension_row[$i]['comment'], - 'S_GROUP_SELECT' => group_select('group_select[]', $extension_row[$i]['group_id'])) - ); - } - } - } + if ($num_extension_row > 0) { + $extension_row = sort_multi_array($extension_row, 'group_id'); + for ($i = 0; $i < $num_extension_row; $i++) { + if ($submit) { + $template->assign_block_vars('extension_row', array( + 'EXT_ID' => $extension_row[$i]['ext_id'], + 'EXTENSION' => $extension_row[$i]['extension'], + 'EXTENSION_EXPLAIN' => $extension_explain_list[$i], + 'S_GROUP_SELECT' => group_select('group_select[]', $group_select_list[$i])) + ); + } else { + $template->assign_block_vars('extension_row', array( + 'EXT_ID' => $extension_row[$i]['ext_id'], + 'EXTENSION' => $extension_row[$i]['extension'], + 'EXTENSION_EXPLAIN' => $extension_row[$i]['comment'], + 'S_GROUP_SELECT' => group_select('group_select[]', $extension_row[$i]['group_id'])) + ); + } + } + } } // Extension Groups -if ($submit && $mode == 'groups') -{ - // Change Extension Groups ? - $group_change_list = get_var('group_change_list', array(0)); - $extension_group_list = get_var('extension_group_list', array('')); - $group_allowed_list = get_var('allowed_list', array(0)); - $download_mode_list = get_var('download_mode_list', array(0)); - $category_list = get_var('category_list', array(0)); - $upload_icon_list = get_var('upload_icon_list', array('')); - $filesize_list = get_var('max_filesize_list', array(0)); - $size_select_list = get_var('size_select_list', array('')); +if ($submit && $mode == 'groups') { + // Change Extension Groups ? + $group_change_list = get_var('group_change_list', array(0)); + $extension_group_list = get_var('extension_group_list', array('')); + $group_allowed_list = get_var('allowed_list', array(0)); + $download_mode_list = get_var('download_mode_list', array(0)); + $category_list = get_var('category_list', array(0)); + $upload_icon_list = get_var('upload_icon_list', array('')); + $filesize_list = get_var('max_filesize_list', array(0)); + $size_select_list = get_var('size_select_list', array('')); - $allowed_list = array(); + $allowed_list = []; - for ($i = 0; $i < sizeof($group_allowed_list); $i++) - { - for ($j = 0; $j < sizeof($group_change_list); $j++) - { - if ($group_allowed_list[$i] == $group_change_list[$j]) - { - $allowed_list[$j] = 1; - } - } - } + foreach ($group_allowed_list as $iValue) { + for ($j = 0, $jMax = count($group_change_list); $j < $jMax; $j++) { + if ($iValue == $group_change_list[$j]) { + $allowed_list[$j] = 1; + } + } + } - for ($i = 0; $i < sizeof($group_change_list); $i++) - { - $allowed = (isset($allowed_list[$i])) ? 1 : 0; + for ($i = 0, $iMax = count($group_change_list); $i < $iMax; $i++) { + $allowed = isset($allowed_list[$i]) ? 1 : 0; - $filesize_list[$i] = ($size_select_list[$i] == 'kb') ? round($filesize_list[$i] * 1024) : ( ($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i] ); + $filesize_list[$i] = ($size_select_list[$i] == 'kb') ? round($filesize_list[$i] * 1024) : (($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i]); - $sql_ary = array( - 'group_name' => (string) $extension_group_list[$i], - 'cat_id' => (int) $category_list[$i], - 'allow_group' => (int) $allowed, - 'download_mode' => (int) $download_mode_list[$i], - 'upload_icon' => (string) $upload_icon_list[$i], - 'max_filesize' => (int) $filesize_list[$i] - ); + $sql_ary = array( + 'group_name' => (string)$extension_group_list[$i], + 'cat_id' => (int)$category_list[$i], + 'allow_group' => (int)$allowed, + 'download_mode' => (int)$download_mode_list[$i], + 'upload_icon' => (string)$upload_icon_list[$i], + 'max_filesize' => (int)$filesize_list[$i] + ); - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' - WHERE group_id = ' . (int) $group_change_list[$i]; + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' SET ' . DB()->build_array('UPDATE', $sql_ary) . ' + WHERE group_id = ' . (int)$group_change_list[$i]; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not update extension groups informations'); - } - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update extension groups informations'); + } + } - // Delete Extension Groups - $group_id_list = get_var('group_id_list', array(0)); + // Delete Extension Groups + $group_id_list = get_var('group_id_list', array(0)); - $group_id_sql = implode(', ', $group_id_list); + $group_id_sql = implode(', ', $group_id_list); - if ($group_id_sql != '') - { - $sql = 'DELETE + if ($group_id_sql != '') { + $sql = 'DELETE FROM ' . BB_EXTENSION_GROUPS . ' WHERE group_id IN (' . $group_id_sql . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not delete extension groups'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete extension groups'); + } - // Set corresponding Extensions to a pending Group - $sql = 'UPDATE ' . BB_EXTENSIONS . ' + // Set corresponding Extensions to a pending Group + $sql = 'UPDATE ' . BB_EXTENSIONS . ' SET group_id = 0 WHERE group_id IN (' . $group_id_sql . ')'; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not assign extensions to pending group'); - } - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not assign extensions to pending group'); + } + } - // Add Extensions? - $extension_group = get_var('add_extension_group', ''); - $download_mode = get_var('add_download_mode', 0); - $cat_id = get_var('add_category', 0); - $upload_icon = get_var('add_upload_icon', ''); - $filesize = get_var('add_max_filesize', 0); - $size_select = get_var('add_size_select', ''); + // Add Extensions? + $extension_group = get_var('add_extension_group', ''); + $download_mode = get_var('add_download_mode', 0); + $cat_id = get_var('add_category', 0); + $upload_icon = get_var('add_upload_icon', ''); + $filesize = get_var('add_max_filesize', 0); + $size_select = get_var('add_size_select', ''); - $is_allowed = (isset($_POST['add_allowed'])) ? 1 : 0; - $add = ( isset($_POST['add_extension_group_check']) ) ? TRUE : FALSE; + $is_allowed = isset($_POST['add_allowed']) ? 1 : 0; + $add = isset($_POST['add_extension_group_check']); - if ($extension_group != '' && $add) - { - // check Extension Group - $sql = 'SELECT group_name FROM ' . BB_EXTENSION_GROUPS; + if ($extension_group != '' && $add) { + // check Extension Group + $sql = 'SELECT group_name FROM ' . BB_EXTENSION_GROUPS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extension groups table'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups table'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - for ($i = 0; $i < $num_rows; $i++) - { - if ($row[$i]['group_name'] == $extension_group) - { - $error = TRUE; - if( isset($error_msg) ) - { - $error_msg .= '
'; - } - $error_msg .= sprintf($lang['EXTENSION_GROUP_EXIST'], $extension_group); - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if ($row[$i]['group_name'] == $extension_group) { + $error = true; + if (isset($error_msg)) { + $error_msg .= '
'; + } + $error_msg .= sprintf($lang['EXTENSION_GROUP_EXIST'], $extension_group); + } + } + } - if (!@$error) - { - $filesize = ($size_select == 'kb') ? round($filesize * 1024) : ( ($size_select == 'mb') ? round($filesize * 1048576) : $filesize ); + if (!$error) { + $filesize = ($size_select == 'kb') ? round($filesize * 1024) : (($size_select == 'mb') ? round($filesize * 1048576) : $filesize); - $sql_ary = array( - 'group_name' => (string) $extension_group, - 'cat_id' => (int) $cat_id, - 'allow_group' => (int) $is_allowed, - 'download_mode' => (int) $download_mode, - 'upload_icon' => (string) $upload_icon, - 'max_filesize' => (int) $filesize, - 'forum_permissions' => '' - ); + $sql_ary = array( + 'group_name' => (string)$extension_group, + 'cat_id' => (int)$cat_id, + 'allow_group' => (int)$is_allowed, + 'download_mode' => (int)$download_mode, + 'upload_icon' => (string)$upload_icon, + 'max_filesize' => (int)$filesize, + 'forum_permissions' => '' + ); - $sql = 'INSERT INTO ' . BB_EXTENSION_GROUPS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_EXTENSION_GROUPS . ' ' . DB()->build_array('INSERT', $sql_ary); - if (!(DB()->sql_query($sql))) - { - bb_die('Could not add extension group'); - } - } + if (!DB()->sql_query($sql)) { + bb_die('Could not add extension group'); + } + } + } - } - - if (!@$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'groups') -{ - // Extension Groups - if (!$size && !$submit) - { - $max_add_filesize = $attach_config['max_filesize']; +if ($mode == 'groups') { + // Extension Groups + if (!$size && !$submit) { + $max_add_filesize = $attach_config['max_filesize']; - $size = ($max_add_filesize >= 1048576) ? 'mb' : ( ($max_add_filesize >= 1024) ? 'kb' : 'b' ); - } + $size = ($max_add_filesize >= 1048576) ? 'mb' : (($max_add_filesize >= 1024) ? 'kb' : 'b'); + } - if ($max_add_filesize >= 1048576) - { - $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; - } - else if ( $max_add_filesize >= 1024) - { - $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; - } + if ($max_add_filesize >= 1048576) { + $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; + } elseif ($max_add_filesize >= 1024) { + $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; + } - $viewgroup = get_var(POST_GROUPS_URL, 0); + $viewgroup = get_var(POST_GROUPS_URL, 0); - $template->assign_vars(array( - 'TPL_ATTACH_EXTENSION_GROUPS' => true, - 'ADD_GROUP_NAME' => ( isset($submit) ) ? @$extension_group : '', - 'MAX_FILESIZE' => $max_add_filesize, - 'S_FILESIZE' => size_select('add_size_select', $size), - 'S_ADD_DOWNLOAD_MODE' => download_select('add_download_mode'), - 'S_SELECT_CAT' => category_select('add_category'), - 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=groups', - 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=groups', - )); + $template->assign_vars(array( + 'TPL_ATTACH_EXTENSION_GROUPS' => true, + 'ADD_GROUP_NAME' => $extension_group ?? '', + 'MAX_FILESIZE' => $max_add_filesize, + 'S_FILESIZE' => size_select('add_size_select', $size), + 'S_ADD_DOWNLOAD_MODE' => download_select('add_download_mode'), + 'S_SELECT_CAT' => category_select('add_category'), + 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=groups', + 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=groups', + )); - $sql = 'SELECT * FROM ' . BB_EXTENSION_GROUPS; + $sql = 'SELECT * FROM ' . BB_EXTENSION_GROUPS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get extension group informations'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get extension group informations'); + } - $extension_group = DB()->sql_fetchrowset($result); - $num_extension_group = DB()->num_rows($result); - DB()->sql_freeresult($result); + $extension_group = DB()->sql_fetchrowset($result); + $num_extension_group = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_extension_group; $i++) - { - // Format the filesize - if (!$extension_group[$i]['max_filesize']) - { - $extension_group[$i]['max_filesize'] = $attach_config['max_filesize']; - } + for ($i = 0; $i < $num_extension_group; $i++) { + // Format the filesize + if (!$extension_group[$i]['max_filesize']) { + $extension_group[$i]['max_filesize'] = $attach_config['max_filesize']; + } - $size_format = ($extension_group[$i]['max_filesize'] >= 1048576) ? 'mb' : ( ($extension_group[$i]['max_filesize'] >= 1024) ? 'kb' : 'b' ); + $size_format = ($extension_group[$i]['max_filesize'] >= 1048576) ? 'mb' : (($extension_group[$i]['max_filesize'] >= 1024) ? 'kb' : 'b'); - if ( $extension_group[$i]['max_filesize'] >= 1048576) - { - $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1048576 * 100) / 100; - } - else if($extension_group[$i]['max_filesize'] >= 1024) - { - $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1024 * 100) / 100; - } + if ($extension_group[$i]['max_filesize'] >= 1048576) { + $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1048576 * 100) / 100; + } elseif ($extension_group[$i]['max_filesize'] >= 1024) { + $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1024 * 100) / 100; + } - $s_allowed = ($extension_group[$i]['allow_group'] == 1) ? 'checked="checked"' : ''; + $s_allowed = ($extension_group[$i]['allow_group'] == 1) ? 'checked' : ''; - $template->assign_block_vars('grouprow', array( - 'GROUP_ID' => $extension_group[$i]['group_id'], - 'EXTENSION_GROUP' => $extension_group[$i]['group_name'], - 'UPLOAD_ICON' => $extension_group[$i]['upload_icon'], + $template->assign_block_vars('grouprow', array( + 'GROUP_ID' => $extension_group[$i]['group_id'], + 'EXTENSION_GROUP' => $extension_group[$i]['group_name'], + 'UPLOAD_ICON' => $extension_group[$i]['upload_icon'], - 'S_ALLOW_SELECTED' => $s_allowed, - 'S_SELECT_CAT' => category_select('category_list[]', $extension_group[$i]['group_id']), - 'S_DOWNLOAD_MODE' => download_select('download_mode_list[]', $extension_group[$i]['group_id']), - 'S_FILESIZE' => size_select('size_select_list[]', $size_format), + 'S_ALLOW_SELECTED' => $s_allowed, + 'S_SELECT_CAT' => category_select('category_list[]', $extension_group[$i]['group_id']), + 'S_DOWNLOAD_MODE' => download_select('download_mode_list[]', $extension_group[$i]['group_id']), + 'S_FILESIZE' => size_select('size_select_list[]', $size_format), - 'MAX_FILESIZE' => $extension_group[$i]['max_filesize'], - 'CAT_BOX' => ( $viewgroup == $extension_group[$i]['group_id'] ) ? '+' : '-', - 'U_VIEWGROUP' => ( $viewgroup == $extension_group[$i]['group_id'] ) ? "admin_extensions.php?mode=groups" : "admin_extensions.php?mode=groups&" . POST_GROUPS_URL . "=" . $extension_group[$i]['group_id'], - 'U_FORUM_PERMISSIONS' => "admin_extensions.php?mode=$mode&e_mode=perm&e_group=" . $extension_group[$i]['group_id'], - )); + 'MAX_FILESIZE' => $extension_group[$i]['max_filesize'], + 'CAT_BOX' => ($viewgroup == $extension_group[$i]['group_id']) ? '-' : '+', + 'U_VIEWGROUP' => ($viewgroup == $extension_group[$i]['group_id']) ? 'admin_extensions.php?mode=groups' : 'admin_extensions.php?mode=groups&' . POST_GROUPS_URL . '=' . $extension_group[$i]['group_id'], + 'U_FORUM_PERMISSIONS' => "admin_extensions.php?mode=$mode&e_mode=perm&e_group=" . $extension_group[$i]['group_id'], + )); - if ($viewgroup && $viewgroup == $extension_group[$i]['group_id']) - { - $sql = 'SELECT comment, extension FROM ' . BB_EXTENSIONS . ' WHERE group_id = ' . (int) $viewgroup; + if ($viewgroup && $viewgroup == $extension_group[$i]['group_id']) { + $sql = 'SELECT comment, extension FROM ' . BB_EXTENSIONS . ' WHERE group_id = ' . (int)$viewgroup; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get extension informations #3'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get extension informations #3'); + } - $extension = DB()->sql_fetchrowset($result); - $num_extension = DB()->num_rows($result); - DB()->sql_freeresult($result); + $extension = DB()->sql_fetchrowset($result); + $num_extension = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($j = 0; $j < $num_extension; $j++) - { - $template->assign_block_vars('grouprow.extensionrow', array( - 'EXPLANATION' => $extension[$j]['comment'], - 'EXTENSION' => $extension[$j]['extension']) - ); - } - } - } + for ($j = 0; $j < $num_extension; $j++) { + $template->assign_block_vars('grouprow.extensionrow', array( + 'EXPLANATION' => $extension[$j]['comment'], + 'EXTENSION' => $extension[$j]['extension']) + ); + } + } + } } -if ($e_mode == 'perm') -{ - $group = get_var('e_group', 0); +if ($e_mode == 'perm') { + $group = get_var('e_group', 0); - $add_forum = (isset($_POST['add_forum'])) ? TRUE : FALSE; - $delete_forum = (isset($_POST['del_forum'])) ? TRUE : FALSE; - - if (isset($_POST['close_perm'])) - { - $e_mode = ''; - } + if (isset($_POST['close_perm'])) { + $e_mode = ''; + } } // Add Forums -if (@$add_forum && $e_mode == 'perm' && $group) -{ - $add_forums_list = get_var('entries', array(0)); - $add_all_forums = FALSE; +if ($add_forum && $e_mode == 'perm' && $group) { + $add_forums_list = get_var('entries', array(0)); + $add_all_forums = false; - for ($i = 0; $i < sizeof($add_forums_list); $i++) - { - if ($add_forums_list[$i] == 0) - { - $add_all_forums = TRUE; - } - } + foreach ($add_forums_list as $iValue) { + if ($iValue == 0) { + $add_all_forums = true; + } + } - // If we add ALL FORUMS, we are able to overwrite the Permissions - if ($add_all_forums) - { - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '' WHERE group_id = " . (int) $group; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update permissions #1'); - } - } + // If we add ALL FORUMS, we are able to overwrite the Permissions + if ($add_all_forums) { + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '' WHERE group_id = " . (int)$group; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update permissions #1'); + } + } - // Else we have to add Permissions - if (!$add_all_forums) - { - $sql = 'SELECT forum_permissions + // Else we have to add Permissions + if (!$add_all_forums) { + $sql = 'SELECT forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' - WHERE group_id = ' . intval($group) . ' + WHERE group_id = ' . (int)$group . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - if (trim($row['forum_permissions']) == '') - { - $auth_p = array(); - } - else - { - $auth_p = auth_unpack($row['forum_permissions']); - } + if (trim($row['forum_permissions']) == '') { + $auth_p = []; + } else { + $auth_p = auth_unpack($row['forum_permissions']); + } - // Generate array for Auth_Pack, do not add doubled forums - for ($i = 0; $i < sizeof($add_forums_list); $i++) - { - if (!in_array($add_forums_list[$i], $auth_p)) - { - $auth_p[] = $add_forums_list[$i]; - } - } + // Generate array for Auth_Pack, do not add doubled forums + foreach ($add_forums_list as $i => $iValue) { + if (!in_array($add_forums_list[$i], $auth_p)) { + $auth_p[] = $iValue; + } + } - $auth_bitstream = auth_pack($auth_p); + $auth_bitstream = auth_pack($auth_p); - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . attach_mod_sql_escape($auth_bitstream) . "' WHERE group_id = " . (int) $group; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update permissions #2'); - } - } + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . DB()->escape($auth_bitstream) . "' WHERE group_id = " . (int)$group; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update permissions #2'); + } + } } // Delete Forums -if (@$delete_forum && $e_mode == 'perm' && $group) -{ - $delete_forums_list = get_var('entries', array(0)); +if ($delete_forum && $e_mode == 'perm' && $group) { + $delete_forums_list = get_var('entries', array(0)); - // Get the current Forums - $sql = 'SELECT forum_permissions + // Get the current Forums + $sql = 'SELECT forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' - WHERE group_id = ' . intval($group) . ' + WHERE group_id = ' . (int)$group . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $auth_p2 = auth_unpack(trim($row['forum_permissions'])); - $auth_p = array(); + $auth_p2 = auth_unpack(trim($row['forum_permissions'])); + $auth_p = []; - // Generate array for Auth_Pack, delete the chosen ones - for ($i = 0; $i < sizeof($auth_p2); $i++) - { - if (!in_array($auth_p2[$i], $delete_forums_list)) - { - $auth_p[] = $auth_p2[$i]; - } - } + // Generate array for Auth_Pack, delete the chosen ones + foreach ($auth_p2 as $i => $iValue) { + if (!in_array($auth_p2[$i], $delete_forums_list)) { + $auth_p[] = $iValue; + } + } - $auth_bitstream = (sizeof($auth_p) > 0) ? auth_pack($auth_p) : ''; + $auth_bitstream = (count($auth_p) > 0) ? auth_pack($auth_p) : ''; - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . attach_mod_sql_escape($auth_bitstream) . "' WHERE group_id = " . (int) $group; + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . DB()->escape($auth_bitstream) . "' WHERE group_id = " . (int)$group; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update permissions #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update permissions #3'); + } } // Display the Group Permissions Box for configuring it -if ($e_mode == 'perm' && $group) -{ - $sql = 'SELECT group_name, forum_permissions +if ($e_mode == 'perm' && $group) { + $sql = 'SELECT group_name, forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' - WHERE group_id = ' . intval($group) . ' + WHERE group_id = ' . (int)$group . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group name from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group name from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $group_name = $row['group_name']; - $allowed_forums = trim($row['forum_permissions']); + $group_name = $row['group_name']; + $allowed_forums = trim($row['forum_permissions']); - $forum_perm = array(); + $forum_perm = []; - if ($allowed_forums == '') - { - $forum_perm[0]['forum_id'] = 0; - $forum_perm[0]['forum_name'] = $lang['PERM_ALL_FORUMS']; - } - else - { - $forum_p = array(); - $act_id = 0; - $forum_p = auth_unpack($allowed_forums); - $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " WHERE forum_id IN (" . implode(', ', $forum_p) . ")"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get forum names'); - } + if ($allowed_forums == '') { + $forum_perm[0]['forum_id'] = 0; + $forum_perm[0]['forum_name'] = $lang['PERM_ALL_FORUMS']; + } else { + $forum_p = []; + $act_id = 0; + $forum_p = auth_unpack($allowed_forums); + $sql = 'SELECT forum_id, forum_name FROM ' . BB_FORUMS . ' WHERE forum_id IN (' . implode(', ', $forum_p) . ')'; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get forum names'); + } - while ($row = DB()->sql_fetchrow($result)) - { - $forum_perm[$act_id]['forum_id'] = $row['forum_id']; - $forum_perm[$act_id]['forum_name'] = $row['forum_name']; - $act_id++; - } - } + while ($row = DB()->sql_fetchrow($result)) { + $forum_perm[$act_id]['forum_id'] = $row['forum_id']; + $forum_perm[$act_id]['forum_name'] = $row['forum_name']; + $act_id++; + } + } - for ($i = 0; $i < sizeof($forum_perm); $i++) - { - $template->assign_block_vars('allow_option_values', array( - 'VALUE' => $forum_perm[$i]['forum_id'], - 'OPTION' => htmlCHR($forum_perm[$i]['forum_name'])) - ); - } + for ($i = 0, $iMax = count($forum_perm); $i < $iMax; $i++) { + $template->assign_block_vars('allow_option_values', array( + 'VALUE' => $forum_perm[$i]['forum_id'], + 'OPTION' => htmlCHR($forum_perm[$i]['forum_name'])) + ); + } - $template->assign_vars(array( - 'TPL_ATTACH_EXTENSION_GROUPS_PERMISSIONS' => true, - 'L_GROUP_PERMISSIONS_TITLE' => sprintf($lang['GROUP_PERMISSIONS_TITLE_ADMIN'], trim($group_name)), - 'A_PERM_ACTION' => "admin_extensions.php?mode=groups&e_mode=perm&e_group=$group", - )); + $template->assign_vars(array( + 'TPL_ATTACH_EXTENSION_GROUPS_PERMISSIONS' => true, + 'L_GROUP_PERMISSIONS_TITLE' => sprintf($lang['GROUP_PERMISSIONS_TITLE_ADMIN'], trim($group_name)), + 'A_PERM_ACTION' => "admin_extensions.php?mode=groups&e_mode=perm&e_group=$group", + )); - $forum_option_values = array(0 => $lang['PERM_ALL_FORUMS']); + $forum_option_values = array(0 => $lang['PERM_ALL_FORUMS']); - $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS; + $sql = 'SELECT forum_id, forum_name FROM ' . BB_FORUMS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get forums #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get forums #1'); + } - while ($row = DB()->sql_fetchrow($result)) - { - $forum_option_values[intval($row['forum_id'])] = $row['forum_name']; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $forum_option_values[(int)$row['forum_id']] = $row['forum_name']; + } + DB()->sql_freeresult($result); - foreach ($forum_option_values as $value => $option) - { - $template->assign_block_vars('forum_option_values', array( - 'VALUE' => $value, - 'OPTION' => htmlCHR($option)) - ); - } + foreach ($forum_option_values as $value => $option) { + $template->assign_block_vars('forum_option_values', array( + 'VALUE' => $value, + 'OPTION' => htmlCHR($option)) + ); + } - $empty_perm_forums = array(); + $empty_perm_forums = []; - $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " WHERE auth_attachments < " . AUTH_ADMIN; + $sql = 'SELECT forum_id, forum_name FROM ' . BB_FORUMS . ' WHERE auth_attachments < ' . AUTH_ADMIN; - if (!($f_result = DB()->sql_query($sql))) - { - bb_die('Could not get forums #2'); - } + if (!($f_result = DB()->sql_query($sql))) { + bb_die('Could not get forums #2'); + } - while ($row = DB()->sql_fetchrow($f_result)) - { - $forum_id = $row['forum_id']; + while ($row = DB()->sql_fetchrow($f_result)) { + $forum_id = $row['forum_id']; - $sql = "SELECT forum_permissions - FROM " . BB_EXTENSION_GROUPS . " + $sql = 'SELECT forum_permissions + FROM ' . BB_EXTENSION_GROUPS . ' WHERE allow_group = 1 - ORDER BY group_name ASC"; + ORDER BY group_name ASC'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extension groups'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - $found_forum = FALSE; + $found_forum = false; - for ($i = 0; $i < $num_rows; $i++) - { - $allowed_forums = auth_unpack(trim($rows[$i]['forum_permissions'])); - if (in_array($forum_id, $allowed_forums) || trim($rows[$i]['forum_permissions']) == '') - { - $found_forum = TRUE; - break; - } - } + for ($i = 0; $i < $num_rows; $i++) { + $allowed_forums = auth_unpack(trim($rows[$i]['forum_permissions'])); + if (in_array($forum_id, $allowed_forums) || trim($rows[$i]['forum_permissions']) == '') { + $found_forum = true; + break; + } + } - if (!$found_forum) - { - $empty_perm_forums[$forum_id] = $row['forum_name']; - } - } - DB()->sql_freeresult($f_result); + if (!$found_forum) { + $empty_perm_forums[$forum_id] = $row['forum_name']; + } + } + DB()->sql_freeresult($f_result); - $message = ''; + $message = ''; - foreach ($empty_perm_forums as $forum_id => $forum_name) - { - $message .= ( $message == '' ) ? $forum_name : '
' . $forum_name; - } + foreach ($empty_perm_forums as $forum_id => $forum_name) { + $message .= ($message == '') ? $forum_name : '
' . $forum_name; + } - if (sizeof($empty_perm_forums) > 0) - { - $template->assign_vars(array('ERROR_MESSAGE' => $lang['NOTE_ADMIN_EMPTY_GROUP_PERMISSIONS'] . $message)); - } + if (count($empty_perm_forums) > 0) { + $template->assign_vars(array('ERROR_MESSAGE' => $lang['NOTE_ADMIN_EMPTY_GROUP_PERMISSIONS'] . $message)); + } } -if (@$error) -{ - $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); +if ($error) { + $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); } -print_page('admin_extensions.tpl', 'admin'); \ No newline at end of file +print_page('admin_extensions.tpl', 'admin'); diff --git a/admin/admin_forum_prune.php b/admin/admin_forum_prune.php index 86e8968e3..97a3a539b 100644 --- a/admin/admin_forum_prune.php +++ b/admin/admin_forum_prune.php @@ -1,60 +1,61 @@ fetch_rowset($sql) as $i => $row) - { - $pruned_topics = topic_delete('prune', $row['forum_id'], $prunetime, !empty($_POST['prune_all_topic_types'])); - $pruned_total += $pruned_topics; - $prune_performed = true; + foreach (DB()->fetch_rowset($sql) as $i => $row) { + $pruned_topics = \TorrentPier\Legacy\Admin\Common::topic_delete('prune', $row['forum_id'], $prunetime, !empty($_POST['prune_all_topic_types'])); + $pruned_total += $pruned_topics; + $prune_performed = true; - $template->assign_block_vars('pruned', array( - 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', - 'FORUM_NAME' => htmlCHR($row['forum_name']), - 'PRUNED_TOPICS' => $pruned_topics, - )); - } - if (!$prune_performed) - { - bb_die($lang['NONE_SELECTED']); - } - if (!$pruned_total) - { - bb_die($lang['NO_SEARCH_MATCH']); - } + $template->assign_block_vars('pruned', [ + 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', + 'FORUM_NAME' => htmlCHR($row['forum_name']), + 'PRUNED_TOPICS' => $pruned_topics + ]); + } + if (!$prune_performed) { + bb_die($lang['NONE_SELECTED']); + } + if (!$pruned_total) { + bb_die($lang['NO_SEARCH_MATCH']); + } } -$template->assign_vars(array( - 'PRUNED_TOTAL' => $pruned_total, - 'S_PRUNE_ACTION' => basename(__FILE__), - 'SEL_FORUM' => get_forum_select('admin', 'f[]', null, 65, 16, '', $all_forums), -)); +$template->assign_vars([ + 'PRUNED_TOTAL' => $pruned_total, + 'S_PRUNE_ACTION' => basename(__FILE__), + 'SEL_FORUM' => get_forum_select('admin', 'f[]', null, 65, 16, '', $all_forums) +]); -print_page('admin_forum_prune.tpl', 'admin'); \ No newline at end of file +print_page('admin_forum_prune.tpl', 'admin'); diff --git a/admin/admin_forumauth.php b/admin/admin_forumauth.php index f4798d3dc..fec7aa909 100644 --- a/admin/admin_forumauth.php +++ b/admin/admin_forumauth.php @@ -1,252 +1,228 @@ array(AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL, AUTH_ALL, AUTH_MOD, AUTH_MOD), // Public -/* Reg */ 1 => array(AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD), // Registered -/* Reg [Hid] */ 2 => array(AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD), // Registered [Hidden] -/* Priv */ 3 => array(AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD), // Private -/* Priv [Hid] */ 4 => array(AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD), // Private [Hidden] -/* MOD */ 5 => array(AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators -/* MOD [Hid] */ 6 => array(AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators [Hidden] -); +$simple_auth_ary = [ + 0 => [AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL, AUTH_ALL, AUTH_MOD, AUTH_MOD], // Public + 1 => [AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD], // Registered + 2 => [AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD], // Registered [Hidden] + 3 => [AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD], // Private + 4 => [AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD], // Private [Hidden] + 5 => [AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD], // Moderators + 6 => [AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD], // Moderators [Hidden] +]; -$simple_auth_types = array( - $lang['PUBLIC'], - $lang['REGISTERED'], - $lang['REGISTERED'] .' ['. $lang['HIDDEN'] .']', - $lang['PRIVATE'], - $lang['PRIVATE'] .' ['. $lang['HIDDEN'] .']', - $lang['MODERATORS'], - $lang['MODERATORS'] .' ['. $lang['HIDDEN'] .']', -); +$simple_auth_types = [ + $lang['PUBLIC'], + $lang['REGISTERED'], + $lang['REGISTERED'] . ' [' . $lang['HIDDEN'] . ']', + $lang['PRIVATE'], + $lang['PRIVATE'] . ' [' . $lang['HIDDEN'] . ']', + $lang['MODERATORS'], + $lang['MODERATORS'] . ' [' . $lang['HIDDEN'] . ']', +]; -$field_names = array(); -foreach ($forum_auth_fields as $auth_type) -{ - $field_names[$auth_type] = $lang[strtoupper($auth_type)]; +$field_names = []; +foreach ($forum_auth_fields as $auth_type) { + $field_names[$auth_type] = $lang[strtoupper($auth_type)]; } -$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); -$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); +$forum_auth_levels = ['ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN']; +$forum_auth_const = [AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN]; -if (@$_REQUEST[POST_FORUM_URL]) -{ - $forum_id = (int) $_REQUEST[POST_FORUM_URL]; - $forum_sql = "WHERE forum_id = $forum_id"; -} -else -{ - unset($forum_id); - $forum_sql = ''; +if (isset($_REQUEST[POST_FORUM_URL])) { + $forum_id = (int)$_REQUEST[POST_FORUM_URL]; + $forum_sql = "WHERE forum_id = $forum_id"; +} else { + unset($forum_id); + $forum_sql = ''; } -if( isset($_GET['adv']) ) -{ - $adv = intval($_GET['adv']); -} -else -{ - unset($adv); +if (isset($_GET['adv'])) { + $adv = (int)$_GET['adv']; +} else { + unset($adv); } -// -// Start program proper -// -if( isset($_POST['submit']) ) -{ - $sql = ''; +$submit = isset($_POST['submit']); - if(!empty($forum_id)) - { - if(isset($_POST['simpleauth'])) - { - $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; - - for($i = 0; $i < count($simple_ary); $i++) - { - $sql .= ( ( $sql != '' ) ? ', ' : '' ) . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; - } - - if (is_array($simple_ary)) - { - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } - } - else - { - for ($i = 0; $i < count($forum_auth_fields); $i++) - { - $value = intval($_POST[$forum_auth_fields[$i]]); - - if ($forum_auth_fields[$i] == 'auth_vote') - { - if ($_POST['auth_vote'] == AUTH_ALL) - { - $value = AUTH_REG; - } - } - - $sql .= ( ( $sql != '' ) ? ', ' : '' ) .$forum_auth_fields[$i] . ' = ' . $value; - } - - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } - - if ($sql != '') - { - if (!DB()->sql_query($sql)) - { - bb_die('Could not update auth table'); - } - } - - $forum_sql = ''; - $adv = 0; - } - - $datastore->update('cat_forums'); - bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); - -} // End of submit - -// -// Get required information, either all forums if -// no id was specified or just the requsted if it -// was -// -$forum_rows = DB()->fetch_rowset("SELECT * FROM ". BB_FORUMS ." $forum_sql"); - -if (empty($forum_id)) -{ - // Output the selection table if no forum id was specified - $template->assign_vars(array( - 'TPL_AUTH_SELECT_FORUM' => true, - 'S_AUTH_ACTION' => 'admin_forumauth.php', - 'S_AUTH_SELECT' => get_forum_select('admin', 'f', null, 80), - )); - -} -else -{ - // Output the authorisation details if an id was specified - $forum_name = $forum_rows[0]['forum_name']; - - @reset($simple_auth_ary); - while (list($key, $auth_levels) = each($simple_auth_ary)) - { - $matched = 1; - for ($k = 0; $k < count($auth_levels); $k++) - { - $matched_type = $key; - - if ($forum_rows[0][$forum_auth_fields[$k]] != $auth_levels[$k]) - { - $matched = 0; - } - } - - if ( $matched ) - { - break; - } - } - - // - // If we didn't get a match above then we - // automatically switch into 'advanced' mode - // - if ( !isset($adv) && !$matched ) - { - $adv = 1; - } - - $s_column_span = 0; - - if (empty($adv)) - { - $simple_auth = ''; - - $template->assign_block_vars('forum_auth', array( - 'CELL_TITLE' => $lang['SIMPLE_MODE'], - 'S_AUTH_LEVELS_SELECT' => $simple_auth, - )); - - $s_column_span++; - } - else - { - // - // Output values of individual - // fields - // - for ($j = 0; $j < count($forum_auth_fields); $j++) - { - $custom_auth[$j] = '  '; - - $cell_title = $field_names[$forum_auth_fields[$j]]; - - $template->assign_block_vars('forum_auth', array( - 'CELL_TITLE' => $cell_title, - 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j], - )); - - $s_column_span++; - } - } - - $adv_mode = ( empty($adv) ) ? '1' : '0'; - $switch_mode = "admin_forumauth.php?f=$forum_id&adv=$adv_mode"; - $switch_mode_text = ( empty($adv) ) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE']; - $u_switch_mode = '' . $switch_mode_text . ''; - - $s_hidden_fields = ''; - - $template->assign_vars(array( - 'TPL_EDIT_FORUM_AUTH' => true, - 'FORUM_NAME' => htmlCHR($forum_name), - 'U_SWITCH_MODE' => $u_switch_mode, - 'S_FORUMAUTH_ACTION' => 'admin_forumauth.php', - 'S_COLUMN_SPAN' => $s_column_span, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); +// Check for demo mode +if (IN_DEMO_MODE && $submit) { + bb_die($lang['CANT_EDIT_IN_DEMO_MODE']); } -print_page('admin_forumauth.tpl', 'admin'); \ No newline at end of file +/** + * Start program proper + */ +if ($submit) { + $sql = ''; + + if (!empty($forum_id)) { + if (isset($_POST['simpleauth'])) { + $simple_ary = $simple_auth_ary[(int)$_POST['simpleauth']]; + + for ($i = 0, $iMax = count($simple_ary); $i < $iMax; $i++) { + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; + } + + if (is_array($simple_ary)) { + $sql = 'UPDATE ' . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } + } else { + for ($i = 0, $iMax = count($forum_auth_fields); $i < $iMax; $i++) { + $value = (int)$_POST[$forum_auth_fields[$i]]; + + if ($forum_auth_fields[$i] == 'auth_vote') { + if ($_POST['auth_vote'] == AUTH_ALL) { + $value = AUTH_REG; + } + } + + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $value; + } + + $sql = 'UPDATE ' . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } + + if ($sql != '') { + if (!DB()->sql_query($sql)) { + bb_die('Could not update auth table'); + } + } + + $forum_sql = ''; + $adv = 0; + } + + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); + bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', '')); +} + +/** + * Get required information + */ +$forum_rows = DB()->fetch_rowset('SELECT * FROM ' . BB_FORUMS . " $forum_sql"); + +if (empty($forum_id)) { + // Output the selection table if no forum id was specified + $template->assign_vars([ + 'TPL_AUTH_SELECT_FORUM' => true, + 'S_AUTH_ACTION' => 'admin_forumauth.php', + 'S_AUTH_SELECT' => get_forum_select('admin', 'f', null, 80), + ]); +} else { + // Output the authorisation details if an id was specified + $forum_name = reset($forum_rows)['forum_name']; + + reset($simple_auth_ary); + foreach ($simple_auth_ary as $key => $auth_levels) { + $matched = 1; + for ($k = 0, $kMax = count($auth_levels); $k < $kMax; $k++) { + $matched_type = $key; + + if ($forum_rows[0][$forum_auth_fields[$k]] != $auth_levels[$k]) { + $matched = 0; + } + } + + if ($matched) { + break; + } + } + + // + // If we didn't get a match above then we + // automatically switch into 'advanced' mode + // + if (!isset($adv) && !$matched) { + $adv = 1; + } + + $s_column_span = 0; + + if (empty($adv)) { + $simple_auth = ''; + + $template->assign_block_vars('forum_auth', [ + 'CELL_TITLE' => $lang['SIMPLE_MODE'], + 'S_AUTH_LEVELS_SELECT' => $simple_auth, + ]); + + $s_column_span++; + } else { + // Output values of individual fields + for ($j = 0, $jMax = count($forum_auth_fields); $j < $jMax; $j++) { + $custom_auth[$j] = '  '; + + $cell_title = $field_names[$forum_auth_fields[$j]]; + + $template->assign_block_vars('forum_auth', [ + 'CELL_TITLE' => $cell_title, + 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j], + ]); + + $s_column_span++; + } + } + + $adv_mode = empty($adv) ? '1' : '0'; + $switch_mode = "admin_forumauth.php?" . POST_FORUM_URL . "=$forum_id&adv=$adv_mode"; + $switch_mode_text = empty($adv) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE']; + $u_switch_mode = '' . $switch_mode_text . ''; + + $s_hidden_fields = ''; + + $template->assign_vars([ + 'TPL_EDIT_FORUM_AUTH' => true, + 'FORUM_NAME' => htmlCHR($forum_name), + 'U_VIEWFORUM' => BB_ROOT . FORUM_URL . $forum_id, + 'U_SWITCH_MODE' => $u_switch_mode, + 'S_FORUMAUTH_ACTION' => 'admin_forumauth.php', + 'S_COLUMN_SPAN' => $s_column_span, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + ]); +} + +print_page('admin_forumauth.tpl', 'admin'); diff --git a/admin/admin_forumauth_list.php b/admin/admin_forumauth_list.php index b8c8a7188..37c49d251 100644 --- a/admin/admin_forumauth_list.php +++ b/admin/admin_forumauth_list.php @@ -1,175 +1,160 @@ array(AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL), // Public -/* Reg */ 1 => array(AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG), // Registered -/* Reg [Hid] */ 2 => array(AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG), // Registered [Hidden] -/* Priv */ 3 => array(AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL), // Private -/* Priv [Hid] */ 4 => array(AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL), // Private [Hidden] -/* MOD */ 5 => array(AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators -/* MOD [Hid] */ 6 => array(AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators [Hidden] -); +$simple_auth_ary = [ + 0 => [AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL], // Public + 1 => [AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG], // Registered + 2 => [AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG], // Registered [Hidden] + 3 => [AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL], // Private + 4 => [AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL], // Private [Hidden] + 5 => [AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD], // Moderators + 6 => [AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD], // Moderators [Hidden] +]; -$simple_auth_types = array( - $lang['PUBLIC'], - $lang['REGISTERED'], - $lang['REGISTERED'] .' ['. $lang['HIDDEN'] .']', - $lang['PRIVATE'], - $lang['PRIVATE'] .' ['. $lang['HIDDEN'] .']', - $lang['MODERATORS'], - $lang['MODERATORS'] .' ['. $lang['HIDDEN'] .']', -); +$simple_auth_types = [ + $lang['PUBLIC'], + $lang['REGISTERED'], + $lang['REGISTERED'] . ' [' . $lang['HIDDEN'] . ']', + $lang['PRIVATE'], + $lang['PRIVATE'] . ' [' . $lang['HIDDEN'] . ']', + $lang['MODERATORS'], + $lang['MODERATORS'] . ' [' . $lang['HIDDEN'] . ']', +]; -$forum_auth_fields = array( - 'auth_view', - 'auth_read', - 'auth_reply', - 'auth_edit', - 'auth_delete', - 'auth_vote', - 'auth_pollcreate', - 'auth_attachments', - 'auth_download', - 'auth_post', - 'auth_sticky', - 'auth_announce', -); +$forum_auth_fields = [ + 'auth_view', + 'auth_read', + 'auth_reply', + 'auth_edit', + 'auth_delete', + 'auth_vote', + 'auth_pollcreate', + 'auth_attachments', + 'auth_download', + 'auth_post', + 'auth_sticky', + 'auth_announce', +]; -$field_names = array(); -foreach ($forum_auth_fields as $auth_type) -{ - $field_names[$auth_type] = $lang[strtoupper($auth_type)]; +$field_names = []; +foreach ($forum_auth_fields as $auth_type) { + $field_names[$auth_type] = $lang[strtoupper($auth_type)]; } -$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); -$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); +$forum_auth_levels = ['ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN']; +$forum_auth_const = [AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN]; -if(isset($_GET[POST_FORUM_URL]) || isset($_POST[POST_FORUM_URL])) -{ - $forum_id = (isset($_POST[POST_FORUM_URL])) ? intval($_POST[POST_FORUM_URL]) : intval($_GET[POST_FORUM_URL]); - $forum_sql = "AND forum_id = $forum_id"; -} -else -{ - unset($forum_id); - $forum_sql = ''; +if (isset($_GET[POST_FORUM_URL]) || isset($_POST[POST_FORUM_URL])) { + $forum_id = isset($_POST[POST_FORUM_URL]) ? (int)$_POST[POST_FORUM_URL] : (int)$_GET[POST_FORUM_URL]; + $forum_sql = "AND forum_id = $forum_id"; +} else { + unset($forum_id); + $forum_sql = ''; } -if(isset($_GET[POST_CAT_URL]) || isset($_POST[POST_CAT_URL])) -{ - $cat_id = (isset($_POST[POST_CAT_URL])) ? intval($_POST[POST_CAT_URL]) : intval($_GET[POST_CAT_URL]); - $cat_sql = "AND c.cat_id = $cat_id"; -} -else -{ - unset($cat_id); - $cat_sql = ''; +if (isset($_GET[POST_CAT_URL]) || isset($_POST[POST_CAT_URL])) { + $cat_id = isset($_POST[POST_CAT_URL]) ? (int)$_POST[POST_CAT_URL] : (int)$_GET[POST_CAT_URL]; + $cat_sql = "AND c.cat_id = $cat_id"; +} else { + unset($cat_id); + $cat_sql = ''; } -if( isset($_GET['adv']) ) -{ - $adv = intval($_GET['adv']); -} -else -{ - unset($adv); +if (isset($_GET['adv'])) { + $adv = (int)$_GET['adv']; +} else { + unset($adv); } -// -// Start program proper -// -if( isset($_POST['submit']) ) -{ - $sql = ''; +$submit = isset($_POST['submit']); - if(!empty($forum_id)) - { - if(isset($_POST['simpleauth'])) - { - $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; +// Check for demo mode +if (IN_DEMO_MODE && $submit) { + bb_die($lang['CANT_EDIT_IN_DEMO_MODE']); +} - for($i = 0; $i < count($simple_ary); $i++) - { - $sql .= ( ( $sql != '' ) ? ', ' : '' ) . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; - } +/** + * Start program proper + */ +if ($submit) { + $sql = ''; - if (is_array($simple_ary)) - { - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } - } - else - { - for($i = 0; $i < count($forum_auth_fields); $i++) - { - $value = intval($_POST[$forum_auth_fields[$i]]); + if (!empty($forum_id)) { + if (isset($_POST['simpleauth'])) { + $simple_ary = $simple_auth_ary[(int)$_POST['simpleauth']]; - if ( $forum_auth_fields[$i] == 'auth_vote' ) - { - if ( $_POST['auth_vote'] == AUTH_ALL ) - { - $value = AUTH_REG; - } - } + for ($i = 0, $iMax = count($simple_ary); $i < $iMax; $i++) { + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; + } - $sql .= ( ( $sql != '' ) ? ', ' : '' ) .$forum_auth_fields[$i] . ' = ' . $value; - } + if (is_array($simple_ary)) { + $sql = 'UPDATE ' . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } + } else { + for ($i = 0, $iMax = count($forum_auth_fields); $i < $iMax; $i++) { + $value = (int)$_POST[$forum_auth_fields[$i]]; - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } + if ($forum_auth_fields[$i] == 'auth_vote') { + if ($_POST['auth_vote'] == AUTH_ALL) { + $value = AUTH_REG; + } + } - if ($sql != '') - { - if (!DB()->sql_query($sql)) - { - bb_die('Could not update auth table #1'); - } - } + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $value; + } - $forum_sql = ''; - $adv = 0; - } - elseif (!empty($cat_id)) - { - for ($i = 0; $i < count($forum_auth_fields); $i++) - { - $value = intval($_POST[$forum_auth_fields[$i]]); + $sql = 'UPDATE ' . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } - if ($forum_auth_fields[$i] == 'auth_vote') - { - if ( $_POST['auth_vote'] == AUTH_ALL ) - { - $value = AUTH_REG; - } - } + if ($sql != '') { + if (!DB()->sql_query($sql)) { + bb_die('Could not update auth table #1'); + } + } - $sql .= ( ( $sql != '' ) ? ', ' : '' ) .$forum_auth_fields[$i] . ' = ' . $value; - } + $forum_sql = ''; + $adv = 0; + } elseif (!empty($cat_id)) { + for ($i = 0, $iMax = count($forum_auth_fields); $i < $iMax; $i++) { + $value = (int)$_POST[$forum_auth_fields[$i]]; - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE cat_id = $cat_id"; + if ($forum_auth_fields[$i] == 'auth_vote') { + if ($_POST['auth_vote'] == AUTH_ALL) { + $value = AUTH_REG; + } + } - if ($sql != '') - { - if (!DB()->sql_query($sql)) - { - bb_die('Could not update auth table #2'); - } - } + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $value; + } - $cat_sql = ''; - } + $sql = 'UPDATE ' . BB_FORUMS . " SET $sql WHERE cat_id = $cat_id"; - $datastore->update('cat_forums'); - bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); + if ($sql != '') { + if (!DB()->sql_query($sql)) { + bb_die('Could not update auth table #2'); + } + } + $cat_sql = ''; + } + + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); + bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', '')); } // End of submit // @@ -177,187 +162,166 @@ if( isset($_POST['submit']) ) // no id was specified or just the requsted forum // or category if it was // -$sql = "SELECT f.* - FROM " . BB_FORUMS . " f, " . BB_CATEGORIES . " c +$sql = 'SELECT f.* + FROM ' . BB_FORUMS . ' f, ' . BB_CATEGORIES . " c WHERE c.cat_id = f.cat_id $forum_sql $cat_sql ORDER BY c.cat_order ASC, f.forum_order ASC"; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not obtain forum list'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain forum list'); } $forum_rows = DB()->sql_fetchrowset($result); DB()->sql_freeresult($result); -if( empty($forum_id) && empty($cat_id) ) -{ - // - // Output the summary list if no forum id was - // specified - // - $template->assign_vars(array( - 'TPL_AUTH_FORUM_LIST' => true, - 'S_COLUMN_SPAN' => count($forum_auth_fields)+1, - )); +if (empty($forum_id) && empty($cat_id)) { + // + // Output the summary list if no forum id was + // specified + // + $template->assign_vars(array( + 'TPL_AUTH_FORUM_LIST' => true, + 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1, + )); - for ($i = 0; $iassign_block_vars('forum_auth_titles', array( - 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], - )); - } + for ($i = 0, $iMax = count($forum_auth_fields); $i < $iMax; $i++) { + $template->assign_block_vars('forum_auth_titles', array( + 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], + )); + } - // Obtain the category list - $sql = "SELECT c.cat_id, c.cat_title, c.cat_order - FROM " . BB_CATEGORIES . " c - ORDER BY c.cat_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query categories list #1'); - } + // Obtain the category list + $sql = 'SELECT c.cat_id, c.cat_title, c.cat_order + FROM ' . BB_CATEGORIES . ' c + ORDER BY c.cat_order'; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query categories list #1'); + } - $category_rows = DB()->sql_fetchrowset($result); - $cat_count = count($category_rows); + $category_rows = DB()->sql_fetchrowset($result); + $cat_count = count($category_rows); - for ($i=0; $i<$cat_count; $i++) - { - $cat_id = $category_rows[$i]['cat_id']; + for ($i = 0; $i < $cat_count; $i++) { + $cat_id = $category_rows[$i]['cat_id']; - $template->assign_block_vars('cat_row', array( - 'CAT_NAME' => htmlCHR($category_rows[$i]['cat_title']), - 'CAT_URL' => 'admin_forumauth_list.php'.'?'.POST_CAT_URL.'='.$category_rows[$i]['cat_id']) - ); + $template->assign_block_vars('cat_row', array( + 'CAT_NAME' => htmlCHR($category_rows[$i]['cat_title']), + 'CAT_URL' => 'admin_forumauth_list.php' . '?' . POST_CAT_URL . '=' . $category_rows[$i]['cat_id']) + ); - for ($j=0; $jassign_block_vars('cat_row.forum_row', array( - 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', - 'FORUM_NAME' => ''. htmlCHR($forum_rows[$j]['forum_name']) .'', - 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], - )); + for ($j = 0, $jMax = count($forum_rows); $j < $jMax; $j++) { + if ($cat_id == $forum_rows[$j]['cat_id']) { + $template->assign_block_vars('cat_row.forum_row', array( + 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', + 'FORUM_NAME' => '' . htmlCHR($forum_rows[$j]['forum_name']) . '', + 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], + )); - for ($k=0; $kassign_block_vars('cat_row.forum_row.forum_auth_data', array( - 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], - 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) - ); - } - } - } - } -} -else -{ - // - // output the authorisation details if an category id was - // specified - // + for ($k = 0, $kMax = count($forum_auth_fields); $k < $kMax; $k++) { + $item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]]; + for ($l = 0, $lMax = count($forum_auth_const); $l < $lMax; $l++) { + if ($item_auth_value == $forum_auth_const[$l]) { + $item_auth_level = $forum_auth_levels[$l]; + break; + } + } + $template->assign_block_vars('cat_row.forum_row.forum_auth_data', array( + 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], + 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) + ); + } + } + } + } +} else { + // + // output the authorisation details if an category id was + // specified + // - // - // first display the current details for all forums - // in the category - // - for ($i = 0; $iassign_block_vars('forum_auth_titles', array( - 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], - )); - } + // + // first display the current details for all forums + // in the category + // + for ($i = 0, $iMax = count($forum_auth_fields); $i < $iMax; $i++) { + $template->assign_block_vars('forum_auth_titles', array( + 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], + )); + } - // obtain the category list - $sql = "SELECT c.cat_id, c.cat_title, c.cat_order - FROM " . BB_CATEGORIES . " c + // obtain the category list + $sql = 'SELECT c.cat_id, c.cat_title, c.cat_order + FROM ' . BB_CATEGORIES . " c WHERE c.cat_id = $cat_id ORDER BY c.cat_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query categories list #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query categories list #2'); + } - $category_rows = DB()->sql_fetchrowset($result); + $category_rows = DB()->sql_fetchrowset($result); - $cat_id = $category_rows[0]['cat_id']; - $cat_name = $category_rows[0]['cat_title']; + $cat_id = reset($category_rows)['cat_id']; + $cat_name = reset($category_rows)['cat_title']; - $template->assign_block_vars('cat_row', array( - 'CAT_NAME' => htmlCHR($cat_name), - 'CAT_URL' => 'admin_forumauth_list.php?'. POST_CAT_URL .'='. $cat_id) - ); + $template->assign_block_vars('cat_row', array( + 'CAT_NAME' => htmlCHR($cat_name), + 'CAT_URL' => 'admin_forumauth_list.php?' . POST_CAT_URL . '=' . $cat_id) + ); - for ($j=0; $jassign_block_vars('cat_row.forum_row', array( - 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', - 'FORUM_NAME' => ''. htmlCHR($forum_rows[$j]['forum_name']) .'', - 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], - )); + for ($j = 0, $jMax = count($forum_rows); $j < $jMax; $j++) { + if ($cat_id == $forum_rows[$j]['cat_id']) { + $template->assign_block_vars('cat_row.forum_row', array( + 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', + 'FORUM_NAME' => '' . htmlCHR($forum_rows[$j]['forum_name']) . '', + 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], + )); - for ($k=0; $kassign_block_vars('cat_row.forum_row.forum_auth_data', array( - 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], - 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) - ); - } - } - } + for ($k = 0, $kMax = count($forum_auth_fields); $k < $kMax; $k++) { + $item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]]; + for ($l = 0, $lMax = count($forum_auth_const); $l < $lMax; $l++) { + if ($item_auth_value == $forum_auth_const[$l]) { + $item_auth_level = $forum_auth_levels[$l]; + break; + } + } + $template->assign_block_vars('cat_row.forum_row.forum_auth_data', array( + 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], + 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) + ); + } + } + } - // - // next generate the information to allow the permissions to be changed - // note: we always read from the first forum in the category - // - for($j = 0; $j < count($forum_auth_fields); $j++) - { - $custom_auth[$j] = ''; - for($k = 0; $k < count($forum_auth_levels); $k++) - { - $selected = ( !empty($forum_rows) && $forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k] ) ? ' selected="selected"' : ''; - $custom_auth[$j] .= ''; - } - $custom_auth[$j] .= ''; + for ($k = 0, $kMax = count($forum_auth_levels); $k < $kMax; $k++) { + $selected = (!empty($forum_rows) && $forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k]) ? ' selected' : ''; + $custom_auth[$j] .= ''; + } + $custom_auth[$j] .= ''; - $template->assign_block_vars('forum_auth_data', array( - 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j]) - ); - } + $template->assign_block_vars('forum_auth_data', array( + 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j]) + ); + } - // - // finally pass any remaining items to the template - // - $s_hidden_fields = ''; + // + // finally pass any remaining items to the template + // + $s_hidden_fields = ''; - $template->assign_vars(array( - 'TPL_AUTH_CAT' => true, - 'CAT_NAME' => htmlCHR($cat_name), - 'S_FORUMAUTH_ACTION' => 'admin_forumauth_list.php', - 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); + $template->assign_vars(array( + 'TPL_AUTH_CAT' => true, + 'CAT_NAME' => htmlCHR($cat_name), + 'S_FORUMAUTH_ACTION' => 'admin_forumauth_list.php', + 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); } -print_page('admin_forumauth_list.tpl', 'admin'); \ No newline at end of file +print_page('admin_forumauth_list.tpl', 'admin'); diff --git a/admin/admin_forums.php b/admin/admin_forums.php index eb2c56ae4..8a195bb64 100644 --- a/admin/admin_forums.php +++ b/admin/admin_forums.php @@ -1,302 +1,286 @@ AUTH_ALL, - 'auth_read' => AUTH_ALL, - 'auth_post' => AUTH_REG, - 'auth_reply' => AUTH_REG, - 'auth_edit' => AUTH_REG, - 'auth_delete' => AUTH_REG, - 'auth_sticky' => AUTH_MOD, - 'auth_announce' => AUTH_MOD, - 'auth_vote' => AUTH_REG, - 'auth_pollcreate' => AUTH_REG, - 'auth_attachments' => AUTH_REG, - 'auth_download' => AUTH_REG, -); +$default_forum_auth = [ + 'auth_view' => AUTH_ALL, + 'auth_read' => AUTH_ALL, + 'auth_post' => AUTH_REG, + 'auth_reply' => AUTH_REG, + 'auth_edit' => AUTH_REG, + 'auth_delete' => AUTH_REG, + 'auth_sticky' => AUTH_MOD, + 'auth_announce' => AUTH_MOD, + 'auth_vote' => AUTH_REG, + 'auth_pollcreate' => AUTH_REG, + 'auth_attachments' => AUTH_REG, + 'auth_download' => AUTH_REG, +]; -$mode = (@$_REQUEST['mode']) ? (string) $_REQUEST['mode'] : ''; +$mode = isset($_REQUEST['mode']) ? (string)$_REQUEST['mode'] : ''; $cat_forums = get_cat_forums(); -if ($orphan_sf_sql = get_orphan_sf()) -{ - fix_orphan_sf($orphan_sf_sql, TRUE); +if ($orphan_sf_sql = get_orphan_sf()) { + fix_orphan_sf($orphan_sf_sql, true); } $forum_parent = $cat_id = 0; $forumname = ''; -if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory'])) -{ - $mode = (isset($_REQUEST['addforum'])) ? "addforum" : "addcat"; +if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory'])) { + $mode = isset($_REQUEST['addforum']) ? 'addforum' : 'addcat'; - if ($mode == 'addforum' && isset($_POST['addforum']) && isset($_POST['forumname']) && is_array($_POST['addforum'])) - { - $req_cat_id = array_keys($_POST['addforum']); - $cat_id = $req_cat_id[0]; - $forumname = stripslashes($_POST['forumname'][$cat_id]); - } + if (isset($_POST['addforum'], $_POST['forumname']) && $mode == 'addforum' && is_array($_POST['addforum'])) { + $req_cat_id = array_keys($_POST['addforum']); + $cat_id = reset($req_cat_id); + $forumname = stripslashes($_POST['forumname'][$cat_id]); + } +} + +// Check for demo mode +if (IN_DEMO_MODE && in_array($mode, ['deletecat', 'deleteforum'])) { + bb_die($lang['CANT_EDIT_IN_DEMO_MODE']); } $show_main_page = false; -if ($mode) -{ - switch ($mode) - { - case 'addforum': - case 'editforum': - // - // Show form to create/modify a forum - // - if ($mode == 'editforum') - { - // $newmode determines if we are going to INSERT or UPDATE after posting? +if ($mode) { + switch ($mode) { + case 'addforum': + case 'editforum': + // + // Show form to create/modify a forum + // + if ($mode == 'editforum') { + // $newmode determines if we are going to INSERT or UPDATE after posting? - $l_title = $lang['EDIT_FORUM']; - $newmode = 'modforum'; - $buttonvalue = $lang['UPDATE']; + $l_title = $lang['EDIT_FORUM']; + $newmode = 'modforum'; + $buttonvalue = $lang['UPDATE']; - $forum_id = intval($_GET[POST_FORUM_URL]); + $forum_id = (int)$_GET[POST_FORUM_URL]; - $row = get_info('forum', $forum_id); + $row = get_info('forum', $forum_id); - $cat_id = $row['cat_id']; - $forumname = $row['forum_name']; - $forumdesc = $row['forum_desc']; - $forumstatus = $row['forum_status']; - $forum_display_sort = $row['forum_display_sort']; - $forum_display_order = $row['forum_display_order']; - $forum_parent = $row['forum_parent']; - $show_on_index = $row['show_on_index']; - $prune_days = $row['prune_days']; - $forum_tpl_id = $row['forum_tpl_id']; - $allow_reg_tracker = $row['allow_reg_tracker']; - $allow_porno_topic = $row['allow_porno_topic']; - $self_moderated = $row['self_moderated']; - } - else - { - $l_title = $lang['CREATE_FORUM']; - $newmode = 'createforum'; - $buttonvalue = $lang['CREATE_FORUM']; + $cat_id = $row['cat_id']; + $forumname = $row['forum_name']; + $forumdesc = $row['forum_desc']; + $forumstatus = $row['forum_status']; + $forum_display_sort = $row['forum_display_sort']; + $forum_display_order = $row['forum_display_order']; + $forum_parent = $row['forum_parent']; + $show_on_index = $row['show_on_index']; + $prune_days = $row['prune_days']; + $forum_tpl_id = $row['forum_tpl_id']; + $allow_reg_tracker = $row['allow_reg_tracker']; + $allow_porno_topic = $row['allow_porno_topic']; + $self_moderated = $row['self_moderated']; + } else { + $l_title = $lang['CREATE_FORUM']; + $newmode = 'createforum'; + $buttonvalue = $lang['CREATE_FORUM']; - $forumdesc = ''; - $forumstatus = FORUM_UNLOCKED; - $forum_display_sort = 0; - $forum_display_order = 0; - $forum_id = ''; - $show_on_index = 1; - $prune_days = 0; - $forum_tpl_id = 0; - $allow_reg_tracker = 0; - $allow_porno_topic = 0; - $self_moderated = 0; - } + $forumdesc = ''; + $forumstatus = FORUM_UNLOCKED; + $forum_display_sort = 0; + $forum_display_order = 0; + $forum_id = ''; + $show_on_index = 1; + $prune_days = 0; + $forum_tpl_id = 0; + $allow_reg_tracker = 0; + $allow_porno_topic = 0; + $self_moderated = 0; + } - if (isset($_REQUEST['forum_parent'])) - { - $forum_parent = intval($_REQUEST['forum_parent']); + if (isset($_REQUEST['forum_parent'])) { + $forum_parent = (int)$_REQUEST['forum_parent']; - if ($parent = get_forum_data($forum_parent)) - { - $cat_id = $parent['cat_id']; - } - } - else if (isset($_REQUEST['c'])) - { - $cat_id = (int) $_REQUEST['c']; - } + if ($parent = get_forum_data($forum_parent)) { + $cat_id = $parent['cat_id']; + } + } elseif (isset($_REQUEST[POST_CAT_URL])) { + $cat_id = (int)$_REQUEST[POST_CAT_URL]; + } - $catlist = get_list('category', $cat_id, TRUE); - $forumlocked = $forumunlocked = ''; + $catlist = get_list('category', $cat_id, true); + $forumlocked = $forumunlocked = ''; - $forumstatus == ( FORUM_LOCKED ) ? $forumlocked = 'selected="selected"' : $forumunlocked = 'selected="selected"'; + $forumstatus == FORUM_LOCKED ? $forumlocked = 'selected' : $forumunlocked = 'selected'; - $statuslist = '\n'; - $statuslist .= '\n'; + $statuslist = '\n'; + $statuslist .= '\n'; - $forum_display_sort_list = get_forum_display_sort_option($forum_display_sort, 'list', 'sort'); - $forum_display_order_list = get_forum_display_sort_option($forum_display_order, 'list', 'order'); + $forum_display_sort_list = get_forum_display_sort_option($forum_display_sort, 'list', 'sort'); + $forum_display_order_list = get_forum_display_sort_option($forum_display_order, 'list', 'order'); - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $s_parent = '\n'; - $sel_forum = ($forum_parent && !isset($_REQUEST['forum_parent'])) ? $forum_id : $forum_parent; - $s_parent .= sf_get_list('forum', $forum_id, $sel_forum); + $s_parent = '\n'; + $sel_forum = ($forum_parent && !isset($_REQUEST['forum_parent'])) ? $forum_id : $forum_parent; + $s_parent .= sf_get_list('forum', $forum_id, $sel_forum); - $template->assign_vars(array( - 'TPL_EDIT_FORUM' => true, + $template->assign_vars(array( + 'TPL_EDIT_FORUM' => true, - 'S_FORUM_DISPLAY_SORT_LIST' => $forum_display_sort_list, - 'S_FORUM_DISPLAY_ORDER_LIST' => $forum_display_order_list, - 'S_FORUM_ACTION' => 'admin_forums.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_SUBMIT_VALUE' => $buttonvalue, - 'S_CAT_LIST' => $catlist, - 'S_STATUS_LIST' => $statuslist, + 'S_FORUM_DISPLAY_SORT_LIST' => $forum_display_sort_list, + 'S_FORUM_DISPLAY_ORDER_LIST' => $forum_display_order_list, + 'S_FORUM_ACTION' => 'admin_forums.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_SUBMIT_VALUE' => $buttonvalue, + 'S_CAT_LIST' => $catlist, + 'S_STATUS_LIST' => $statuslist, - 'SHOW_ON_INDEX' => $show_on_index, - 'S_PARENT_FORUM' => $s_parent, - 'CAT_LIST_CLASS' => ($forum_parent) ? 'hidden' : '', - 'SHOW_ON_INDEX_CLASS' => (!$forum_parent) ? 'hidden' : '', - 'TPL_SELECT' => get_select('forum_tpl', $forum_tpl_id, 'html', $lang['TEMPLATE_DISABLE']), - 'ALLOW_REG_TRACKER' => build_select('allow_reg_tracker', array($lang['DISALLOWED'] => 0, $lang['ALLOWED'] => 1), $allow_reg_tracker), - 'ALLOW_PORNO_TOPIC' => build_select('allow_porno_topic', array($lang['NONE'] => 0, $lang['YES'] => 1), $allow_porno_topic), - 'SELF_MODERATED' => build_select('self_moderated', array($lang['NONE'] => 0, $lang['YES'] => 1), $self_moderated), + 'SHOW_ON_INDEX' => $show_on_index, + 'S_PARENT_FORUM' => $s_parent, + 'CAT_LIST_CLASS' => $forum_parent ? 'hidden' : '', + 'SHOW_ON_INDEX_CLASS' => (!$forum_parent) ? 'hidden' : '', + 'TPL_SELECT' => get_select('forum_tpl', $forum_tpl_id, 'html', $lang['TEMPLATE_DISABLE']), + 'ALLOW_REG_TRACKER' => build_select('allow_reg_tracker', array($lang['DISALLOWED'] => 0, $lang['ALLOWED'] => 1), $allow_reg_tracker), + 'ALLOW_PORNO_TOPIC' => build_select('allow_porno_topic', array($lang['NONE'] => 0, $lang['YES'] => 1), $allow_porno_topic), + 'SELF_MODERATED' => build_select('self_moderated', array($lang['NONE'] => 0, $lang['YES'] => 1), $self_moderated), - 'L_FORUM_TITLE' => $l_title, + 'L_FORUM_TITLE' => $l_title, - 'PRUNE_DAYS' => $prune_days, - 'FORUM_NAME' => htmlCHR($forumname), - 'DESCRIPTION' => htmlCHR($forumdesc), - )); - break; + 'PRUNE_DAYS' => $prune_days, + 'FORUM_NAME' => htmlCHR($forumname), + 'DESCRIPTION' => htmlCHR($forumdesc), + )); + break; - case 'createforum': - // - // Create a forum in the DB - // - $cat_id = intval($_POST[POST_CAT_URL]); - $forum_name = (string) $_POST['forumname']; - $forum_desc = (string) $_POST['forumdesc']; - $forum_status = intval($_POST['forumstatus']); + case 'createforum': + // + // Create a forum in the DB + // + $cat_id = (int)$_POST[POST_CAT_URL]; + $forum_name = (string)$_POST['forumname']; + $forum_desc = (string)$_POST['forumdesc']; + $forum_status = (int)$_POST['forumstatus']; - $prune_days = intval($_POST['prune_days']); + $prune_days = (int)$_POST['prune_days']; - $forum_parent = ($_POST['forum_parent'] != -1) ? intval($_POST['forum_parent']) : 0; - $show_on_index = ($forum_parent) ? intval($_POST['show_on_index']) : 1; + $forum_parent = ($_POST['forum_parent'] != -1) ? (int)$_POST['forum_parent'] : 0; + $show_on_index = $forum_parent ? (int)$_POST['show_on_index'] : 1; - $forum_display_sort = intval($_POST['forum_display_sort']); - $forum_display_order = intval($_POST['forum_display_order']); + $forum_display_sort = (int)$_POST['forum_display_sort']; + $forum_display_order = (int)$_POST['forum_display_order']; - $forum_tpl_id = (int) $_POST['forum_tpl_select']; - $allow_reg_tracker = (int) $_POST['allow_reg_tracker']; - $allow_porno_topic = (int) $_POST['allow_porno_topic']; - $self_moderated = (int) $_POST['self_moderated']; + $forum_tpl_id = (int)$_POST['forum_tpl_select']; + $allow_reg_tracker = (int)$_POST['allow_reg_tracker']; + $allow_porno_topic = (int)$_POST['allow_porno_topic']; + $self_moderated = (int)$_POST['self_moderated']; - if (!$forum_name) - { - bb_die('Can not create a forum without a name'); - } + if (!$forum_name) { + bb_die('Can not create a forum without a name'); + } - if ($forum_parent) - { - if (!$parent = get_forum_data($forum_parent)) - { - bb_die('Parent forum with id '. $forum_parent .' not found'); - } + if ($forum_parent) { + if (!$parent = get_forum_data($forum_parent)) { + bb_die('Parent forum with id ' . $forum_parent . ' not found'); + } - $cat_id = $parent['cat_id']; - $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; - $forum_order = $parent['forum_order'] + 5; - } - else - { - $max_order = get_max_forum_order($cat_id); - $forum_order = $max_order + 5; - } + $cat_id = $parent['cat_id']; + $forum_parent = $parent['forum_parent'] ?: $parent['forum_id']; + $forum_order = $parent['forum_order'] + 5; + } else { + $max_order = get_max_forum_order($cat_id); + $forum_order = $max_order + 5; + } - // Default permissions of public forum - $field_sql = $value_sql = ''; + // Default permissions of public forum + $field_sql = $value_sql = ''; - foreach ($default_forum_auth as $field => $value) - { - $field_sql .= ", $field"; - $value_sql .= ", $value"; - } + foreach ($default_forum_auth as $field => $value) { + $field_sql .= ", $field"; + $value_sql .= ", $value"; + } - $forum_name_sql = DB()->escape($forum_name); - $forum_desc_sql = DB()->escape($forum_desc); + $forum_name_sql = DB()->escape($forum_name); + $forum_desc_sql = DB()->escape($forum_desc); - $columns = ' forum_name, cat_id, forum_desc, forum_order, forum_status, prune_days, forum_parent, show_on_index, forum_display_sort, forum_display_order, forum_tpl_id, allow_reg_tracker, allow_porno_topic, self_moderated'. $field_sql; - $values = "'$forum_name_sql', $cat_id, '$forum_desc_sql', $forum_order, $forum_status, $prune_days, $forum_parent, $show_on_index, $forum_display_sort, $forum_display_order, $forum_tpl_id, $allow_reg_tracker, $allow_porno_topic, $self_moderated". $value_sql; + $columns = ' forum_name, cat_id, forum_desc, forum_order, forum_status, prune_days, forum_parent, show_on_index, forum_display_sort, forum_display_order, forum_tpl_id, allow_reg_tracker, allow_porno_topic, self_moderated' . $field_sql; + $values = "'$forum_name_sql', $cat_id, '$forum_desc_sql', $forum_order, $forum_status, $prune_days, $forum_parent, $show_on_index, $forum_display_sort, $forum_display_order, $forum_tpl_id, $allow_reg_tracker, $allow_porno_topic, $self_moderated" . $value_sql; - DB()->query("INSERT INTO ". BB_FORUMS ." ($columns) VALUES ($values)"); + DB()->query('INSERT INTO ' . BB_FORUMS . " ($columns) VALUES ($values)"); - renumber_order('forum', $cat_id); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('forum', $cat_id); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'modforum': - // - // Modify a forum in the DB - // - $cat_id = intval($_POST[POST_CAT_URL]); - $forum_id = intval($_POST[POST_FORUM_URL]); - $forum_name = (string) $_POST['forumname']; - $forum_desc = (string) $_POST['forumdesc']; - $forum_status = intval($_POST['forumstatus']); - $prune_days = intval($_POST['prune_days']); + case 'modforum': + // + // Modify a forum in the DB + // + $cat_id = (int)$_POST[POST_CAT_URL]; + $forum_id = (int)$_POST[POST_FORUM_URL]; + $forum_name = (string)$_POST['forumname']; + $forum_desc = (string)$_POST['forumdesc']; + $forum_status = (int)$_POST['forumstatus']; + $prune_days = (int)$_POST['prune_days']; - $forum_parent = ($_POST['forum_parent'] != -1) ? intval($_POST['forum_parent']) : 0; - $show_on_index = ($forum_parent) ? intval($_POST['show_on_index']) : 1; + $forum_parent = ($_POST['forum_parent'] != -1) ? (int)$_POST['forum_parent'] : 0; + $show_on_index = $forum_parent ? (int)$_POST['show_on_index'] : 1; - $forum_display_order = intval($_POST['forum_display_order']); - $forum_display_sort = intval($_POST['forum_display_sort']); - $forum_tpl_id = (int) $_POST['forum_tpl_select']; - $allow_reg_tracker = (int) $_POST['allow_reg_tracker']; - $allow_porno_topic = (int) $_POST['allow_porno_topic']; - $self_moderated = (int) $_POST['self_moderated']; + $forum_display_order = (int)$_POST['forum_display_order']; + $forum_display_sort = (int)$_POST['forum_display_sort']; + $forum_tpl_id = (int)$_POST['forum_tpl_select']; + $allow_reg_tracker = (int)$_POST['allow_reg_tracker']; + $allow_porno_topic = (int)$_POST['allow_porno_topic']; + $self_moderated = (int)$_POST['self_moderated']; - $forum_data = get_forum_data($forum_id); - $old_cat_id = $forum_data['cat_id']; - $forum_order = $forum_data['forum_order']; + $forum_data = get_forum_data($forum_id); + $old_cat_id = $forum_data['cat_id']; + $forum_order = $forum_data['forum_order']; - if (!$forum_name) - { - bb_die('Can not modify a forum without a name'); - } + if (!$forum_name) { + bb_die('Can not modify a forum without a name'); + } - if ($forum_parent) - { - if (!$parent = get_forum_data($forum_parent)) - { - bb_die('Parent forum with id '. $forum_parent .' not found'); - } + if ($forum_parent) { + if (!$parent = get_forum_data($forum_parent)) { + bb_die('Parent forum with id ' . $forum_parent . ' not found'); + } - $cat_id = $parent['cat_id']; - $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; - $forum_order = $parent['forum_order'] + 5; + $cat_id = $parent['cat_id']; + $forum_parent = $parent['forum_parent'] ?: $parent['forum_id']; + $forum_order = $parent['forum_order'] + 5; - if ($forum_id == $forum_parent) - { - bb_die('Ambiguous forum ID. Please select other parent forum'); - } - } - else if ($cat_id != $old_cat_id) - { - $max_order = get_max_forum_order($cat_id); - $forum_order = $max_order + 5; - } - else if ($forum_data['forum_parent']) - { - $old_parent = $forum_data['forum_parent']; - $forum_order = $cat_forums[$old_cat_id]['f'][$old_parent]['forum_order'] - 5; - } + if ($forum_id == $forum_parent) { + bb_die('Ambiguous forum ID. Please select other parent forum'); + } + } elseif ($cat_id != $old_cat_id) { + $max_order = get_max_forum_order($cat_id); + $forum_order = $max_order + 5; + } elseif ($forum_data['forum_parent']) { + $old_parent = $forum_data['forum_parent']; + $forum_order = $cat_forums[$old_cat_id]['f'][$old_parent]['forum_order'] - 5; + } - $forum_name_sql = DB()->escape($forum_name); - $forum_desc_sql = DB()->escape($forum_desc); + $forum_name_sql = DB()->escape($forum_name); + $forum_desc_sql = DB()->escape($forum_desc); - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(' + UPDATE ' . BB_FORUMS . " SET forum_name = '$forum_name_sql', cat_id = $cat_id, forum_desc = '$forum_desc_sql', @@ -314,905 +298,894 @@ if ($mode) WHERE forum_id = $forum_id "); - if ($cat_id != $old_cat_id) - { - change_sf_cat($forum_id, $cat_id, $forum_order); - renumber_order('forum', $cat_id); - } + if ($cat_id != $old_cat_id) { + change_sf_cat($forum_id, $cat_id, $forum_order); + renumber_order('forum', $cat_id); + } - renumber_order('forum', $old_cat_id); + renumber_order('forum', $old_cat_id); - $cat_forums = get_cat_forums(); - $fix = fix_orphan_sf(); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $cat_forums = get_cat_forums(); + $fix = fix_orphan_sf(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $message = $lang['FORUMS_UPDATED'] . '

'; - $message .= ($fix) ? "$fix

" : ''; - $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + $message = $lang['FORUMS_UPDATED'] . '

'; + $message .= $fix ? "$fix

" : ''; + $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); - break; + break; - case 'addcat': - // - // Create a category in the DB - // - if (!$new_cat_title = trim($_POST['categoryname'])) - { - bb_die('Category name is empty'); - } + case 'addcat': + // + // Create a category in the DB + // + if (!$new_cat_title = trim($_POST['categoryname'])) { + bb_die($lang['CATEGORY_NAME_EMPTY']); + } - check_name_dup('cat', $new_cat_title); + check_name_dup('cat', $new_cat_title); - $order = DB()->fetch_row("SELECT MAX(cat_order) AS max_order FROM ". BB_CATEGORIES); + $order = DB()->fetch_row('SELECT MAX(cat_order) AS max_order FROM ' . BB_CATEGORIES); - $args = DB()->build_array('INSERT', array( - 'cat_title' => (string) $new_cat_title, - 'cat_order' => (int) $order['max_order'] + 10, - )); + $args = DB()->build_array('INSERT', array( + 'cat_title' => (string)$new_cat_title, + 'cat_order' => (int)$order['max_order'] + 10, + )); - DB()->query("INSERT INTO ". BB_CATEGORIES . $args); + DB()->query('INSERT INTO ' . BB_CATEGORIES . $args); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'editcat': - // - // Show form to edit a category - // - $cat_id = (int) $_GET['c']; - $cat_info = get_info('category', $cat_id); + case 'editcat': + // + // Show form to edit a category + // + $cat_id = (int)$_GET[POST_CAT_URL]; + $cat_info = get_info('category', $cat_id); - $hidden_fields = array( - 'mode' => 'modcat', - 'c' => $cat_id, - ); + $hidden_fields = array( + 'mode' => 'modcat', + POST_CAT_URL => $cat_id, + ); - $template->assign_vars(array( - 'TPL_EDIT_CATEGORY' => true, - 'CAT_TITLE' => htmlCHR($cat_info['cat_title']), - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - 'S_SUBMIT_VALUE' => $lang['UPDATE'], - 'S_FORUM_ACTION' => "admin_forums.php", - )); + $template->assign_vars(array( + 'TPL_EDIT_CATEGORY' => true, + 'CAT_TITLE' => htmlCHR($cat_info['cat_title']), + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + 'S_SUBMIT_VALUE' => $lang['UPDATE'], + 'S_FORUM_ACTION' => 'admin_forums.php', + )); - break; + break; - case 'modcat': - // - // Modify a category in the DB - // - if (!$new_cat_title = trim($_POST['cat_title'])) - { - bb_die('Category name is empty'); - } + case 'modcat': + // + // Modify a category in the DB + // + if (!$new_cat_title = trim($_POST['cat_title'])) { + bb_die($lang['CATEGORY_NAME_EMPTY']); + } - $cat_id = (int) $_POST['c']; + $cat_id = (int)$_POST[POST_CAT_URL]; - $row = get_info('category', $cat_id); - $cur_cat_title = $row['cat_title']; + $row = get_info('category', $cat_id); + $cur_cat_title = $row['cat_title']; - if ($cur_cat_title && $cur_cat_title !== $new_cat_title) - { - check_name_dup('cat', $new_cat_title); + if ($cur_cat_title && $cur_cat_title !== $new_cat_title) { + check_name_dup('cat', $new_cat_title); - $new_cat_title_sql = DB()->escape($new_cat_title); + $new_cat_title_sql = DB()->escape($new_cat_title); - DB()->query(" - UPDATE ". BB_CATEGORIES ." SET + DB()->query(' + UPDATE ' . BB_CATEGORIES . " SET cat_title = '$new_cat_title_sql' WHERE cat_id = $cat_id "); - } + } - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'deleteforum': - // - // Show form to delete a forum - // - $forum_id = (int) $_GET['f']; + case 'deleteforum': + // + // Show form to delete a forum + // + $forum_id = (int)$_GET[POST_FORUM_URL]; - $move_to_options = ''; - $move_to_options .= sf_get_list('forum', $forum_id, 0); + $move_to_options = ''; + $move_to_options .= sf_get_list('forum', $forum_id, 0); - $foruminfo = get_info('forum', $forum_id); + $foruminfo = get_info('forum', $forum_id); - $hidden_fields = array( - 'mode' => 'movedelforum', - 'from_id' => $forum_id, - ); + $hidden_fields = array( + 'mode' => 'movedelforum', + 'from_id' => $forum_id, + ); - $template->assign_vars(array( - 'TPL_DELETE_FORUM' => true, + $template->assign_vars(array( + 'TPL_DELETE_FORUM' => true, - 'WHAT_TO_DELETE' => htmlCHR($foruminfo['forum_name']), - 'DELETE_TITLE' => $lang['FORUM_DELETE'], - 'CAT_FORUM_NAME' => $lang['FORUM_NAME'], + 'WHAT_TO_DELETE' => htmlCHR($foruminfo['forum_name']), + 'DELETE_TITLE' => $lang['FORUM_DELETE'], + 'CAT_FORUM_NAME' => $lang['FORUM_NAME'], - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - 'S_FORUM_ACTION' => "admin_forums.php", - 'MOVE_TO_OPTIONS' => $move_to_options, - 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], - )); + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + 'S_FORUM_ACTION' => 'admin_forums.php', + 'MOVE_TO_OPTIONS' => $move_to_options, + 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], + )); - break; + break; - case 'movedelforum': - // - // Move or delete a forum in the DB - // - $from_id = (int) $_POST['from_id']; - $to_id = (int) $_POST['to_id']; + case 'movedelforum': + // + // Move or delete a forum in the DB + // + $from_id = (int)$_POST['from_id']; + $to_id = (int)$_POST['to_id']; - if ($to_id == -1) - { - // Delete everything from forum - topic_delete('prune', $from_id, 0, true); - } - else - { - // Move all posts - $sql = "SELECT * FROM ". BB_FORUMS ." WHERE forum_id IN($from_id, $to_id)"; - $result = DB()->query($sql); + if ($to_id == -1) { + // Delete everything from forum + \TorrentPier\Legacy\Admin\Common::topic_delete('prune', $from_id, 0, true); + $datastore->update('stats'); + } else { + // Move all posts + $sql = 'SELECT * FROM ' . BB_FORUMS . " WHERE forum_id IN($from_id, $to_id)"; + $result = DB()->query($sql); - if (DB()->num_rows($result) != 2) - { - bb_die('Ambiguous forum ID'); - } + if (DB()->num_rows($result) != 2) { + bb_die('Ambiguous forum ID'); + } - DB()->query("UPDATE ". BB_TOPICS ." SET forum_id = $to_id WHERE forum_id = $from_id"); - DB()->query("UPDATE ". BB_BT_TORRENTS ." SET forum_id = $to_id WHERE forum_id = $from_id"); + DB()->query('UPDATE ' . BB_TOPICS . " SET forum_id = $to_id WHERE forum_id = $from_id"); + DB()->query('UPDATE ' . BB_BT_TORRENTS . " SET forum_id = $to_id WHERE forum_id = $from_id"); - $row = DB()->fetch_row("SELECT MIN(post_id) AS start_id, MAX(post_id) AS finish_id FROM ". BB_POSTS); - $start_id = (int) $row['start_id']; - $finish_id = (int) $row['finish_id']; - $per_cycle = 10000; - while (true) - { - set_time_limit(600); - $end_id = $start_id + $per_cycle - 1; - DB()->query(" - UPDATE ". BB_POSTS ." SET forum_id = $to_id WHERE post_id BETWEEN $start_id AND $end_id AND forum_id = $from_id + $row = DB()->fetch_row('SELECT MIN(post_id) AS start_id, MAX(post_id) AS finish_id FROM ' . BB_POSTS); + $start_id = (int)$row['start_id']; + $finish_id = (int)$row['finish_id']; + $per_cycle = 10000; + while (true) { + set_time_limit(600); + $end_id = $start_id + $per_cycle - 1; + DB()->query(' + UPDATE ' . BB_POSTS . " SET forum_id = $to_id WHERE post_id BETWEEN $start_id AND $end_id AND forum_id = $from_id "); - if ($end_id > $finish_id) - { - break; - } - $start_id += $per_cycle; - } + if ($end_id > $finish_id) { + break; + } + $start_id += $per_cycle; + } - sync('forum', $to_id); - } + \TorrentPier\Legacy\Admin\Common::sync('forum', $to_id); + } - DB()->query("DELETE FROM ". BB_FORUMS ." WHERE forum_id = $from_id"); - DB()->query("DELETE FROM ". BB_AUTH_ACCESS ." WHERE forum_id = $from_id"); - DB()->query("DELETE FROM ". BB_AUTH_ACCESS_SNAP ." WHERE forum_id = $from_id"); + DB()->query('DELETE FROM ' . BB_FORUMS . " WHERE forum_id = $from_id"); + DB()->query('DELETE FROM ' . BB_AUTH_ACCESS . " WHERE forum_id = $from_id"); + DB()->query('DELETE FROM ' . BB_AUTH_ACCESS_SNAP . " WHERE forum_id = $from_id"); - $cat_forums = get_cat_forums(); - fix_orphan_sf(); - update_user_level('all'); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $cat_forums = get_cat_forums(); + fix_orphan_sf(); + \TorrentPier\Legacy\Group::update_user_level('all'); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'deletecat': - // Show form to delete a category - $cat_id = (int) $_GET['c']; - $catinfo = get_info('category', $cat_id); - $categories_count = $catinfo['number']; + case 'deletecat': + // Show form to delete a category + $cat_id = (int)$_GET[POST_CAT_URL]; + $catinfo = get_info('category', $cat_id); + $categories_count = $catinfo['number']; - if ($categories_count == 1) - { - $row = DB()->fetch_row("SELECT COUNT(*) AS forums_count FROM ". BB_FORUMS); + if ($categories_count == 1) { + $row = DB()->fetch_row('SELECT COUNT(*) AS forums_count FROM ' . BB_FORUMS); - if ($row['forums_count'] > 0) - { - bb_die($lang['MUST_DELETE_FORUMS']); - } - else - { - $template->assign_var('NOWHERE_TO_MOVE', $lang['NOWHERE_TO_MOVE']); - } - } + if ($row['forums_count'] > 0) { + bb_die($lang['MUST_DELETE_FORUMS']); + } else { + $template->assign_var('NOWHERE_TO_MOVE', $lang['NOWHERE_TO_MOVE']); + } + } - $hidden_fields = array( - 'mode' => 'movedelcat', - 'from_id' => $cat_id, - ); + $hidden_fields = array( + 'mode' => 'movedelcat', + 'from_id' => $cat_id, + ); - $template->assign_vars(array( - 'TPL_DELETE_FORUM' => true, + $template->assign_vars(array( + 'TPL_DELETE_FORUM' => true, - 'WHAT_TO_DELETE' => htmlCHR($catinfo['cat_title']), - 'DELETE_TITLE' => $lang['CATEGORY_DELETE'], - 'CAT_FORUM_NAME' => $lang['CATEGORY'], + 'WHAT_TO_DELETE' => htmlCHR($catinfo['cat_title']), + 'DELETE_TITLE' => $lang['CATEGORY_DELETE'], + 'CAT_FORUM_NAME' => $lang['CATEGORY'], - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - 'S_FORUM_ACTION' => "admin_forums.php", - 'MOVE_TO_OPTIONS' => get_list('category', $cat_id, 0), - 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], - )); + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + 'S_FORUM_ACTION' => 'admin_forums.php', + 'MOVE_TO_OPTIONS' => get_list('category', $cat_id, 0), + 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], + )); - break; + break; - case 'movedelcat': - // Move or delete a category in the DB - $from_id = (int) $_POST['from_id']; - $to_id = (int) $_POST['to_id']; + case 'movedelcat': + // Move or delete a category in the DB + $from_id = (int)$_POST['from_id']; + $to_id = (int)$_POST['to_id'] ?? -1; - if ($from_id == $to_id || !cat_exists($from_id) || !cat_exists($to_id)) - { - bb_die('Bad input'); - } + if ($to_id === -1) { + bb_die($lang['NOWHERE_TO_MOVE']); + } - $order_shear = get_max_forum_order($to_id) + 10; + if ($from_id == $to_id || !cat_exists($from_id) || !cat_exists($to_id)) { + bb_die('Bad input'); + } - DB()->query(" - UPDATE ". BB_FORUMS ." SET + $order_shear = get_max_forum_order($to_id) + 10; + + DB()->query(' + UPDATE ' . BB_FORUMS . " SET cat_id = $to_id, forum_order = forum_order + $order_shear WHERE cat_id = $from_id "); - DB()->query("DELETE FROM ". BB_CATEGORIES ." WHERE cat_id = $from_id"); + DB()->query('DELETE FROM ' . BB_CATEGORIES . " WHERE cat_id = $from_id"); - renumber_order('forum', $to_id); - $cat_forums = get_cat_forums(); - $fix = fix_orphan_sf(); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('forum', $to_id); + $cat_forums = get_cat_forums(); + $fix = fix_orphan_sf(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $message = $lang['FORUMS_UPDATED'] . '

'; - $message .= ($fix) ? "$fix

" : ''; - $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + $message = $lang['FORUMS_UPDATED'] . '

'; + $message .= $fix ? "$fix

" : ''; + $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); - break; + break; - case 'forum_order': - // Change order of forums - $move = intval($_GET['move']); - $forum_id = intval($_GET[POST_FORUM_URL]); + case 'forum_order': + // Change order of forums + $move = (int)$_GET['move']; + $forum_id = (int)$_GET[POST_FORUM_URL]; - $forum_info = get_info('forum', $forum_id); - renumber_order('forum', $forum_info['cat_id']); + $forum_info = get_info('forum', $forum_id); + renumber_order('forum', $forum_info['cat_id']); - $cat_id = $forum_info['cat_id']; + $cat_id = $forum_info['cat_id']; - $move_down_forum_id = FALSE; - $forums = $cat_forums[$cat_id]['f_ord']; - $forum_order = $forum_info['forum_order']; - $prev_forum = (isset($forums[$forum_order - 10])) ? $forums[$forum_order - 10] : FALSE; - $next_forum = (isset($forums[$forum_order + 10])) ? $forums[$forum_order + 10] : FALSE; + $move_down_forum_id = false; + $forums = $cat_forums[$cat_id]['f_ord']; + $forum_order = $forum_info['forum_order']; + $prev_forum = $forums[$forum_order - 10] ?? false; + $next_forum = $forums[$forum_order + 10] ?? false; - // move selected forum ($forum_id) UP - if ($move < 0 && $prev_forum) - { - if ($forum_info['forum_parent'] && $prev_forum['forum_parent'] != $forum_info['forum_parent']) - { - $show_main_page = true; - break; - } - else if ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order)) - { - $move_up_forum_id = $forum_id; - $move_down_ord_val = (get_sf_count($forum_id) + 1) * 10; - $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; - $move_down_forum_order = $cat_forums[$cat_id]['f'][$move_down_forum_id]['forum_order']; - } - } - // move selected forum ($forum_id) DOWN - else if ($move > 0 && $next_forum) - { - if ($forum_info['forum_parent'] && $next_forum['forum_parent'] != $forum_info['forum_parent']) - { - $show_main_page = true; - break; - } - else if ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order)) - { - $move_down_forum_id = $forum_id; - $move_down_forum_order = $forum_order; - $move_down_ord_val = (get_sf_count($move_up_forum_id) + 1) * 10; - $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; - } - } - else - { - $show_main_page = true; - break; - } + // move selected forum ($forum_id) UP + if ($move < 0 && $prev_forum) { + if ($forum_info['forum_parent'] && $prev_forum['forum_parent'] != $forum_info['forum_parent']) { + $show_main_page = true; + break; + } - if ($forum_info['forum_parent']) - { - DB()->query(" - UPDATE ". BB_FORUMS ." SET + if ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order)) { + $move_up_forum_id = $forum_id; + $move_down_ord_val = (get_sf_count($forum_id) + 1) * 10; + $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; + $move_down_forum_order = $cat_forums[$cat_id]['f'][$move_down_forum_id]['forum_order']; + } + } // move selected forum ($forum_id) DOWN + elseif ($move > 0 && $next_forum) { + if ($forum_info['forum_parent'] && $next_forum['forum_parent'] != $forum_info['forum_parent']) { + $show_main_page = true; + break; + } + + if ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order)) { + $move_down_forum_id = $forum_id; + $move_down_forum_order = $forum_order; + $move_down_ord_val = (get_sf_count($move_up_forum_id) + 1) * 10; + $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; + } + } else { + $show_main_page = true; + break; + } + + if ($forum_info['forum_parent']) { + DB()->query(' + UPDATE ' . BB_FORUMS . " SET forum_order = forum_order + $move WHERE forum_id = $forum_id "); - } - else if ($move_down_forum_id) - { - DB()->query(" - UPDATE ". BB_FORUMS ." SET + } elseif ($move_down_forum_id) { + DB()->query(' + UPDATE ' . BB_FORUMS . " SET forum_order = forum_order + $move_down_ord_val WHERE cat_id = $cat_id AND forum_order >= $move_down_forum_order "); - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(' + UPDATE ' . BB_FORUMS . " SET forum_order = forum_order - $move_up_ord_val WHERE forum_id = $move_up_forum_id OR forum_parent = $move_up_forum_id "); - } + } - renumber_order('forum', $forum_info['cat_id']); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('forum', $forum_info['cat_id']); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $show_main_page = true; - break; + $show_main_page = true; + break; - case 'cat_order': - $move = (int) $_GET['move']; - $cat_id = (int) $_GET['c']; + case 'cat_order': + $move = (int)$_GET['move']; + $cat_id = (int)$_GET[POST_CAT_URL]; - DB()->query(" - UPDATE ". BB_CATEGORIES ." SET + DB()->query(' + UPDATE ' . BB_CATEGORIES . " SET cat_order = cat_order + $move WHERE cat_id = $cat_id "); - renumber_order('category'); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('category'); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $show_main_page = true; - break; + $show_main_page = true; + break; - case 'forum_sync': - sync('forum', intval($_GET['f'])); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + case 'forum_sync': + \TorrentPier\Legacy\Admin\Common::sync('forum', (int)$_GET[POST_FORUM_URL]); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $show_main_page = true; - break; + $show_main_page = true; + break; - default: - bb_die($lang['NO_MODE']); - - break; - } + default: + bb_die($lang['NO_MODE']); + break; + } } -if (!$mode || $show_main_page) -{ - $template->assign_vars(array( - 'TPL_FORUMS_LIST' => true, +if (!$mode || $show_main_page) { + $template->assign_vars(array( + 'TPL_FORUMS_LIST' => true, - 'S_FORUM_ACTION' => 'admin_forums.php', - 'L_FORUM_TITLE' => $lang['FORUM_ADMIN_MAIN'], - )); + 'S_FORUM_ACTION' => 'admin_forums.php', + 'L_FORUM_TITLE' => $lang['FORUM_ADMIN_MAIN'], + )); - $sql = "SELECT cat_id, cat_title, cat_order FROM " . BB_CATEGORIES . " ORDER BY cat_order"; - if (!$q_categories = DB()->sql_query($sql)) - { - bb_die('Could not query categories list'); - } + $sql = 'SELECT cat_id, cat_title, cat_order FROM ' . BB_CATEGORIES . ' ORDER BY cat_order'; + if (!$q_categories = DB()->sql_query($sql)) { + bb_die('Could not query categories list'); + } - if ($total_categories = DB()->num_rows($q_categories)) - { - $category_rows = DB()->sql_fetchrowset($q_categories); + if ($total_categories = DB()->num_rows($q_categories)) { + $category_rows = DB()->sql_fetchrowset($q_categories); - $where_cat_sql = $req_cat_id = ''; + $where_cat_sql = $req_cat_id = ''; - if ($c =& $_REQUEST['c']) - { - if ($c !== 'all') - { - $req_cat_id = (int) $c; - $where_cat_sql = "WHERE cat_id = $req_cat_id"; - } - else - { - $req_cat_id = 'all'; - } - } - else - { - $where_cat_sql = "WHERE cat_id = '-1'"; - } + if ($c =& $_REQUEST[POST_CAT_URL]) { + if ($c !== 'all') { + $req_cat_id = (int)$c; + $where_cat_sql = "WHERE cat_id = $req_cat_id"; + } else { + $req_cat_id = 'all'; + } + } else { + $where_cat_sql = "WHERE cat_id = '-1'"; + } - $sql = "SELECT * FROM ". BB_FORUMS ." $where_cat_sql ORDER BY cat_id, forum_order"; - if (!$q_forums = DB()->sql_query($sql)) - { - bb_die('Could not query forums information'); - } + $sql = 'SELECT * FROM ' . BB_FORUMS . " $where_cat_sql ORDER BY cat_id, forum_order"; + if (!$q_forums = DB()->sql_query($sql)) { + bb_die('Could not query forums information'); + } - if ($total_forums = DB()->num_rows($q_forums)) - { - $forum_rows = DB()->sql_fetchrowset($q_forums); - } + if ($total_forums = DB()->num_rows($q_forums)) { + $forum_rows = DB()->sql_fetchrowset($q_forums); + } - // Okay, let's build the index - $gen_cat = array(); + // Okay, let's build the index + $gen_cat = []; - $bgr_class_1 = 'prow1'; - $bgr_class_2 = 'prow2'; - $bgr_class_over = 'prow3'; + $bgr_class_1 = 'prow1'; + $bgr_class_2 = 'prow2'; + $bgr_class_over = 'prow3'; - $template->assign_vars(array( - 'U_ALL_FORUMS' => 'admin_forums.php?c=all', - 'FORUMS_COUNT' => $total_forums, - )); + $template->assign_vars(array( + 'U_ALL_FORUMS' => 'admin_forums.php?' . POST_CAT_URL . '=all', + 'FORUMS_COUNT' => $total_forums, + )); - for ($i = 0; $i < $total_categories; $i++) - { - $cat_id = $category_rows[$i]['cat_id']; + for ($i = 0; $i < $total_categories; $i++) { + $cat_id = $category_rows[$i]['cat_id']; - $template->assign_block_vars("c", array( - 'S_ADD_FORUM_SUBMIT' => "addforum[$cat_id]", - 'S_ADD_FORUM_NAME' => "forumname[$cat_id]", + $template->assign_block_vars('c', array( + 'S_ADD_FORUM_SUBMIT' => "addforum[$cat_id]", + 'S_ADD_FORUM_NAME' => "forumname[$cat_id]", - 'CAT_ID' => $cat_id, - 'CAT_DESC' => htmlCHR($category_rows[$i]['cat_title']), + 'CAT_ID' => $cat_id, + 'CAT_DESC' => htmlCHR($category_rows[$i]['cat_title']), - 'U_CAT_EDIT' => "admin_forums.php?mode=editcat&c=$cat_id", - 'U_CAT_DELETE' => "admin_forums.php?mode=deletecat&c=$cat_id", - 'U_CAT_MOVE_UP' => "admin_forums.php?mode=cat_order&move=-15&c=$cat_id", - 'U_CAT_MOVE_DOWN' => "admin_forums.php?mode=cat_order&move=15&c=$cat_id", - 'U_VIEWCAT' => "admin_forums.php?c=$cat_id", - 'U_CREATE_FORUM' => "admin_forums.php?mode=addforum&c=$cat_id", - )); + 'U_CAT_EDIT' => "admin_forums.php?mode=editcat&" . POST_CAT_URL . "=$cat_id", + 'U_CAT_DELETE' => "admin_forums.php?mode=deletecat&" . POST_CAT_URL . "=$cat_id", + 'U_CAT_MOVE_UP' => "admin_forums.php?mode=cat_order&move=-15&" . POST_CAT_URL . "=$cat_id", + 'U_CAT_MOVE_DOWN' => "admin_forums.php?mode=cat_order&move=15&" . POST_CAT_URL . "=$cat_id", + 'U_VIEWCAT' => "admin_forums.php?" . POST_CAT_URL . "=$cat_id", + 'U_CREATE_FORUM' => "admin_forums.php?mode=addforum&" . POST_CAT_URL . "=$cat_id", + )); - for ($j = 0; $j < $total_forums; $j++) - { - $forum_id = $forum_rows[$j]['forum_id']; + for ($j = 0; $j < $total_forums; $j++) { + $forum_id = $forum_rows[$j]['forum_id']; - $bgr_class = (!($j % 2)) ? $bgr_class_2 : $bgr_class_1; - $row_bgr = " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\""; + $bgr_class = (!($j % 2)) ? $bgr_class_2 : $bgr_class_1; + $row_bgr = " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\""; - if ($forum_rows[$j]['cat_id'] == $cat_id) - { + if ($forum_rows[$j]['cat_id'] == $cat_id) { + $template->assign_block_vars('c.f', array( + 'FORUM_NAME' => htmlCHR($forum_rows[$j]['forum_name']), + 'FORUM_DESC' => htmlCHR($forum_rows[$j]['forum_desc']), + 'NUM_TOPICS' => $forum_rows[$j]['forum_topics'], + 'NUM_POSTS' => $forum_rows[$j]['forum_posts'], + 'PRUNE_DAYS' => !empty($forum_rows[$j]['prune_days']) ? delta_time((TIMENOW - 86400 * $forum_rows[$j]['prune_days']), TIMENOW, 'days') : $lang['DISABLED'], - $template->assign_block_vars("c.f", array( - 'FORUM_NAME' => htmlCHR($forum_rows[$j]['forum_name']), - 'FORUM_DESC' => htmlCHR($forum_rows[$j]['forum_desc']), - 'NUM_TOPICS' => $forum_rows[$j]['forum_topics'], - 'NUM_POSTS' => $forum_rows[$j]['forum_posts'], - 'PRUNE_DAYS' => ($forum_rows[$j]['prune_days']) ? $forum_rows[$j]['prune_days'] : '-', + 'ORDER' => $forum_rows[$j]['forum_order'], + 'FORUM_ID' => $forum_rows[$j]['forum_id'], + 'ROW_BGR' => $row_bgr, - 'ORDER' => $forum_rows[$j]['forum_order'], - 'FORUM_ID' => $forum_rows[$j]['forum_id'], - 'ROW_BGR' => $row_bgr, - - 'SHOW_ON_INDEX' => (bool) $forum_rows[$j]['show_on_index'], - 'FORUM_PARENT' => $forum_rows[$j]['forum_parent'], - 'SF_PAD' => ($forum_rows[$j]['forum_parent']) ? ' style="padding-left: 20px;" ' : '', - 'FORUM_NAME_CLASS' => ($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen', - 'ADD_SUB_HREF' => "admin_forums.php?mode=addforum&forum_parent={$forum_rows[$j]['forum_id']}", - 'U_VIEWFORUM' => BB_ROOT ."viewforum.php?f=$forum_id", - 'U_FORUM_EDIT' => "admin_forums.php?mode=editforum&f=$forum_id", - 'U_FORUM_PERM' => "admin_forumauth.php?f=$forum_id", - 'U_FORUM_DELETE' => "admin_forums.php?mode=deleteforum&f=$forum_id", - 'U_FORUM_MOVE_UP' => "admin_forums.php?mode=forum_order&move=-15&f=$forum_id&c=$req_cat_id", - 'U_FORUM_MOVE_DOWN' => "admin_forums.php?mode=forum_order&move=15&f=$forum_id&c=$req_cat_id", - 'U_FORUM_RESYNC' => "admin_forums.php?mode=forum_sync&f=$forum_id", - )); - - }// if ... forumid == catid - } // for ... forums - } // for ... categories - }// if ... total_categories + 'SHOW_ON_INDEX' => (bool)$forum_rows[$j]['show_on_index'], + 'FORUM_PARENT' => $forum_rows[$j]['forum_parent'], + 'SF_PAD' => $forum_rows[$j]['forum_parent'] ? ' style="padding-left: 20px;" ' : '', + 'FORUM_NAME_CLASS' => $forum_rows[$j]['forum_parent'] ? 'genmed' : 'gen', + 'ADD_SUB_HREF' => !$forum_rows[$j]['forum_parent'] ? "admin_forums.php?mode=addforum&forum_parent={$forum_rows[$j]['forum_id']}" : '', + 'U_VIEWFORUM' => BB_ROOT . FORUM_URL . $forum_id, + 'U_FORUM_EDIT' => "admin_forums.php?mode=editforum&" . POST_FORUM_URL . "=$forum_id", + 'U_FORUM_PERM' => "admin_forumauth.php?" . POST_FORUM_URL . "=$forum_id", + 'U_FORUM_DELETE' => "admin_forums.php?mode=deleteforum&" . POST_FORUM_URL . "=$forum_id", + 'U_FORUM_MOVE_UP' => "admin_forums.php?mode=forum_order&move=-15&" . POST_FORUM_URL . "=$forum_id&" . POST_CAT_URL . "=$req_cat_id", + 'U_FORUM_MOVE_DOWN' => "admin_forums.php?mode=forum_order&move=15&" . POST_FORUM_URL . "=$forum_id&" . POST_CAT_URL . "=$req_cat_id", + 'U_FORUM_RESYNC' => "admin_forums.php?mode=forum_sync&" . POST_FORUM_URL . "=$forum_id", + )); + } + } + } + } } print_page('admin_forums.tpl', 'admin'); -// Functions -function get_info ($mode, $id) +/** + * @param $mode + * @param $id + * @return mixed + */ +function get_info($mode, $id) { - switch($mode) - { - case 'category': - $table = BB_CATEGORIES; - $idfield = 'cat_id'; - break; + $table = null; + $idfield = null; + switch ($mode) { + case 'category': + $table = BB_CATEGORIES; + $idfield = 'cat_id'; + break; - case 'forum': - $table = BB_FORUMS; - $idfield = 'forum_id'; - break; + case 'forum': + $table = BB_FORUMS; + $idfield = 'forum_id'; + break; - default: - bb_die('Wrong mode for generating select list #1'); - break; - } - $sql = "SELECT count(*) as total FROM $table"; - if( !$result = DB()->sql_query($sql) ) - { - bb_die('Could not get forum / category information #1'); - } - $count = DB()->sql_fetchrow($result); - $count = $count['total']; + default: + bb_die('Wrong mode for generating select list #1'); + break; + } + $sql = "SELECT count(*) as total FROM $table"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get forum / category information #1'); + } + $count = DB()->sql_fetchrow($result); + $count = $count['total']; - $sql = "SELECT * FROM $table WHERE $idfield = $id"; + $sql = "SELECT * FROM $table WHERE $idfield = $id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get forum / category information #2'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get forum / category information #2'); + } - if (DB()->num_rows($result) != 1) - { - bb_die('Forum / category does not exist or multiple forums / categories with ID '. $id); - } + if (DB()->num_rows($result) != 1) { + bb_die('Forum / category does not exist or multiple forums / categories with ID ' . $id); + } - $return = DB()->sql_fetchrow($result); - $return['number'] = $count; - return $return; + $return = DB()->sql_fetchrow($result); + $return['number'] = $count; + return $return; } -function get_list ($mode, $id, $select) +/** + * @param $mode + * @param $id + * @param $select + * @return string + */ +function get_list($mode, $id, $select) { - switch($mode) - { - case 'category': - $table = BB_CATEGORIES; - $idfield = 'cat_id'; - $namefield = 'cat_title'; - $order = 'cat_order'; - break; + $table = null; + $idfield = null; + $order = null; + $namefield = null; + switch ($mode) { + case 'category': + $table = BB_CATEGORIES; + $idfield = 'cat_id'; + $namefield = 'cat_title'; + $order = 'cat_order'; + break; - case 'forum': - $table = BB_FORUMS; - $idfield = 'forum_id'; - $namefield = 'forum_name'; - $order = 'cat_id, forum_order'; - break; + case 'forum': + $table = BB_FORUMS; + $idfield = 'forum_id'; + $namefield = 'forum_name'; + $order = 'cat_id, forum_order'; + break; - default: - bb_die('Wrong mode for generating select list #2'); - break; - } + default: + bb_die('Wrong mode for generating select list #2'); + break; + } - $sql = "SELECT * FROM $table"; - if( $select == 0 ) - { - $sql .= " WHERE $idfield <> $id"; - } - $sql .= " ORDER BY $order"; + $sql = "SELECT * FROM $table"; + if ($select == 0) { + $sql .= " WHERE $idfield <> $id"; + } + $sql .= " ORDER BY $order"; - if( !$result = DB()->sql_query($sql) ) - { - bb_die('Could not get list of categories / forums #1'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #1'); + } - $catlist = ''; + $catlist = ''; - while( $row = DB()->sql_fetchrow($result) ) - { - $s = ''; - if ($row[$idfield] == $id) - { - $s = ' selected="selected"'; - } - $catlist .= '\n'; - } + while ($row = DB()->sql_fetchrow($result)) { + $s = ''; + if ($row[$idfield] == $id) { + $s = ' selected'; + } + $catlist .= '\n'; + } - return($catlist); + return $catlist; } -function renumber_order ($mode, $cat = 0) +/** + * @param $mode + * @param int $cat + */ +function renumber_order($mode, $cat = 0) { - switch($mode) - { - case 'category': - $table = BB_CATEGORIES; - $idfield = 'cat_id'; - $orderfield = 'cat_order'; - $cat = 0; - break; + $table = null; + $catfield = null; + $orderfield = null; + $idfield = null; + switch ($mode) { + case 'category': + $table = BB_CATEGORIES; + $idfield = 'cat_id'; + $orderfield = 'cat_order'; + $cat = 0; + break; - case 'forum': - $table = BB_FORUMS; - $idfield = 'forum_id'; - $orderfield = 'forum_order'; - $catfield = 'cat_id'; - break; + case 'forum': + $table = BB_FORUMS; + $idfield = 'forum_id'; + $orderfield = 'forum_order'; + $catfield = 'cat_id'; + break; - default: - bb_die('Wrong mode for generating select list #3'); - break; - } + default: + bb_die('Wrong mode for generating select list #3'); + break; + } - $sql = "SELECT * FROM $table"; - if( $cat != 0) - { - $sql .= " WHERE $catfield = $cat"; - } - $sql .= " ORDER BY $orderfield ASC"; + $sql = "SELECT * FROM $table"; + if ($cat != 0) { + $sql .= " WHERE $catfield = $cat"; + } + $sql .= " ORDER BY $orderfield ASC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get list of categories / forums #2'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #2'); + } - $i = 10; + $i = 10; - while ($row = DB()->sql_fetchrow($result)) - { - $sql = "UPDATE $table SET $orderfield = $i WHERE $idfield = " . $row[$idfield]; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update order fields'); - } - $i += 10; - } - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get list of categories / forums #3'); - } + while ($row = DB()->sql_fetchrow($result)) { + $sql = "UPDATE $table SET $orderfield = $i WHERE $idfield = " . $row[$idfield]; + if (!DB()->sql_query($sql)) { + bb_die('Could not update order fields'); + } + $i += 10; + } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #3'); + } } -function get_cat_forums ($cat_id = FALSE) +/** + * @param bool $cat_id + * @return array + */ +function get_cat_forums($cat_id = false) { - $forums = array(); - $where_sql = ''; + $forums = []; + $where_sql = ''; - if ($cat_id = intval($cat_id)) - { - $where_sql = "AND f.cat_id = $cat_id"; - } + if ($cat_id = (int)$cat_id) { + $where_sql = "AND f.cat_id = $cat_id"; + } - $sql = 'SELECT c.cat_title, f.* - FROM '. BB_FORUMS .' f, '. BB_CATEGORIES ." c + $sql = 'SELECT c.cat_title, f.* + FROM ' . BB_FORUMS . ' f, ' . BB_CATEGORIES . " c WHERE f.cat_id = c.cat_id $where_sql ORDER BY c.cat_order, f.cat_id, f.forum_order"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get list of categories / forums #4'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #4'); + } - if ($rowset = DB()->sql_fetchrowset($result)) - { - foreach ($rowset as $rid => $row) - { - $forums[$row['cat_id']]['cat_title'] = $row['cat_title']; - $forums[$row['cat_id']]['f'][$row['forum_id']] = $row; - $forums[$row['cat_id']]['f_ord'][$row['forum_order']] = $row; - } - } + if ($rowset = DB()->sql_fetchrowset($result)) { + foreach ($rowset as $rid => $row) { + $forums[$row['cat_id']]['cat_title'] = $row['cat_title']; + $forums[$row['cat_id']]['f'][$row['forum_id']] = $row; + $forums[$row['cat_id']]['f_ord'][$row['forum_order']] = $row; + } + } - return $forums; + return $forums; } -function get_sf_count ($forum_id) +/** + * @param $forum_id + * @return int + */ +function get_sf_count($forum_id) { - global $cat_forums; + global $cat_forums; - $sf_count = 0; + $sf_count = 0; - foreach ($cat_forums as $cid => $c) - { - foreach ($c['f'] as $fid => $f) - { - if ($f['forum_parent'] == $forum_id) - { - $sf_count++; - } - } - } + foreach ($cat_forums as $cid => $c) { + foreach ($c['f'] as $fid => $f) { + if ($f['forum_parent'] == $forum_id) { + $sf_count++; + } + } + } - return $sf_count; + return $sf_count; } -function get_prev_root_forum_id ($forums, $curr_forum_order) +/** + * @param $forums + * @param $curr_forum_order + * @return bool + */ +function get_prev_root_forum_id($forums, $curr_forum_order) { - $i = $curr_forum_order - 10; + $i = $curr_forum_order - 10; - while ($i > 0) - { - if (isset($forums[$i]) && !$forums[$i]['forum_parent']) - { - return $forums[$i]['forum_id']; - } - $i = $i - 10; - } + while ($i > 0) { + if (isset($forums[$i]) && !$forums[$i]['forum_parent']) { + return $forums[$i]['forum_id']; + } + $i -= 10; + } - return FALSE; + return false; } -function get_next_root_forum_id ($forums, $curr_forum_order) +/** + * @param $forums + * @param $curr_forum_order + * @return bool + */ +function get_next_root_forum_id($forums, $curr_forum_order) { - $i = $curr_forum_order + 10; - $limit = (count($forums) * 10) + 10; + $i = $curr_forum_order + 10; + $limit = (count($forums) * 10) + 10; - while ($i < $limit) - { - if (isset($forums[$i]) && !$forums[$i]['forum_parent']) - { - return $forums[$i]['forum_id']; - } - $i = $i + 10; - } + while ($i < $limit) { + if (isset($forums[$i]) && !$forums[$i]['forum_parent']) { + return $forums[$i]['forum_id']; + } + $i += 10; + } - return FALSE; + return false; } -function get_orphan_sf () +/** + * @return string + */ +function get_orphan_sf() { - global $cat_forums; + global $cat_forums; - $last_root = 0; - $bad_sf_ary = array(); + $last_root = 0; + $bad_sf_ary = []; - foreach ($cat_forums as $cid => $c) - { - foreach ($c['f'] as $fid => $f) - { - if ($f['forum_parent']) - { - if ($f['forum_parent'] != $last_root) - { - $bad_sf_ary[] = $f['forum_id']; - } - } - else - { - $last_root = $f['forum_id']; - } - } - } + foreach ($cat_forums as $cid => $c) { + foreach ($c['f'] as $fid => $f) { + if ($f['forum_parent']) { + if ($f['forum_parent'] != $last_root) { + $bad_sf_ary[] = $f['forum_id']; + } + } else { + $last_root = $f['forum_id']; + } + } + } - return implode(',', $bad_sf_ary); + return implode(',', $bad_sf_ary); } -function fix_orphan_sf ($orphan_sf_sql = '', $show_mess = FALSE) +/** + * @param string $orphan_sf_sql + * @param bool $show_mess + * @return string + */ +function fix_orphan_sf($orphan_sf_sql = '', $show_mess = false) { - global $lang; + global $lang; - $done_mess = ''; + $done_mess = ''; - if (!$orphan_sf_sql) - { - $orphan_sf_sql = get_orphan_sf(); - } + if (!$orphan_sf_sql) { + $orphan_sf_sql = get_orphan_sf(); + } - if ($orphan_sf_sql) - { - $sql = "UPDATE ". BB_FORUMS ." SET forum_parent = 0, show_on_index = 1 WHERE forum_id IN($orphan_sf_sql)"; + if ($orphan_sf_sql) { + $sql = 'UPDATE ' . BB_FORUMS . " SET forum_parent = 0, show_on_index = 1 WHERE forum_id IN($orphan_sf_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not change subforums data'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not change subforums data'); + } - if ($affectedrows = DB()->affected_rows()) - { - $done_mess = 'Subforums data corrected. '. $affectedrows .' orphan subforum(s) moved to root level.'; - } + if ($affectedrows = DB()->affected_rows()) { + $done_mess = 'Subforums data corrected. ' . $affectedrows . ' orphan subforum(s) moved to root level.'; + } - if ($show_mess) - { - $message = $done_mess .'

'; - $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - } + if ($show_mess) { + $message = $done_mess . '

'; + $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); + } + } - return $done_mess; + return $done_mess; } -function sf_get_list ($mode, $exclude = 0, $select = 0) +/** + * @param $mode + * @param int $exclude + * @param int $select + * @return string + */ +function sf_get_list($mode, $exclude = 0, $select = 0) { - global $cat_forums, $forum_parent; + global $cat_forums, $forum_parent; - $opt = ''; + $opt = ''; - if ($mode == 'forum') - { - foreach ($cat_forums as $cid => $c) - { - $opt .= ''; + if ($mode == 'forum') { + foreach ($cat_forums as $cid => $c) { + $opt .= ''; - foreach ($c['f'] as $fid => $f) - { - $selected = ($fid == $select) ? HTML_SELECTED : ''; - $disabled = ($fid == $exclude && !$forum_parent) ? HTML_DISABLED : ''; - $style = ($disabled) ? ' style="color: gray" ' : (($fid == $exclude) ? ' style="color: darkred" ' : ''); - $opt .= '\n"; - } + foreach ($c['f'] as $fid => $f) { + $selected = ($fid == $select) ? HTML_SELECTED : ''; + $disabled = ($fid == $exclude && !$forum_parent) ? HTML_DISABLED : ''; + $style = $disabled ? ' style="color: gray" ' : (($fid == $exclude) ? ' style="color: darkred" ' : ''); + $opt .= '\n"; + } - $opt .= ''; - } - } + $opt .= ''; + } + } - return $opt; + return $opt; } -function get_forum_data ($forum_id) +/** + * @param $forum_id + * @return bool + */ +function get_forum_data($forum_id) { - global $cat_forums; + global $cat_forums; - foreach ($cat_forums as $cid => $c) - { - foreach ($c['f'] as $fid => $f) - { - if ($fid == $forum_id) - { - return $f; - } - } - } + foreach ($cat_forums as $cid => $c) { + foreach ($c['f'] as $fid => $f) { + if ($fid == $forum_id) { + return $f; + } + } + } - return FALSE; + return false; } -function get_max_forum_order ($cat_id) +/** + * @param $cat_id + * @return int + */ +function get_max_forum_order($cat_id) { - $row = DB()->fetch_row(" + $row = DB()->fetch_row(' SELECT MAX(forum_order) AS max_forum_order - FROM ". BB_FORUMS ." + FROM ' . BB_FORUMS . " WHERE cat_id = $cat_id "); - return intval($row['max_forum_order']); + return (int)$row['max_forum_order']; } -function check_name_dup ($mode, $name, $die_on_error = true) +/** + * @param $mode + * @param $name + * @param bool $die_on_error + * @return mixed + */ +function check_name_dup($mode, $name, $die_on_error = true) { - $name_sql = DB()->escape($name); + $name_sql = DB()->escape($name); - if ($mode == 'cat') - { - $what_checked = 'category'; - $sql = "SELECT cat_id FROM ". BB_CATEGORIES ." WHERE cat_title = '$name_sql'"; - } - else - { - $what_checked = 'forum'; - $sql = "SELECT forum_id FROM ". BB_FORUMS ." WHERE forum_name = '$name_sql'"; - } + if ($mode == 'cat') { + $what_checked = 'category'; + $sql = 'SELECT cat_id FROM ' . BB_CATEGORIES . " WHERE cat_title = '$name_sql'"; + } else { + $what_checked = 'forum'; + $sql = 'SELECT forum_id FROM ' . BB_FORUMS . " WHERE forum_name = '$name_sql'"; + } - $name_is_dup = DB()->fetch_row($sql); + $name_is_dup = DB()->fetch_row($sql); - if ($name_is_dup && $die_on_error) - { - bb_die('This '. $what_checked .' name taken, please choose something else'); - } + if ($name_is_dup && $die_on_error) { + bb_die('This ' . $what_checked . ' name taken, please choose something else'); + } - return $name_is_dup; + return $name_is_dup; } /** * Change subforums cat_id if parent's cat_id was changed + * + * @param $parent_id + * @param $new_cat_id + * @param $order_shear */ -function change_sf_cat ($parent_id, $new_cat_id, $order_shear) +function change_sf_cat($parent_id, $new_cat_id, $order_shear) { - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(' + UPDATE ' . BB_FORUMS . " SET cat_id = $new_cat_id, forum_order = forum_order + $order_shear WHERE forum_parent = $parent_id "); -} \ No newline at end of file +} diff --git a/admin/admin_groups.php b/admin/admin_groups.php index ade36db3a..69361639d 100644 --- a/admin/admin_groups.php +++ b/admin/admin_groups.php @@ -1,188 +1,168 @@ $row['group_name'], - 'group_description' => $row['group_description'], - 'group_moderator' => $row['group_moderator'], - 'group_mod_name' => $row['moderator_name'], - 'group_type' => $row['group_type'], - 'release_group' => $row['release_group'], - ); - $mode = 'editgroup'; - $template->assign_block_vars('group_edit', array()); - } - else if (!empty($_POST['new'])) - { - $group_info = array( - 'group_name' => '', - 'group_description' => '', - 'group_moderator' => '', - 'group_mod_name' => '', - 'group_type' => GROUP_OPEN, - 'release_group' => 0, - ); - $mode = 'newgroup'; - } +if (!empty($_POST['edit']) || !empty($_POST['new'])) { + if (!empty($_POST['edit'])) { + if (!$row = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + $group_info = [ + 'group_name' => $row['group_name'], + 'group_description' => $row['group_description'], + 'group_moderator' => $row['group_moderator'], + 'group_mod_name' => $row['moderator_name'], + 'group_type' => $row['group_type'], + 'release_group' => $row['release_group'] + ]; + $mode = 'editgroup'; + $template->assign_block_vars('group_edit', []); + } elseif (!empty($_POST['new'])) { + $group_info = [ + 'group_name' => '', + 'group_description' => '', + 'group_moderator' => '', + 'group_mod_name' => '', + 'group_type' => GROUP_OPEN, + 'release_group' => 0 + ]; + $mode = 'newgroup'; + } - // Ok, now we know everything about them, let's show the page. - $s_hidden_fields = ' - - + // Ok, now we know everything about them, let's show the page. + $s_hidden_fields = ' + + '; - $template->assign_vars(array( - 'TPL_EDIT_GROUP' => true, + $template->assign_vars([ + 'TPL_EDIT_GROUP' => true, - 'GROUP_NAME' => stripslashes(htmlspecialchars($group_info['group_name'])), - 'GROUP_DESCRIPTION' => stripslashes(htmlspecialchars($group_info['group_description'])), - 'GROUP_MODERATOR' => replace_quote($group_info['group_mod_name']), - 'T_GROUP_EDIT_DELETE' => ($mode == 'newgroup') ? $lang['CREATE_NEW_GROUP'] : $lang['EDIT_GROUP'], - 'U_SEARCH_USER' => BB_ROOT ."search.php?mode=searchuser", - 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, - 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, - 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, - 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? HTML_CHECKED : '', - 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? HTML_CHECKED : '', - 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN ) ? HTML_CHECKED : '', - 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, - 'S_GROUP_ACTION' => "admin_groups.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); -} -else if (!empty($_POST['group_update'])) -{ - if (!empty($_POST['group_delete'])) - { - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } - // Delete Group - delete_group($group_id); + 'GROUP_NAME' => stripslashes(htmlspecialchars($group_info['group_name'])), + 'GROUP_DESCRIPTION' => stripslashes(htmlspecialchars($group_info['group_description'])), + 'GROUP_MODERATOR' => replace_quote($group_info['group_mod_name']), + 'T_GROUP_EDIT_DELETE' => ($mode == 'newgroup') ? $lang['CREATE_NEW_GROUP'] : $lang['EDIT_GROUP'], + 'U_SEARCH_USER' => BB_ROOT . 'search.php?mode=searchuser', + 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, + 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, + 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, + 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? HTML_CHECKED : '', + 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? HTML_CHECKED : '', + 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? HTML_CHECKED : '', + 'RELEASE_GROUP' => (bool)$group_info['release_group'], + 'S_GROUP_ACTION' => 'admin_groups.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields + ]); +} elseif (!empty($_POST['group_update'])) { + if (!empty($_POST['group_delete'])) { + if (!$group_info = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + // Delete Group + \TorrentPier\Legacy\Group::delete_group($group_id); - $message = $lang['DELETED_GROUP'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['DELETED_GROUP'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else - { - $group_type = isset($_POST['group_type']) ? intval($_POST['group_type']) : GROUP_OPEN; - $release_group = isset($_POST['release_group']) ? intval($_POST['release_group']) : 0; - $group_name = isset($_POST['group_name']) ? trim($_POST['group_name']) : ''; - $group_desc = isset($_POST['group_description']) ? trim($_POST['group_description']) : ''; - $group_moderator = isset($_POST['username']) ? $_POST['username'] : ''; + bb_die($message); + } else { + $group_type = isset($_POST['group_type']) ? (int)$_POST['group_type'] : GROUP_OPEN; + $release_group = isset($_POST['release_group']) ? (int)$_POST['release_group'] : 0; + $group_name = isset($_POST['group_name']) ? trim($_POST['group_name']) : ''; + $group_desc = isset($_POST['group_description']) ? trim($_POST['group_description']) : ''; + $group_moderator = $_POST['username'] ?? ''; - if ($group_name === '') - { - bb_die($lang['NO_GROUP_NAME']); - } - else if ($group_moderator === '') - { - bb_die($lang['NO_GROUP_MODERATOR']); - } - $this_userdata = get_userdata($group_moderator, true); + if ($group_name === '') { + bb_die($lang['NO_GROUP_NAME']); + } elseif ($group_moderator === '') { + bb_die($lang['NO_GROUP_MODERATOR']); + } + $this_userdata = get_userdata($group_moderator, true); - if (!$group_moderator = $this_userdata['user_id']) - { - bb_die($lang['NO_GROUP_MODERATOR']); - } + if (!$group_moderator = $this_userdata['user_id']) { + bb_die($lang['NO_GROUP_MODERATOR']); + } - $sql_ary = array( - 'group_type' => (int) $group_type, - 'release_group' => (int) $release_group, - 'group_name' => (string) $group_name, - 'group_description' => (string) $group_desc, - 'group_moderator' => (int) $group_moderator, - 'group_single_user' => 0, - ); + $sql_ary = [ + 'group_type' => (int)$group_type, + 'release_group' => (int)$release_group, + 'group_name' => (string)$group_name, + 'group_description' => (string)$group_desc, + 'group_moderator' => (int)$group_moderator, + 'group_single_user' => 0, + ]; - if ($mode == "editgroup") - { - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } + if ($mode == 'editgroup') { + if (!$group_info = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } - if ($group_info['group_moderator'] != $group_moderator) - { - // Create user_group for new group's moderator - add_user_into_group($group_id, $group_moderator); - $sql_ary['mod_time'] = TIMENOW; + if ($group_info['group_moderator'] != $group_moderator) { + // Create user_group for new group's moderator + \TorrentPier\Legacy\Group::add_user_into_group($group_id, $group_moderator); + $sql_ary['mod_time'] = TIMENOW; - // Delete old moderator's user_group - if (isset($_POST['delete_old_moderator'])) - { - delete_user_group($group_id, $group_info['group_moderator']); - } - } + // Delete old moderator's user_group + if (isset($_POST['delete_old_moderator'])) { + \TorrentPier\Legacy\Group::delete_user_group($group_id, $group_info['group_moderator']); + } + } - $sql_args = DB()->build_array('UPDATE', $sql_ary); + $sql_args = DB()->build_array('UPDATE', $sql_ary); - // Update group's data - DB()->query("UPDATE ". BB_GROUPS ." SET $sql_args WHERE group_id = $group_id"); + // Update group's data + DB()->query('UPDATE ' . BB_GROUPS . " SET $sql_args WHERE group_id = $group_id"); - $message = $lang['UPDATED_GROUP'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['UPDATED_GROUP'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else if ($mode == 'newgroup') - { - $sql_ary['group_time'] = $sql_ary['mod_time'] = TIMENOW; - $sql_args = DB()->build_array('INSERT', $sql_ary); + bb_die($message); + } elseif ($mode == 'newgroup') { + $sql_ary['group_time'] = $sql_ary['mod_time'] = TIMENOW; + $sql_args = DB()->build_array('INSERT', $sql_ary); - // Create new group - DB()->query("INSERT INTO ". BB_GROUPS ." $sql_args"); - $new_group_id = DB()->sql_nextid(); + // Create new group + DB()->query('INSERT INTO ' . BB_GROUPS . " $sql_args"); + $new_group_id = DB()->sql_nextid(); - // Create user_group for group's moderator - add_user_into_group($new_group_id, $group_moderator); + // Create user_group for group's moderator + \TorrentPier\Legacy\Group::add_user_into_group($new_group_id, $group_moderator); - $message = $lang['ADDED_NEW_GROUP'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['ADDED_NEW_GROUP'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else - { - bb_die($lang['NO_GROUP_ACTION']); - } - } -} -else -{ - $template->assign_vars(array( - 'TPL_GROUP_SELECT' => true, + bb_die($message); + } else { + bb_die($lang['NO_GROUP_ACTION']); + } + } +} else { + $template->assign_vars([ + 'TPL_GROUP_SELECT' => true, - 'S_GROUP_ACTION' => "admin_groups.php", - 'S_GROUP_SELECT' => stripslashes(get_select('groups')), - )); + 'S_GROUP_ACTION' => 'admin_groups.php', + 'S_GROUP_SELECT' => stripslashes(get_select('groups')), + ]); } -print_page('admin_groups.tpl', 'admin'); \ No newline at end of file +print_page('admin_groups.tpl', 'admin'); diff --git a/admin/admin_log.php b/admin/admin_log.php index 2e53c4099..89f0e8b0b 100644 --- a/admin/admin_log.php +++ b/admin/admin_log.php @@ -1,60 +1,67 @@ enqueue(array( - 'moderators', -)); +require __DIR__ . '/pagestart.php'; + +$datastore->enqueue([ + 'moderators', + 'cat_forums', +]); $log_action->init(); -$per_page = 50; -$row_class_1 = 'row1'; -$row_class_2 = 'row2'; -$def_days = 3; -$def_datetime = TIMENOW; -$max_forum_name_len = 40; +$per_page = 50; +$row_class_1 = 'row1'; +$row_class_2 = 'row2'; +$def_days = 3; +$def_datetime = TIMENOW; +$max_forum_name_len = 40; $title_match_max_len = 60; $poster_name_max_len = 25; -$select_max_height = 16; -$dt_format = 'Y-m-d'; // used in one-day filter +$select_max_height = 16; +$dt_format = 'Y-m-d'; // used in one-day filter $url = basename(__FILE__); // Key names -$type_key = 'type'; -$forum_key = 'f'; -$topic_key = 't'; -$user_key = 'u'; -$datetime_key = 'dt'; // value should be strtotime() time ("2006-06-25" etc.) -$daysback_key = 'db'; -$sort_key = 'sort'; +$type_key = 'type'; +$forum_key = POST_FORUM_URL; +$topic_key = POST_TOPIC_URL; +$user_key = POST_USERS_URL; +$datetime_key = 'dt'; // value should be strtotime() time ("2006-06-25" etc.) +$daysback_key = 'db'; +$sort_key = 'sort'; $title_match_key = 'tm'; // Key values -$all_types = 0; // =| -$all_users = 0; // |> only "0" is a valid value +$all_types = 0; // =| +$all_users = 0; // |> only "0" is a valid value $all_forums = 0; // =| -$sort_asc = 'ASC'; -$sort_desc = 'DESC'; +$sort_asc = 'ASC'; +$sort_desc = 'DESC'; // Defaults -$def_types = $all_types; -$def_users = $all_users; +$def_types = $all_types; +$def_users = $all_users; $def_forums = $all_forums; -$def_sort = $sort_desc; +$def_sort = $sort_desc; // Moderators data -if (!$mod = $datastore->get('moderators')) -{ - $datastore->update('moderators'); - $mod = $datastore->get('moderators'); +if (!$mod = $datastore->get('moderators')) { + $datastore->update('moderators'); + $mod = $datastore->get('moderators'); } array_deep($mod['moderators'], 'html_entity_decode'); array_deep($mod['admins'], 'html_entity_decode'); @@ -64,350 +71,292 @@ $users = array($lang['ACTS_LOG_ALL_ACTIONS'] => $all_users) + array_flip($mod['m unset($mod); // Forums data -if (!$forums = $datastore->get('cat_forums')) -{ - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); +if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); } $f_data = $forums['f']; unset($forums); // Start -$start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; +$start = isset($_REQUEST['start']) ? abs((int)$_REQUEST['start']) : 0; // Type $type_selected = array($def_types); $type_csv = ''; -if ($var =& $_REQUEST[$type_key]) -{ - $type_selected = get_id_ary($var); +if ($var =& $_REQUEST[$type_key]) { + $type_selected = get_id_ary($var); - if (in_array($all_types, $type_selected)) - { - $type_selected = array($all_types); - } - $type_csv = join(',', $type_selected); - $url = ($type_csv != $def_types) ? url_arg($url, $type_key, $type_csv) : $url; + if (in_array($all_types, $type_selected)) { + $type_selected = array($all_types); + } + $type_csv = implode(',', $type_selected); + $url = ($type_csv != $def_types) ? url_arg($url, $type_key, $type_csv) : $url; } // User $user_selected = array($def_users); $user_csv = ''; -if ($var =& $_REQUEST[$user_key]) -{ - $user_selected = get_id_ary($var); +if ($var =& $_REQUEST[$user_key]) { + $user_selected = get_id_ary($var); - if (in_array($all_users, $user_selected)) - { - $user_selected = array($all_users); - } - $user_csv = join(',', $user_selected); - $url = ($user_csv != $def_users) ? url_arg($url, $user_key, $user_csv) : $url; + if (in_array($all_users, $user_selected)) { + $user_selected = array($all_users); + } + $user_csv = implode(',', $user_selected); + $url = ($user_csv != $def_users) ? url_arg($url, $user_key, $user_csv) : $url; } // Forum $forum_selected = array($def_forums); $forum_csv = ''; -if ($var =& $_REQUEST[$forum_key]) -{ - $forum_selected = get_id_ary($var); +if ($var =& $_REQUEST[$forum_key]) { + $forum_selected = get_id_ary($var); - if (in_array($all_forums, $forum_selected)) - { - $forum_selected = array($all_forums); - } - $forum_csv = join(',', $forum_selected); - $url = ($forum_csv != $def_forums) ? url_arg($url, $forum_key, $forum_csv) : $url; + if (in_array($all_forums, $forum_selected)) { + $forum_selected = array($all_forums); + } + $forum_csv = implode(',', $forum_selected); + $url = ($forum_csv != $def_forums) ? url_arg($url, $forum_key, $forum_csv) : $url; } // Topic $topic_selected = null; $topic_csv = ''; -if ($var =& $_REQUEST[$topic_key]) -{ - $topic_selected = get_id_ary($var); - $topic_csv = join(',', $topic_selected); - $url = ($topic_csv) ? url_arg($url, $topic_key, $topic_csv) : $url; +if ($var =& $_REQUEST[$topic_key]) { + $topic_selected = get_id_ary($var); + $topic_csv = implode(',', $topic_selected); + $url = $topic_csv ? url_arg($url, $topic_key, $topic_csv) : $url; } -// Order -$order_val = 'log_time'; - // Sort $sort_val = $def_sort; -if ($var =& $_REQUEST[$sort_key] AND $var != $def_sort) -{ - $sort_val = ($var == $sort_asc) ? $sort_asc : $sort_desc; - $url = url_arg($url, $sort_key, $sort_val); +if ($var =& $_REQUEST[$sort_key] && $var != $def_sort) { + $sort_val = ($var == $sort_asc) ? $sort_asc : $sort_desc; + $url = url_arg($url, $sort_key, $sort_val); } // Time $datetime_val = $def_datetime; $daysback_val = $def_days; -if ($var =& $_REQUEST[$daysback_key] AND $var != $def_days) -{ - $daysback_val = max(intval($var), 1); - $url = url_arg($url, $daysback_key, $daysback_val); +if ($var =& $_REQUEST[$daysback_key] && $var != $def_days) { + $daysback_val = max((int)$var, 1); + $url = url_arg($url, $daysback_key, $daysback_val); } -if ($var =& $_REQUEST[$datetime_key] AND $var != $def_datetime) -{ - $tz = TIMENOW + (3600 * $bb_cfg['board_timezone']); - if (($tmp_timestamp = strtotime($var, $tz)) > 0) - { - $datetime_val = $tmp_timestamp; - $url = url_arg($url, $datetime_key, date($dt_format, $datetime_val)); - } +if ($var =& $_REQUEST[$datetime_key] && $var != $def_datetime) { + $tz = TIMENOW + (3600 * config()->get('board_timezone')); + if (($tmp_timestamp = strtotime($var, $tz)) > 0) { + $datetime_val = $tmp_timestamp; + $url = url_arg($url, $datetime_key, date($dt_format, $datetime_val)); + } } $time_end_val = 86400 + mktime(0, 0, 0, date('m', $datetime_val), date('d', $datetime_val), date('Y', $datetime_val)); -$time_start_val = $time_end_val - 86400*$daysback_val; +$time_start_val = $time_end_val - 86400 * $daysback_val; // First log time -$row = DB()->fetch_row("SELECT MIN(log_time) AS first_log_time FROM ". BB_LOG); -$first_log_time = (int) $row['first_log_time']; +$row = DB()->fetch_row('SELECT MIN(log_time) AS first_log_time FROM ' . BB_LOG); +$first_log_time = (int)$row['first_log_time']; // Title match $title_match_val = $title_match_sql = ''; -if ($var =& $_REQUEST[$title_match_key]) -{ - if ($tmp_title_match = substr(urldecode(trim($var)), 0, $title_match_max_len)) - { - $title_match_sql = DB()->escape($tmp_title_match); - $url = url_arg($url, $title_match_key, urlencode($tmp_title_match)); - } +if ($var =& $_REQUEST[$title_match_key]) { + if ($tmp_title_match = substr(urldecode(trim($var)), 0, $title_match_max_len)) { + $title_match_sql = DB()->escape($tmp_title_match); + $url = url_arg($url, $title_match_key, urlencode($tmp_title_match)); + } } -// // SQL -// -$select = "SELECT *"; +$where = " WHERE l.log_time BETWEEN '$time_start_val' AND '$time_end_val'"; +$where .= $type_csv ? " AND l.log_type_id IN($type_csv)" : ''; +$where .= $user_csv ? " AND l.log_user_id IN($user_csv)" : ''; +$where .= $forum_csv ? " AND l.log_forum_id IN($forum_csv)" : ''; +$where .= $topic_csv ? " AND l.log_topic_id IN($topic_csv)" : ''; +$where .= $title_match_sql ? " AND MATCH (l.log_topic_title) AGAINST ('$title_match_sql' IN BOOLEAN MODE)" : ''; -$from = "FROM ". BB_LOG; - -$where = " - WHERE log_time BETWEEN $time_start_val AND $time_end_val -"; -$where .= ($type_csv) ? " - AND log_type_id IN($type_csv) -" : ''; -$where .= ($user_csv) ? " - AND log_user_id IN($user_csv) -" : ''; -$where .= ($forum_csv) ? " - AND log_forum_id IN($forum_csv) -" : ''; -$where .= ($topic_csv) ? " - AND log_topic_id IN($topic_csv) -" : ''; -$where .= ($title_match_sql) ? " - AND MATCH (log_topic_title) AGAINST ('$title_match_sql' IN BOOLEAN MODE) -" : ''; - -$order = "ORDER BY $order_val"; - -$sort = $sort_val; - -$limit = "LIMIT $start, ". ($per_page + 1); - -$sql = " - $select - $from +$sql = 'SELECT l.*, u.* + FROM ' . BB_LOG . ' l + LEFT JOIN ' . BB_USERS . " u ON(u.user_id = l.log_user_id) $where - $order - $sort - $limit -"; + ORDER BY l.log_time + $sort_val + LIMIT $start, " . ($per_page + 1); $log_rowset = DB()->fetch_rowset($sql); $log_count = count($log_rowset); -if ($log_count == $per_page + 1) -{ - $items_count = $start + ($per_page * 2); - $pages = '?'; - array_pop($log_rowset); -} -else -{ - $items_count = $start + $log_count; - $pages = (!$log_count) ? 1 : ceil($items_count / $per_page); +if ($log_count == $per_page + 1) { + $items_count = $start + ($per_page * 2); + $pages = '?'; + array_pop($log_rowset); +} else { + $items_count = $start + $log_count; + $pages = (!$log_count) ? 1 : ceil($items_count / $per_page); } generate_pagination($url, $items_count, $per_page, $start); -$filter = array(); +$filter = []; -if ($log_rowset) -{ - $log_type = $log_action->log_type; - $log_type_flip = array_flip($log_type); +if ($log_rowset) { + $log_type = $log_action->log_type; + $log_type_flip = array_flip($log_type); - foreach ($log_rowset as $row_num => $row) - { - $msg = ''; - $forum_name = $forum_name_new = ''; - $topic_title = $topic_title_new = ''; + foreach ($log_rowset as $row_num => $row) { + $msg = ''; + $forum_name = $forum_name_new = ''; + $topic_title = $topic_title_new = ''; - $topic_deleted = ($row['log_type_id'] == $log_type['mod_topic_delete']); + $topic_deleted = ($row['log_type_id'] == $log_type['mod_topic_delete']); - switch ($row['log_type_id']) - { - case $log_type['mod_topic_delete']: - case $log_type['mod_topic_move']: - case $log_type['mod_topic_lock']: - case $log_type['mod_topic_unlock']: - case $log_type['mod_post_delete']: - case $log_type['mod_topic_split']: - // topic_title - if (!empty($row['log_topic_title'])) - { - $topic_title = $row['log_topic_title']; - } - // topic_title_new - if (!empty($row['log_topic_title_new'])) - { - $topic_title_new = $row['log_topic_title_new']; - } - // forum_name - if ($fid =& $row['log_forum_id']) - { - $forum_name = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:'. $row['log_forum_id']; - } - // forum_name_new - if ($fid =& $row['log_forum_id_new']) - { - $forum_name_new = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:'. $row['log_forum_id']; - } + switch ($row['log_type_id']) { + case $log_type['mod_topic_delete']: + case $log_type['mod_topic_move']: + case $log_type['mod_topic_lock']: + case $log_type['mod_topic_unlock']: + case $log_type['mod_topic_set_downloaded']: + case $log_type['mod_topic_unset_downloaded']: + case $log_type['mod_topic_change_tor_status']: + case $log_type['mod_topic_change_tor_type']: + case $log_type['mod_topic_tor_unregister']: + case $log_type['mod_topic_renamed']: + case $log_type['mod_post_delete']: + case $log_type['mod_post_pin']: + case $log_type['mod_post_unpin']: + case $log_type['mod_topic_split']: + // topic_title + if (!empty($row['log_topic_title'])) { + $topic_title = $row['log_topic_title']; + } + // topic_title_new + if (!empty($row['log_topic_title_new'])) { + $topic_title_new = $row['log_topic_title_new']; + } + // forum_name + if ($fid =& $row['log_forum_id']) { + $forum_name = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:' . $row['log_forum_id']; + } + // forum_name_new + if ($fid =& $row['log_forum_id_new']) { + $forum_name_new = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:' . $row['log_forum_id']; + } - break; - } + break; + } - $msg .= " $row[log_msg]"; + $msg .= " {$row['log_msg']}"; - $row_class = !($row_num & 1) ? $row_class_1 : $row_class_2; + $row_class = !($row_num & 1) ? $row_class_1 : $row_class_2; - $datetime_href_s = url_arg($url, $datetime_key, date($dt_format, $row['log_time'])); - $datetime_href_s = url_arg($datetime_href_s, $daysback_key, 1); + $datetime_href_s = url_arg($url, $datetime_key, date($dt_format, $row['log_time'])); + $datetime_href_s = url_arg($datetime_href_s, $daysback_key, 1); - $template->assign_block_vars('log', array( - 'ACTION_DESC' => $lang['LOG_ACTION']['LOG_TYPE'][$log_type_flip[$row['log_type_id']]], - 'ACTION_HREF_S' => url_arg($url, $type_key, $row['log_type_id']), + $template->assign_block_vars('log', array( + 'ACTION_DESC' => $lang['LOG_ACTION']['LOG_TYPE'][$log_type_flip[$row['log_type_id']]], + 'ACTION_HREF_S' => url_arg($url, $type_key, $row['log_type_id']), - 'USER_ID' => $row['log_user_id'], - 'USERNAME' => $row['log_username'], - 'USER_HREF_S' => url_arg($url, $user_key, $row['log_user_id']), - 'USER_IP' => decode_ip($row['log_user_ip']), + 'USER_ID' => $row['log_user_id'], + 'USERNAME' => profile_url($row, true), + 'USER_HREF_S' => url_arg($url, $user_key, $row['log_user_id']), + 'USER_IP' => \TorrentPier\Helpers\IPHelper::isValid($row['log_user_ip']) ? \TorrentPier\Helpers\IPHelper::long2ip_extended($row['log_user_ip']) : '127.0.0.1', - 'FORUM_ID' => $row['log_forum_id'], - 'FORUM_HREF' => BB_ROOT . FORUM_URL . $row['log_forum_id'], - 'FORUM_HREF_S' => url_arg($url, $forum_key, $row['log_forum_id']), - 'FORUM_NAME' => htmlCHR($forum_name), + 'FORUM_ID' => $row['log_forum_id'], + 'FORUM_HREF' => BB_ROOT . FORUM_URL . $row['log_forum_id'], + 'FORUM_HREF_S' => url_arg($url, $forum_key, $row['log_forum_id']), + 'FORUM_NAME' => htmlCHR($forum_name), - 'FORUM_ID_NEW' => $row['log_forum_id_new'], - 'FORUM_HREF_NEW' => BB_ROOT . FORUM_URL . $row['log_forum_id_new'], - 'FORUM_HREF_NEW_S' => url_arg($url, $forum_key, $row['log_forum_id_new']), - 'FORUM_NAME_NEW' => htmlCHR($forum_name_new), + 'FORUM_ID_NEW' => $row['log_forum_id_new'], + 'FORUM_HREF_NEW' => BB_ROOT . FORUM_URL . $row['log_forum_id_new'], + 'FORUM_HREF_NEW_S' => url_arg($url, $forum_key, $row['log_forum_id_new']), + 'FORUM_NAME_NEW' => htmlCHR($forum_name_new), - 'TOPIC_ID' => $row['log_topic_id'], - 'TOPIC_HREF' => (!$topic_deleted) ? BB_ROOT . TOPIC_URL . $row['log_topic_id'] : '', - 'TOPIC_HREF_S' => url_arg($url, $topic_key, $row['log_topic_id']), - 'TOPIC_TITLE' => $topic_title, + 'TOPIC_ID' => $row['log_topic_id'], + 'TOPIC_HREF' => (!$topic_deleted) ? BB_ROOT . TOPIC_URL . $row['log_topic_id'] : '', + 'TOPIC_HREF_S' => url_arg($url, $topic_key, $row['log_topic_id']), + 'TOPIC_TITLE' => $topic_title, - 'TOPIC_ID_NEW' => $row['log_topic_id_new'], - 'TOPIC_HREF_NEW' => BB_ROOT . TOPIC_URL . $row['log_topic_id_new'], - 'TOPIC_HREF_NEW_S' => url_arg($url, $topic_key, $row['log_topic_id_new']), - 'TOPIC_TITLE_NEW' => $topic_title_new, + 'TOPIC_ID_NEW' => $row['log_topic_id_new'], + 'TOPIC_HREF_NEW' => BB_ROOT . TOPIC_URL . $row['log_topic_id_new'], + 'TOPIC_HREF_NEW_S' => url_arg($url, $topic_key, $row['log_topic_id_new']), + 'TOPIC_TITLE_NEW' => $topic_title_new, - 'DATE' => bb_date($row['log_time'], 'j-M'), - 'TIME' => bb_date($row['log_time'], 'H:i'), - 'DATETIME_HREF_S' => $datetime_href_s, - 'MSG' => $msg, - 'ROW_CLASS' => $row_class, + 'DATETIME' => bb_date($row['log_time'], 'd-M-y H:i'), + 'DATETIME_HREF_S' => $datetime_href_s, + 'MSG' => $msg, + 'ROW_CLASS' => $row_class, - )); + )); - // Topics - if ($topic_csv && empty($filter['topics'][$row['log_topic_title']])) - { - $template->assign_block_vars('topics', array( - 'TOPIC_TITLE' => $row['log_topic_title'], - )); - $filter['topics'][$row['log_topic_title']] = true; - } - // Forums - if ($forum_csv && empty($filter['forums'][$forum_name])) - { - $template->assign_block_vars('forums', array( - 'FORUM_NAME' => htmlCHR($forum_name), - )); - $filter['forums'][$forum_name] = true; - } - // Users - if ($user_csv && empty($filter['users'][$row['log_username']])) - { - $template->assign_block_vars('users', array( - 'USERNAME' => $row['log_username'], - )); - $filter['users'][$row['log_username']] = true; - } - } + // Topics + if ($topic_csv && empty($filter['topics'][$row['log_topic_title']])) { + $template->assign_block_vars('topics', array( + 'TOPIC_TITLE' => $row['log_topic_title'], + )); + $filter['topics'][$row['log_topic_title']] = true; + } + // Forums + if ($forum_csv && empty($filter['forums'][$forum_name])) { + $template->assign_block_vars('forums', array( + 'FORUM_NAME' => htmlCHR($forum_name), + )); + $filter['forums'][$forum_name] = true; + } + // Users + if ($user_csv && empty($filter['users'])) { + $template->assign_block_vars('users', array( + 'USERNAME' => profile_url($row, true), + )); + $filter['users'] = true; + } + } - $template->assign_vars(array( - 'FILTERS' => ($topic_csv || $forum_csv || $user_csv), - 'FILTER_TOPICS' => !empty($filter['topics']), - 'FILTER_FORUMS' => !empty($filter['forums']), - 'FILTER_USERS' => !empty($filter['users']), - )); -} -else -{ - $template->assign_block_vars('log_not_found', array()); + $template->assign_vars(array( + 'FILTERS' => $topic_csv || $forum_csv || $user_csv, + 'FILTER_TOPICS' => !empty($filter['topics']), + 'FILTER_FORUMS' => !empty($filter['forums']), + 'FILTER_USERS' => !empty($filter['users']), + )); +} else { + $template->assign_block_vars('log_not_found', []); } -// -// Selects -// +// Select $log_type_select = array($lang['ACTS_LOG_ALL_ACTIONS'] => $all_types) + $log_action->log_type_select; -// Order select -$order_options = ''; - $template->assign_vars(array( - 'LOG_COLSPAN' => 4, + 'LOG_COLSPAN' => 4, - 'DATETIME_NAME' => $datetime_key, - 'DATETIME_VAL' => date('Y-m-d', $datetime_val), - 'DAYSBACK_NAME' => $daysback_key, - 'DAYSBACK_VAL' => $daysback_val, - 'FIRST_LOG_TIME' => ($first_log_time) ? date('Y-m-d', $first_log_time) : $lang['ACC_NONE'], + 'DATETIME_NAME' => $datetime_key, + 'DATETIME_VAL' => date('Y-m-d', $datetime_val), + 'DAYSBACK_NAME' => $daysback_key, + 'DAYSBACK_VAL' => $daysback_val, + 'FIRST_LOG_TIME' => $first_log_time ? date('Y-m-d', $first_log_time) : $lang['ACC_NONE'], - 'TITLE_MATCH_MAX' => $title_match_max_len, - 'TITLE_MATCH_NAME' => $title_match_key, - 'TITLE_MATCH_VAL' => $title_match_val, + 'TITLE_MATCH_MAX' => $title_match_max_len, + 'TITLE_MATCH_NAME' => $title_match_key, + 'TITLE_MATCH_VAL' => $title_match_val, - 'ORDER_NAME' => '', - 'ORDER_OPTIONS' => $order_options, + 'SORT_NAME' => $sort_key, + 'SORT_ASC' => $sort_asc, + 'SORT_DESC' => $sort_desc, + 'SORT_ASC_CHECKED' => ($sort_val == $sort_asc) ? HTML_CHECKED : '', + 'SORT_DESC_CHECKED' => ($sort_val == $sort_desc) ? HTML_CHECKED : '', - 'SORT_NAME' => $sort_key, - 'SORT_ASC' => $sort_asc, - 'SORT_DESC' => $sort_desc, - 'SORT_ASC_CHECKED' => ($sort_val == $sort_asc) ? HTML_CHECKED : '', - 'SORT_DESC_CHECKED' => ($sort_val == $sort_desc) ? HTML_CHECKED : '', + 'SEL_FORUM' => get_forum_select('admin', "{$forum_key}[]", $forum_selected, $max_forum_name_len, $select_max_height, '', $all_forums), + 'SEL_LOG_TYPE' => build_select("{$type_key}[]", $log_type_select, $type_selected, 60, $select_max_height), + 'SEL_USERS' => build_select("{$user_key}[]", $users, $user_selected, 16, $select_max_height), - 'SEL_FORUM' => get_forum_select('admin', "{$forum_key}[]", $forum_selected, $max_forum_name_len, $select_max_height, '', $all_forums), - 'SEL_LOG_TYPE' => build_select("{$type_key}[]", $log_type_select, $type_selected, 60, $select_max_height), - 'SEL_USERS' => build_select("{$user_key}[]", $users, $user_selected, 16, $select_max_height), - - 'S_LOG_ACTION' => "admin_log.php", - 'TOPIC_CSV' => $topic_csv, + 'S_LOG_ACTION' => 'admin_log.php', + 'TOPIC_CSV' => $topic_csv, )); -print_page('admin_log.tpl', 'admin'); \ No newline at end of file +print_page('admin_log.tpl', 'admin'); diff --git a/admin/admin_mass_email.php b/admin/admin_mass_email.php index a9285ebf0..51902d960 100644 --- a/admin/admin_mass_email.php +++ b/admin/admin_mass_email.php @@ -1,102 +1,105 @@ get('emailer.enabled')) { + bb_die($lang['EMAILER_DISABLED']); +} -$errors = $user_id_sql = array(); +set_time_limit(1200); -if (isset($_POST['submit'])) -{ - if (!$subject) $errors[] = $lang['EMPTY_SUBJECT']; - if (!$message) $errors[] = $lang['EMPTY_MESSAGE']; - if (!$group_id) $errors[] = $lang['GROUP_NOT_EXIST']; +$subject = trim(request_var('subject', '')); +$message = (string)request_var('message', ''); +$group_id = (int)request_var(POST_GROUPS_URL, 0); +$reply_to = (string)request_var('reply_to', config()->get('board_email')); +$message_type = (string)request_var('message_type', ''); - if (!$errors) - { - $sql = DB()->fetch_rowset("SELECT ban_userid FROM ". BB_BANLIST ." WHERE ban_userid != 0"); +$errors = $user_id_sql = []; - foreach ($sql as $row) - { - $user_id_sql[] = ','. $row['ban_userid']; - } - $user_id_sql = join('', $user_id_sql); +if (isset($_POST['submit'])) { + if (!$subject) { + $errors[] = $lang['EMPTY_SUBJECT']; + } + if (!$message) { + $errors[] = $lang['EMPTY_MESSAGE']; + } + if (!$group_id) { + $errors[] = $lang['GROUP_NOT_EXIST']; + } - if ($group_id != -1) - { - $user_list = DB()->fetch_rowset(" + if (!$errors) { + $banned_users = ($get_banned_users = get_banned_users()) ? (', ' . implode(', ', $get_banned_users)) : ''; + + if ($group_id != -1) { + $user_list = DB()->fetch_rowset(' SELECT u.username, u.user_email, u.user_lang - FROM ". BB_USERS ." u, ". BB_USER_GROUP ." ug + FROM ' . BB_USERS . ' u, ' . BB_USER_GROUP . " ug WHERE ug.group_id = $group_id AND ug.user_pending = 0 AND u.user_id = ug.user_id AND u.user_active = 1 - AND u.user_id NOT IN(". EXCLUDED_USERS_CSV . $user_id_sql .") - "); - } - else - { - $user_list = DB()->fetch_rowset(" + AND u.user_id NOT IN(" . EXCLUDED_USERS . $banned_users . ') + '); + } else { + $user_list = DB()->fetch_rowset(' SELECT username, user_email, user_lang - FROM ". BB_USERS ." + FROM ' . BB_USERS . ' WHERE user_active = 1 - AND user_id NOT IN(". EXCLUDED_USERS_CSV . $user_id_sql .") - "); - } + AND user_id NOT IN(' . EXCLUDED_USERS . $banned_users . ') + '); + } - require(CLASS_DIR .'emailer.php'); + foreach ($user_list as $i => $row) { + // Sending email + $emailer = new TorrentPier\Emailer(); - foreach ($user_list as $i => $row) - { - $emailer = new emailer($bb_cfg['smtp_delivery']); + $emailer->set_to($row['user_email'], $row['username']); + $emailer->set_subject($subject); + $emailer->set_reply($reply_to); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); - $emailer->use_template('admin_send_email'); + $emailer->set_template('admin_send_email'); + $emailer->assign_vars(['MESSAGE' => trim(html_entity_decode($message))]); - $emailer->assign_vars(array( - 'SUBJECT' => html_entity_decode($subject), - 'MESSAGE' => html_entity_decode($message), - )); - - $emailer->send(); - $emailer->reset(); - } - } + $emailer->send($message_type); + } + } } // // Generate page // -$sql = "SELECT group_id, group_name - FROM ". BB_GROUPS ." +$sql = 'SELECT group_id, group_name + FROM ' . BB_GROUPS . ' WHERE group_single_user = 0 ORDER BY group_name -"; +'; -$groups = array('-- '. $lang['ALL_USERS'] .' --' => -1); -foreach (DB()->fetch_rowset($sql) as $row) -{ - $groups[$row['group_name']] = $row['group_id']; +$groups = ['-- ' . $lang['ALL_USERS'] . ' --' => -1]; +foreach (DB()->fetch_rowset($sql) as $row) { + $groups[$row['group_name']] = $row['group_id']; } -$template->assign_vars(array( - 'MESSAGE' => $message, - 'SUBJECT' => $subject, +$template->assign_vars([ + 'MESSAGE' => $message, + 'SUBJECT' => $subject, + 'REPLY_TO' => $reply_to, - 'ERROR_MESSAGE' => ($errors) ? join('
', array_unique($errors)) : '', + 'ERROR_MESSAGE' => $errors ? implode('
', array_unique($errors)) : '', - 'S_USER_ACTION' => 'admin_mass_email.php', - 'S_GROUP_SELECT' => build_select(POST_GROUPS_URL, $groups), -)); + 'S_USER_ACTION' => 'admin_mass_email.php', + 'S_GROUP_SELECT' => build_select(POST_GROUPS_URL, $groups) +]); -print_page('admin_mass_email.tpl', 'admin'); \ No newline at end of file +print_page('admin_mass_email.tpl', 'admin'); diff --git a/admin/admin_migrations.php b/admin/admin_migrations.php new file mode 100644 index 000000000..e416d81fb --- /dev/null +++ b/admin/admin_migrations.php @@ -0,0 +1,79 @@ +getMigrationStatus(); +$schemaInfo = $migrationStatus->getSchemaInfo(); + +// Template variables +$template->assign_vars([ + 'PAGE_TITLE' => __('MIGRATIONS_STATUS'), + 'CURRENT_TIME' => date('Y-m-d H:i:s'), + + // Migration status individual fields + 'MIGRATION_TABLE_EXISTS' => $status['table_exists'], + 'MIGRATION_CURRENT_VERSION' => $status['current_version'], + 'MIGRATION_APPLIED_COUNT' => count($status['applied_migrations']), + 'MIGRATION_PENDING_COUNT' => count($status['pending_migrations']), + + // Setup status fields + 'SETUP_REQUIRES_SETUP' => $status['requires_setup'] ?? false, + 'SETUP_TYPE' => $status['setup_status']['type'] ?? __('UNKNOWN'), + 'SETUP_MESSAGE' => $status['setup_status']['message'] ?? '', + 'SETUP_ACTION_REQUIRED' => $status['setup_status']['action_required'] ?? false, + 'SETUP_INSTRUCTIONS' => $status['setup_status']['instructions'] ?? '', + + // Schema info individual fields + 'SCHEMA_DATABASE_NAME' => $schemaInfo['database_name'], + 'SCHEMA_TABLE_COUNT' => $schemaInfo['table_count'], + 'SCHEMA_SIZE_MB' => $schemaInfo['size_mb'], +]); + +// Assign migration data for template +if (!empty($status['applied_migrations'])) { + foreach ($status['applied_migrations'] as $i => $migration) { + $template->assign_block_vars('applied_migrations', [ + 'VERSION' => $migration['version'], + 'NAME' => $migration['migration_name'] ?? __('UNKNOWN'), + 'START_TIME' => $migration['start_time'] ?? __('UNKNOWN'), + 'END_TIME' => $migration['end_time'] ?? __('UNKNOWN'), + 'ROW_CLASS' => ($i % 2) ? 'row1' : 'row2' + ]); + } +} + +if (!empty($status['pending_migrations'])) { + foreach ($status['pending_migrations'] as $i => $migration) { + $template->assign_block_vars('pending_migrations', [ + 'VERSION' => $migration['version'], + 'NAME' => $migration['name'], + 'FILENAME' => $migration['filename'], + 'ROW_CLASS' => ($i % 2) ? 'row1' : 'row2' + ]); + } +} + +// Output template using standard admin pattern +print_page('admin_migrations.tpl', 'admin'); diff --git a/admin/admin_phpinfo.php b/admin/admin_phpinfo.php index 1c70efd1e..1db2a7305 100644 --- a/admin/admin_phpinfo.php +++ b/admin/admin_phpinfo.php @@ -1,10 +1,29 @@ sql_query($sql)) - { - bb_die('Could not obtain ranks data #1'); - } +if ($mode != '') { + if ($mode == 'edit' || $mode == 'add') { + // + // They want to add a new rank, show the form. + // + $rank_id = isset($_GET['id']) ? (int)$_GET['id'] : 0; - $rank_info = DB()->sql_fetchrow($result); - $s_hidden_fields .= ''; - } - else - { - $rank_info['rank_special'] = 0; - } + $s_hidden_fields = ''; - $s_hidden_fields .= ''; + if ($mode == 'edit') { + if (empty($rank_id)) { + bb_die($lang['MUST_SELECT_RANK']); + } - $rank_is_special = !empty($rank_info['rank_special']) ? HTML_CHECKED : ''; - $rank_is_not_special = empty($rank_info['rank_special']) ? HTML_CHECKED : ''; + $sql = 'SELECT * FROM ' . BB_RANKS . " WHERE rank_id = $rank_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain ranks data #1'); + } - $template->assign_vars(array( - 'TPL_RANKS_EDIT' => true, + $rank_info = DB()->sql_fetchrow($result); + $s_hidden_fields .= ''; + } - 'RANK' => !empty($rank_info['rank_title']) ? $rank_info['rank_title'] : '', - 'SPECIAL_RANK' => $rank_is_special, - 'NOT_SPECIAL_RANK' => $rank_is_not_special, - 'MINIMUM' => ($rank_is_special) ? '' : @$rank_info['rank_min'], - 'IMAGE' => !empty($rank_info['rank_image']) ? $rank_info['rank_image'] : 'images/ranks/rank_image.png', - 'STYLE' => !empty($rank_info['rank_style']) ? $rank_info['rank_style'] : '', - 'IMAGE_DISPLAY' => !empty($rank_info['rank_image']) ? '' : '', + $s_hidden_fields .= ''; - 'S_RANK_ACTION' => "admin_ranks.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); - } - elseif ($mode == 'save') - { - // - // Ok, they sent us our info, let's update it. - // + $template->assign_vars([ + 'TPL_RANKS_EDIT' => true, - $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : 0; - $rank_title = (isset($_POST['title'])) ? trim($_POST['title']) : ''; - $rank_style = (isset($_POST['style'])) ? trim($_POST['style']) : ''; - $special_rank = ($_POST['special_rank'] == 1) ? TRUE : 0; - $min_posts = (isset($_POST['min_posts'])) ? intval($_POST['min_posts']) : -1; - $rank_image = ((isset($_POST['rank_image']))) ? trim($_POST['rank_image']) : ''; + 'RANK' => !empty($rank_info['rank_title']) ? $rank_info['rank_title'] : '', + 'IMAGE' => !empty($rank_info['rank_image']) ? $rank_info['rank_image'] : 'styles/images/ranks/rank_image.png', + 'STYLE' => !empty($rank_info['rank_style']) ? $rank_info['rank_style'] : '', + 'IMAGE_DISPLAY' => !empty($rank_info['rank_image']) ? '' : '', - if ($rank_title == '') - { - bb_die($lang['MUST_SELECT_RANK']); - } + 'S_RANK_ACTION' => 'admin_ranks.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields + ]); + } elseif ($mode == 'save') { + // + // Ok, they sent us our info, let's update it. + // - if ($special_rank == 1) - { - $max_posts = -1; - $min_posts = -1; - } + $rank_id = isset($_POST['id']) ? (int)$_POST['id'] : 0; + $rank_title = isset($_POST['title']) ? trim($_POST['title']) : ''; + $rank_style = isset($_POST['style']) ? trim($_POST['style']) : ''; + $rank_image = isset($_POST['rank_image']) ? trim($_POST['rank_image']) : ''; - // - // The rank image has to be a jpg, gif or png - // - if ($rank_image != '') - { - if (!preg_match('/(\.gif|\.png|\.jpg)$/is', $rank_image)) - { - $rank_image = ''; - } - } + if ($rank_title == '') { + bb_die($lang['MUST_SELECT_RANK']); + } - if ($rank_id) - { - if (!$special_rank) - { - $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die($lang['NO_UPDATE_RANKS']); - } - } - $sql = "UPDATE " . BB_RANKS . " - SET rank_title = '". DB()->escape($rank_title) ."', - rank_special = $special_rank, - rank_min = $min_posts, - rank_image = '". DB()->escape($rank_image) . "', - rank_style = '". DB()->escape($rank_style) ."' + // + // The rank image has to be a jpg, gif or png + // + if ($rank_image != '') { + if (!preg_match('/(\.gif|\.png|\.jpg|\.jpeg|\.bmp|\.webp|\.avif\.ico)$/is', $rank_image)) { + $rank_image = ''; + } + } + + if ($rank_id) { + + $sql = 'UPDATE ' . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die($lang['NO_UPDATE_RANKS']); + } + + $sql = 'UPDATE ' . BB_RANKS . " + SET rank_title = '" . DB()->escape($rank_title) . "', + rank_image = '" . DB()->escape($rank_image) . "', + rank_style = '" . DB()->escape($rank_style) . "' WHERE rank_id = $rank_id"; - $message = $lang['RANK_UPDATED']; - } - else - { - $sql = "INSERT INTO " . BB_RANKS . " (rank_title, rank_special, rank_min, rank_image, rank_style) - VALUES ('". DB()->escape($rank_title) ."', $special_rank, $min_posts, '". DB()->escape($rank_image) ."', '". DB()->escape($rank_style) ."')"; + $message = $lang['RANK_UPDATED']; + } else { + $sql = 'INSERT INTO ' . BB_RANKS . " (rank_title, rank_image, rank_style) + VALUES ('" . DB()->escape($rank_title) . "', '" . DB()->escape($rank_image) . "', '" . DB()->escape($rank_style) . "')"; - $message = $lang['RANK_ADDED']; - } + $message = $lang['RANK_ADDED']; + } - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not update / insert into ranks table'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not update / insert into ranks table'); + } - $message .= '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message .= '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - $datastore->update('ranks'); + $datastore->update('ranks'); - bb_die($message); - } - elseif ($mode == 'delete') - { - // - // Ok, they want to delete their rank - // + bb_die($message); + } elseif ($mode == 'delete') { + // + // Ok, they want to delete their rank + // - if (isset($_POST['id']) || isset($_GET['id'])) - { - $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : intval($_GET['id']); - } - else - { - $rank_id = 0; - } + $confirmed = isset($_POST['confirm']); + if (isset($_POST['id']) || isset($_GET['id'])) { + $rank_id = isset($_POST['id']) ? (int)$_POST['id'] : (int)$_GET['id']; + } else { + $rank_id = 0; + } - if ($rank_id) - { - $sql = "DELETE FROM " . BB_RANKS . " WHERE rank_id = $rank_id"; + if ($confirmed) { + if ($rank_id) { + $sql = 'DELETE FROM ' . BB_RANKS . " WHERE rank_id = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not delete rank data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not delete rank data'); + } - $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die($lang['NO_UPDATE_RANKS']); - } + $sql = 'UPDATE ' . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die($lang['NO_UPDATE_RANKS']); + } - $datastore->update('ranks'); + $datastore->update('ranks'); - bb_die($lang['RANK_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } - else - { - bb_die($lang['MUST_SELECT_RANK']); - } - } - else - { - bb_die('Invalid mode'); - } -} -else -{ - // - // Show the default page - // - $sql = "SELECT * FROM " . BB_RANKS . " ORDER BY rank_min, rank_title"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain ranks data #2'); - } - $rank_count = DB()->num_rows($result); - $rank_rows = DB()->sql_fetchrowset($result); + bb_die($lang['RANK_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + bb_die($lang['MUST_SELECT_RANK']); + } + } else { + $hidden_fields = ''; + $hidden_fields .= ''; - $template->assign_vars(array( - 'TPL_RANKS_LIST' => true, - 'S_RANKS_ACTION' => "admin_ranks.php", - )); + print_confirmation([ + 'FORM_ACTION' => 'admin_ranks.php', + 'HIDDEN_FIELDS' => $hidden_fields, + ]); + } + } else { + bb_die('Invalid mode'); + } +} else { + // + // Show the default page + // + $sql = 'SELECT * FROM ' . BB_RANKS . ' ORDER BY rank_title'; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain ranks data #2'); + } + $rank_count = DB()->num_rows($result); + $rank_rows = DB()->sql_fetchrowset($result); - for ($i = 0; $i < $rank_count; $i++) - { - $rank = $rank_rows[$i]['rank_title']; - $special_rank = $rank_rows[$i]['rank_special']; - $rank_id = $rank_rows[$i]['rank_id']; - $rank_min = $rank_rows[$i]['rank_min']; + $template->assign_vars([ + 'TPL_RANKS_LIST' => true, + 'S_RANKS_ACTION' => 'admin_ranks.php' + ]); - if ($special_rank == 1) - { - $rank_min = $rank_max = '-'; - } + for ($i = 0; $i < $rank_count; $i++) { + $rank = $rank_rows[$i]['rank_title']; + $rank_id = $rank_rows[$i]['rank_id']; - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $rank_is_special = ($special_rank) ? $lang['YES'] : $lang['NO']; + $template->assign_block_vars('ranks', [ + 'ROW_CLASS' => $row_class, + 'RANK' => $rank, + 'STYLE' => $rank_rows[$i]['rank_style'], + 'IMAGE_DISPLAY' => $rank_rows[$i]['rank_image'] ? '' : '', - $template->assign_block_vars('ranks', array( - 'ROW_CLASS' => $row_class, - 'RANK' => $rank, - 'STYLE' => $rank_rows[$i]['rank_style'], - 'IMAGE_DISPLAY' => ($rank_rows[$i]['rank_image']) ? '' : '', - 'SPECIAL_RANK' => $rank_is_special, - 'RANK_MIN' => $rank_min, - - 'U_RANK_EDIT' => "admin_ranks.php?mode=edit&id=$rank_id", - 'U_RANK_DELETE' => "admin_ranks.php?mode=delete&id=$rank_id", - )); - } + 'U_RANK_EDIT' => "admin_ranks.php?mode=edit&id=$rank_id", + 'U_RANK_DELETE' => "admin_ranks.php?mode=delete&id=$rank_id" + ]); + } } -print_page('admin_ranks.tpl', 'admin'); \ No newline at end of file +print_page('admin_ranks.tpl', 'admin'); diff --git a/admin/admin_rebuild_search.php b/admin/admin_rebuild_search.php index 391c2917f..cdd4fe32e 100644 --- a/admin/admin_rebuild_search.php +++ b/admin/admin_rebuild_search.php @@ -1,447 +1,422 @@ query(" - UPDATE ". BB_SEARCH_REBUILD ." SET - rebuild_session_status = ". REBUILD_SEARCH_ABORTED ." +if (isset($_REQUEST['cancel_button'])) { + // update the rebuild_status + if ($last_session_id) { + DB()->query(' + UPDATE ' . BB_SEARCH_REBUILD . ' SET + rebuild_session_status = ' . REBUILD_SEARCH_ABORTED . " WHERE rebuild_session_id = $last_session_id "); - } + } - bb_die(sprintf($lang['REBUILD_SEARCH_ABORTED'], $last_session_data['end_post_id']) .'

'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); + bb_die(sprintf($lang['REBUILD_SEARCH_ABORTED'], $last_session_data['end_post_id']) . '

' . sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); } // from which post to start processing -$start = abs(intval(@$_REQUEST['start'])); +$start = isset($_REQUEST['start']) ? abs((int)$_REQUEST['start']) : 0; // get the total number of posts in the db $total_posts = get_total_posts(); // clear the search tables and clear mode (delete or truncate) -$clear_search = isset($_REQUEST['clear_search']) ? (int) $_REQUEST['clear_search'] : 0; +$clear_search = isset($_REQUEST['clear_search']) ? (int)$_REQUEST['clear_search'] : 0; // get the number of total/session posts already processed -$total_posts_processed = ( $start != 0 ) ? get_total_posts('before', $last_session_data['end_post_id']) : 0; -$session_posts_processed = ( $mode == 'refresh' ) ? get_processed_posts('session') : 0; +$total_posts_processed = ($start != 0) ? get_total_posts('before', $last_session_data['end_post_id']) : 0; +$session_posts_processed = ($mode == 'refresh') ? get_processed_posts('session') : 0; // find how many posts aren't processed $total_posts_processing = $total_posts - $total_posts_processed; // how many posts to process in this session -if ($session_posts_processing = @intval($_REQUEST['session_posts_processing'])) -{ - if ($mode == 'submit') - { - // check if we passed over total_posts just after submitting - if ($session_posts_processing + $total_posts_processed > $total_posts) - { - $session_posts_processing = $total_posts - $total_posts_processed; - } - } - // correct it when posts are deleted during processing - $session_posts_processing = ($session_posts_processing > $total_posts) ? $total_posts : $session_posts_processing; -} -else -{ - // if we have finished, get all the posts, else only the remaining - $session_posts_processing = (!$total_posts_processing) ? $total_posts : $total_posts_processing; +$session_posts_processing = isset($_REQUEST['session_posts_processing']) ? (int)$_REQUEST['session_posts_processing'] : null; +if (null !== $session_posts_processing) { + if ($mode == 'submit') { + // check if we passed over total_posts just after submitting + if ($session_posts_processing + $total_posts_processed > $total_posts) { + $session_posts_processing = $total_posts - $total_posts_processed; + } + } + // correct it when posts are deleted during processing + $session_posts_processing = ($session_posts_processing > $total_posts) ? $total_posts : $session_posts_processing; +} else { + // if we have finished, get all the posts, else only the remaining + $session_posts_processing = (!$total_posts_processing) ? $total_posts : $total_posts_processing; } // how many posts to process per cycle -$post_limit = isset($_REQUEST['post_limit']) ? (int) $_REQUEST['post_limit'] : $def_post_limit; +$post_limit = isset($_REQUEST['post_limit']) ? (int)$_REQUEST['post_limit'] : $def_post_limit; // correct the post_limit when we pass over it -if ( $session_posts_processed + $post_limit > $session_posts_processing ) -{ - $post_limit = $session_posts_processing - $session_posts_processed; +if ($session_posts_processed + $post_limit > $session_posts_processing) { + $post_limit = $session_posts_processing - $session_posts_processed; } // how much time to wait per cycle -if (isset($_REQUEST['time_limit'])) -{ - $time_limit = (int) $_REQUEST['time_limit']; -} -else -{ - $time_limit = $def_time_limit; - $time_limit_explain = $lang['TIME_LIMIT_EXPLAIN']; +if (isset($_REQUEST['time_limit'])) { + $time_limit = (int)$_REQUEST['time_limit']; +} else { + $time_limit = $def_time_limit; + $time_limit_explain = $lang['TIME_LIMIT_EXPLAIN']; - // check for safe mode timeout - if ( ini_get('safe_mode') ) - { - // get execution time - $max_execution_time = ini_get('max_execution_time'); - $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_SAFE'], $max_execution_time); + // check for webserver timeout (IE returns null) + if (isset($_SERVER['HTTP_KEEP_ALIVE'])) { + // get webserver timeout + $webserver_timeout = (int)$_SERVER['HTTP_KEEP_ALIVE']; + $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_WEBSERVER'], $webserver_timeout); - if ( $time_limit > $max_execution_time ) - { - $time_limit = $max_execution_time; - } - } - - // check for webserver timeout (IE returns null) - if ( isset($_SERVER["HTTP_KEEP_ALIVE"]) ) - { - // get webserver timeout - $webserver_timeout = intval($_SERVER["HTTP_KEEP_ALIVE"]); - $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_WEBSERVER'], $webserver_timeout); - - if ( $time_limit > $webserver_timeout ) - { - $time_limit = $webserver_timeout; - } - } + if ($time_limit > $webserver_timeout) { + $time_limit = $webserver_timeout; + } + } } // how much time to wait between page refreshes -$refresh_rate = isset($_REQUEST['refresh_rate']) ? (int) $_REQUEST['refresh_rate'] : $def_refresh_rate; +$refresh_rate = isset($_REQUEST['refresh_rate']) ? (int)$_REQUEST['refresh_rate'] : $def_refresh_rate; // check if the user gave wrong input -if ($mode == 'submit') -{ - if (($session_posts_processing || $post_limit || $refresh_rate || $time_limit) <= 0) - { - bb_die($lang['WRONG_INPUT'] .'

'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); - } +if ($mode == 'submit') { + if (($session_posts_processing || $post_limit || $refresh_rate || $time_limit) <= 0) { + bb_die($lang['WRONG_INPUT'] . '

' . sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); + } } // Increase maximum execution time in case of a lot of posts, but don't complain about it if it isn't allowed. -@set_time_limit($time_limit + 20); +set_time_limit($time_limit + 20); // check if we are should start processing -if ($mode == 'submit' || $mode == 'refresh') -{ - // check if we are in the beginning of processing - if ($start == 0) - { - $last_session_data = get_empty_last_session_data(); - clear_search_tables($clear_search); - } +if ($mode == 'submit' || $mode == 'refresh') { + // check if we are in the beginning of processing + if ($start == 0) { + $last_session_data = get_empty_last_session_data(); + clear_search_tables($clear_search); + } - // get the db sizes - list($search_data_size, $search_index_size, $search_tables_size) = get_db_sizes(); + // get the db sizes + [$search_data_size, $search_index_size, $search_tables_size] = get_db_sizes(); - // get the post subject/text of each post - $result = DB()->query(" + // get the post subject/text of each post + $result = DB()->query(" SELECT pt.post_id, pt.post_text, IF(p.post_id = t.topic_first_post_id, t.topic_title, '') AS post_subject FROM - ". BB_POSTS_TEXT ." pt, - ". BB_POSTS ." p, - ". BB_TOPICS ." t + " . BB_POSTS_TEXT . ' pt, + ' . BB_POSTS . ' p, + ' . BB_TOPICS . ' t WHERE p.post_id = pt.post_id AND t.topic_id = p.topic_id - AND p.poster_id NOT IN(". BOT_UID .") + AND p.poster_id NOT IN(' . BOT_UID . ") AND pt.post_id >= $start ORDER BY pt.post_id ASC LIMIT $post_limit "); - $expire_time = $start_time + $time_limit - 5; - $start_post_id = $end_post_id = $num_rows = 0; - $timer_expired = false; - $words_sql = array(); + $expire_time = $start_time + $time_limit - 5; + $start_post_id = $end_post_id = $num_rows = 0; + $timer_expired = false; + $words_sql = []; - while ($row = DB()->fetch_next($result) AND !$timer_expired) - { - @set_time_limit(600); - $start_post_id = ($num_rows == 0) ? $row['post_id'] : $start_post_id; - $end_post_id = $row['post_id']; + while ($row = DB()->fetch_next($result) and !$timer_expired) { + set_time_limit(600); + $start_post_id = ($num_rows == 0) ? $row['post_id'] : $start_post_id; + $end_post_id = $row['post_id']; - // Get search words - $s_post_text = str_replace('\n', "\n", $row['post_text']); - $s_post_subject = str_replace('\n', "\n", $row['post_subject']); - $words_sql[] = array( - 'post_id' => (int) $row['post_id'], - 'search_words' => add_search_words($row['post_id'], stripslashes($s_post_text), stripslashes($s_post_subject), true), - ); + // Get search words + $s_post_text = str_replace('\n', "\n", $row['post_text']); + $s_post_subject = str_replace('\n', "\n", $row['post_subject']); + $words_sql[] = array( + 'post_id' => (int)$row['post_id'], + 'search_words' => add_search_words($row['post_id'], stripslashes($s_post_text), stripslashes($s_post_subject), true), + ); - $timer_expired = (TIMENOW > $expire_time); - $num_rows++; - } + $timer_expired = (TIMENOW > $expire_time); + $num_rows++; + } - // Store search words - if ($words_sql) - { - DB()->query("REPLACE INTO ". BB_POSTS_SEARCH . DB()->build_array('MULTI_INSERT', $words_sql)); - } + // Store search words + if ($words_sql) { + DB()->query('REPLACE INTO ' . BB_POSTS_SEARCH . DB()->build_array('MULTI_INSERT', $words_sql)); + } - // find how much time the last cycle took - $last_cycle_time = intval(TIMENOW - $start_time); + // find how much time the last cycle took + $last_cycle_time = (int)(TIMENOW - $start_time); - // check if we had any data - if ($num_rows != 0) - { - if ($mode == 'submit') - { - // insert a new session entry - $args = DB()->build_array('INSERT', array( - 'end_post_id' => (int) $end_post_id, - 'end_time' => (int) TIMENOW, - 'last_cycle_time' => (int) $last_cycle_time, - 'session_time' => (int) $last_cycle_time, - 'session_posts' => (int) $num_rows, - 'session_cycles' => (int) 1, - 'start_post_id' => (int) $start_post_id, - 'start_time' => (int) $start_time, - 'search_size' => (int) $search_tables_size, - 'rebuild_session_status' => REBUILD_SEARCH_PROCESSED, - )); - DB()->query("REPLACE INTO ". BB_SEARCH_REBUILD . $args); - } - else // refresh - { - // update the last session entry - DB()->query(" - UPDATE ". BB_SEARCH_REBUILD ." SET + // check if we had any data + if ($num_rows != 0) { + if ($mode == 'submit') { + // insert a new session entry + $args = DB()->build_array('INSERT', array( + 'end_post_id' => (int)$end_post_id, + 'end_time' => (int)TIMENOW, + 'last_cycle_time' => (int)$last_cycle_time, + 'session_time' => (int)$last_cycle_time, + 'session_posts' => (int)$num_rows, + 'session_cycles' => (int)1, + 'start_post_id' => (int)$start_post_id, + 'start_time' => (int)$start_time, + 'search_size' => (int)$search_tables_size, + 'rebuild_session_status' => REBUILD_SEARCH_PROCESSED, + )); + DB()->query('REPLACE INTO ' . BB_SEARCH_REBUILD . $args); + } else { + // refresh + + // update the last session entry + DB()->query(' + UPDATE ' . BB_SEARCH_REBUILD . " SET end_post_id = $end_post_id, - end_time = ". TIMENOW .", + end_time = " . TIMENOW . ", last_cycle_time = $last_cycle_time, session_time = session_time + $last_cycle_time, session_posts = session_posts + $num_rows, session_cycles = session_cycles + 1, - rebuild_session_status = ". REBUILD_SEARCH_PROCESSED ." + rebuild_session_status = " . REBUILD_SEARCH_PROCESSED . " WHERE rebuild_session_id = $last_session_id "); - } - } + } + } - $last_session_data = get_rebuild_session_details('last', 'all'); - $template->assign_vars(array('TPL_REBUILD_SEARCH_PROGRESS' => true)); + $last_session_data = get_rebuild_session_details('last', 'all'); + $template->assign_vars(array('TPL_REBUILD_SEARCH_PROGRESS' => true)); - $processing_messages = ''; - $processing_messages .= ($timer_expired) ? sprintf($lang['TIMER_EXPIRED'], TIMENOW - $start_time) : ''; - $processing_messages .= ($start == 0 && $clear_search) ? $lang['CLEARED_SEARCH_TABLES'] : ''; + $processing_messages = ''; + $processing_messages .= $timer_expired ? sprintf($lang['TIMER_EXPIRED'], TIMENOW - $start_time) : ''; + $processing_messages .= ($start == 0 && $clear_search) ? $lang['CLEARED_SEARCH_TABLES'] : ''; - // check if we have reached the end of our post processing - $session_posts_processed = get_processed_posts('session'); - $total_posts_processed = get_total_posts('before', $last_session_data['end_post_id']); - $total_posts = get_total_posts(); + // check if we have reached the end of our post processing + $session_posts_processed = get_processed_posts('session'); + $total_posts_processed = get_total_posts('before', $last_session_data['end_post_id']); + $total_posts = get_total_posts(); - if ( $session_posts_processed < $session_posts_processing && $total_posts_processed < $total_posts ) - { - $form_parameters = '&start='.($end_post_id+1); - $form_parameters .= '&session_posts_processing='.$session_posts_processing; - $form_parameters .= '&post_limit='.$post_limit; - $form_parameters .= '&time_limit='.$time_limit; - $form_parameters .= '&refresh_rate='.$refresh_rate; + if ($session_posts_processed < $session_posts_processing && $total_posts_processed < $total_posts) { + $form_parameters = '&start=' . ($end_post_id + 1); + $form_parameters .= '&session_posts_processing=' . $session_posts_processing; + $form_parameters .= '&post_limit=' . $post_limit; + $form_parameters .= '&time_limit=' . $time_limit; + $form_parameters .= '&refresh_rate=' . $refresh_rate; - $form_action = 'admin_rebuild_search.php'.'?mode=refresh'.$form_parameters; - $next_button = $lang['NEXT']; - $progress_bar_img = $images['progress_bar']; + $form_action = 'admin_rebuild_search.php' . '?mode=refresh' . $form_parameters; + $next_button = $lang['NEXT']; + $progress_bar_img = $images['progress_bar']; - $processing_messages .= sprintf($lang['PROCESSING_NEXT_POSTS'], $post_limit); + $processing_messages .= sprintf($lang['PROCESSING_NEXT_POSTS'], $post_limit); meta_refresh($form_action, $refresh_rate); - // create the meta tag for refresh - $template->assign_vars(array( - 'CANCEL_BUTTON' => true, - )); - } - else // end of processing - { - $form_action = "admin_rebuild_search.php"; - $next_button = $lang['FINISHED']; - $progress_bar_img = $images['progress_bar_full']; + // create the meta tag for refresh + $template->assign_vars(array( + 'CANCEL_BUTTON' => true, + )); + } else { + // end of processing - $processing_messages .= ( $session_posts_processed < $session_posts_processing ) ? sprintf($lang['DELETED_POSTS'], $session_posts_processing - $session_posts_processed) : ''; - $processing_messages .= ( $total_posts_processed == $total_posts ) ? $lang['ALL_POSTS_PROCESSED'] : $lang['ALL_SESSION_POSTS_PROCESSED']; + $form_action = 'admin_rebuild_search.php'; + $next_button = $lang['FINISHED']; + $progress_bar_img = $images['progress_bar_full']; - // if we have processed all the db posts we need to update the rebuild_status - DB()->query("UPDATE ". BB_SEARCH_REBUILD ." SET - rebuild_session_status = ". REBUILD_SEARCH_COMPLETED ." + $processing_messages .= ($session_posts_processed < $session_posts_processing) ? sprintf($lang['DELETED_POSTS'], $session_posts_processing - $session_posts_processed) : ''; + $processing_messages .= ($total_posts_processed == $total_posts) ? $lang['ALL_POSTS_PROCESSED'] : $lang['ALL_SESSION_POSTS_PROCESSED']; + + // if we have processed all the db posts we need to update the rebuild_status + DB()->query('UPDATE ' . BB_SEARCH_REBUILD . ' SET + rebuild_session_status = ' . REBUILD_SEARCH_COMPLETED . " WHERE rebuild_session_id = $last_session_id AND end_post_id = $max_post_id "); - // optimize all search tables when finished - $table_ary = array(BB_POSTS_SEARCH); + // optimize all search tables when finished + $table_ary = array(BB_POSTS_SEARCH); - foreach ($table_ary as $table) - { - DB()->query("ANALYZE TABLE $table"); - DB()->query("OPTIMIZE TABLE $table"); - } + foreach ($table_ary as $table) { + DB()->query("ANALYZE TABLE $table"); + DB()->query("OPTIMIZE TABLE $table"); + } - $processing_messages .= '
' . $lang['ALL_TABLES_OPTIMIZED']; - } + $processing_messages .= '
' . $lang['ALL_TABLES_OPTIMIZED']; + } - // calculate the percent - $session_percent = ($session_posts_processed / $session_posts_processing) * 100; - $total_percent = ($total_posts_processed / $total_posts) * 100; + // calculate the percent + if ($session_posts_processing > 0) { + $session_percent = ($session_posts_processed / $session_posts_processing) * 100; + } else { + $session_percent = 100; + } + if ($total_posts > 0) { + $total_percent = ($total_posts_processed / $total_posts) * 100; + } else { + $total_percent = 100; + } - // get the db sizes - list($search_data_size, $search_index_size, $search_tables_size) = get_db_sizes(); + // get the db sizes + [$search_data_size, $search_index_size, $search_tables_size] = get_db_sizes(); - // calculate the final (estimated) values - $final_search_tables_size = ''; + // calculate the final (estimated) values + $final_search_tables_size = ''; - if ($search_tables_size) - { - $start_search_tables_size = $last_session_data['search_size']; - $final_search_tables_size = $start_search_tables_size + round(($search_tables_size - $start_search_tables_size) * (100 / $session_percent)); - } + if ($search_tables_size) { + $start_search_tables_size = $last_session_data['search_size']; + $final_search_tables_size = $start_search_tables_size + round(($search_tables_size - $start_search_tables_size) * (100 / $session_percent)); + } - // calculate various times - $session_time = $last_session_data['session_time']; - $session_average_cycle_time = round($session_time / $last_session_data['session_cycles']); - $session_estimated_time = round($session_time * (100 / $session_percent)) - $session_time; + // calculate various times + $session_time = $last_session_data['session_time']; + if ($last_session_data['session_cycles'] > 0) { + $session_average_cycle_time = round($session_time / $last_session_data['session_cycles']); + } else { + $session_average_cycle_time = 0; + } + $session_estimated_time = round($session_time * (100 / $session_percent)) - $session_time; - // create the percent boxes - create_percent_box('session', create_percent_color($session_percent), $session_percent); - create_percent_box('total', create_percent_color($total_percent), $total_percent); + // create the percent boxes + create_percent_box('session', create_percent_color($session_percent), $session_percent); + create_percent_box('total', create_percent_color($total_percent), $total_percent); - $template->assign_vars(array( - 'L_NEXT' => $next_button, - 'L_TIME_LAST_POSTS_ADMIN' => sprintf($lang['TIME_LAST_POSTS'], $num_rows), + $template->assign_vars(array( + 'L_NEXT' => $next_button, + 'L_TIME_LAST_POSTS_ADMIN' => sprintf($lang['TIME_LAST_POSTS'], $num_rows), - 'PROCESSING_POSTS' => sprintf($lang['PROCESSED_POST_IDS'], $start_post_id, $end_post_id), - 'PROCESSING_MESSAGES' => $processing_messages, - 'PROGRESS_BAR_IMG' => $progress_bar_img, + 'PROCESSING_POSTS' => sprintf($lang['PROCESSED_POST_IDS'], $start_post_id, $end_post_id), + 'PROCESSING_MESSAGES' => $processing_messages, + 'PROGRESS_BAR_IMG' => $progress_bar_img, - 'SESSION_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $session_posts_processed - $num_rows + 1, $session_posts_processed, $session_posts_processing), - 'SESSION_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($session_percent, 2)), + 'SESSION_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $session_posts_processed - $num_rows + 1, $session_posts_processed, $session_posts_processing), + 'SESSION_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($session_percent, 2)), - 'TOTAL_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $total_posts_processed - $num_rows + 1, $total_posts_processed, $total_posts), - 'TOTAL_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($total_percent, 2)), + 'TOTAL_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $total_posts_processed - $num_rows + 1, $total_posts_processed, $total_posts), + 'TOTAL_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($total_percent, 2)), - 'LAST_CYCLE_TIME' => delta_time(TIMENOW), - 'SESSION_TIME' => delta_time($last_session_data['start_time']), - 'SESSION_AVERAGE_CYCLE_TIME'=> delta_time($session_average_cycle_time, 0), - 'SESSION_ESTIMATED_TIME' => delta_time($session_estimated_time, 0), + 'LAST_CYCLE_TIME' => delta_time(TIMENOW), + 'SESSION_TIME' => delta_time(($last_session_data['start_time'] == 0) ? TIMENOW : $last_session_data['start_time']), + 'SESSION_AVERAGE_CYCLE_TIME' => delta_time((int)$session_average_cycle_time, 0), + 'SESSION_ESTIMATED_TIME' => delta_time((int)$session_estimated_time, 0), - 'SEARCH_TABLES_SIZE' => humn_size($search_tables_size), - 'FINAL_SEARCH_TABLES_SIZE' => humn_size($final_search_tables_size), - 'SEARCH_DATA_SIZE' => humn_size($search_data_size), - 'SEARCH_INDEX_SIZE' => humn_size($search_index_size), + 'SEARCH_TABLES_SIZE' => humn_size($search_tables_size), + 'FINAL_SEARCH_TABLES_SIZE' => humn_size($final_search_tables_size), + 'SEARCH_DATA_SIZE' => humn_size($search_data_size), + 'SEARCH_INDEX_SIZE' => humn_size($search_index_size), - 'START_POST' => $last_session_data['start_post_id'], - 'POST_LIMIT' => $num_rows, - 'TIME_LIMIT' => $time_limit, - 'REFRESH_RATE' => $refresh_rate, + 'START_POST' => $last_session_data['start_post_id'], + 'POST_LIMIT' => $num_rows, + 'TIME_LIMIT' => $time_limit, + 'REFRESH_RATE' => $refresh_rate, - 'S_REBUILD_SEARCH_ACTION' => $form_action, - )); -} -else // show the input page -{ - // create the page - // used only with the select input - $post_limit_hidden = ( $def_post_limit > $total_posts ) ? $total_posts : $def_post_limit; + 'S_REBUILD_SEARCH_ACTION' => $form_action, + )); +} else {// show the input page + // create the page + // used only with the select input + $post_limit_hidden = ($def_post_limit > $total_posts) ? $total_posts : $def_post_limit; - $s_hidden_fields = ''; - $s_hidden_fields .= ''; + $s_hidden_fields = ''; + $s_hidden_fields .= ''; - $next_start_post_id = 0; - $last_saved_processing = ''; - $clear_search_disabled = ''; + $next_start_post_id = 0; + $last_saved_processing = ''; + $clear_search_disabled = ''; - if ($last_session_data['rebuild_session_id']) - { - $last_saved_post_id = $last_session_data['end_post_id']; - $next_start_post_id = $last_saved_post_id + 1; - $last_saved_date = bb_date($last_session_data['end_time']); + if ($last_session_data['rebuild_session_id']) { + $last_saved_post_id = $last_session_data['end_post_id']; + $next_start_post_id = $last_saved_post_id + 1; + $last_saved_date = bb_date($last_session_data['end_time']); - // check our last status - if ( $last_session_data['rebuild_session_status'] == REBUILD_SEARCH_PROCESSED ) - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_STOPPED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); - $clear_search_disabled = 'disabled="disabled"'; + // check our last status + if ($last_session_data['rebuild_session_status'] == REBUILD_SEARCH_PROCESSED) { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_STOPPED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); + $clear_search_disabled = 'disabled'; - $template->assign_block_vars("start_select_input", array()); - } - elseif ( $last_session_data['rebuild_session_status'] == REBUILD_SEARCH_ABORTED ) - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_ABORTED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); - // check if the interrupted cycle has finished - if ( TIMENOW - $last_session_data['end_time'] < $last_session_data['last_cycle_time'] ) - { - $last_saved_processing .= '
'.$lang['INFO_PROCESSING_ABORTED_SOON']; - } - $clear_search_disabled = 'disabled="disabled"'; + $template->assign_block_vars('start_select_input', []); + } elseif ($last_session_data['rebuild_session_status'] == REBUILD_SEARCH_ABORTED) { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_ABORTED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); + // check if the interrupted cycle has finished + if (TIMENOW - $last_session_data['end_time'] < $last_session_data['last_cycle_time']) { + $last_saved_processing .= '
' . $lang['INFO_PROCESSING_ABORTED_SOON']; + } + $clear_search_disabled = 'disabled'; - $template->assign_block_vars("start_select_input", array()); - } - else // when finished - { - if ( $last_session_data['end_post_id'] < $max_post_id ) - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED_NEW'], $last_saved_post_id, $total_posts_processed, $last_saved_date, ($total_posts - $total_posts_processed)); - $clear_search_disabled = 'disabled="disabled"'; + $template->assign_block_vars('start_select_input', []); + } else { + // when finished - $template->assign_block_vars("start_select_input", array()); - } - else - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED'], $total_posts, $last_saved_date); + if ($last_session_data['end_post_id'] < $max_post_id) { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED_NEW'], $last_saved_post_id, $total_posts_processed, $last_saved_date, $total_posts - $total_posts_processed); + $clear_search_disabled = 'disabled'; - $template->assign_block_vars("start_text_input", array()); - } - } + $template->assign_block_vars('start_select_input', []); + } else { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED'], $total_posts, $last_saved_date); - $template->assign_block_vars("last_saved_info", array()); - } - else - { - $template->assign_block_vars("start_text_input", array()); - } + $template->assign_block_vars('start_text_input', []); + } + } - // create the output of page - $template->assign_vars(array( - 'TPL_REBUILD_SEARCH_MAIN' => true, + $template->assign_block_vars('last_saved_info', []); + } else { + $template->assign_block_vars('start_text_input', []); + } - 'L_TIME_LIMIT_EXPLAIN' => $time_limit_explain, + // create the output of page + $template->assign_vars(array( + 'TPL_REBUILD_SEARCH_MAIN' => true, - 'NEXT_START_POST_ID' => $next_start_post_id, - 'CLEAR_SEARCH_DISABLED' => $clear_search_disabled, - 'SESSION_POSTS_PROCESSING' => $session_posts_processing, - 'POST_LIMIT' => $post_limit, - 'REFRESH_RATE' => $refresh_rate, - 'TIME_LIMIT' => $time_limit, + 'L_TIME_LIMIT_EXPLAIN' => $time_limit_explain, - 'LAST_SAVED_PROCESSING' => $last_saved_processing, + 'NEXT_START_POST_ID' => $next_start_post_id, + 'CLEAR_SEARCH_DISABLED' => $clear_search_disabled, + 'SESSION_POSTS_PROCESSING' => $session_posts_processing, + 'POST_LIMIT' => $post_limit, + 'REFRESH_RATE' => $refresh_rate, + 'TIME_LIMIT' => $time_limit, - 'SESSION_ID' => $userdata['session_id'], + 'LAST_SAVED_PROCESSING' => $last_saved_processing, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_REBUILD_SEARCH_ACTION' => "admin_rebuild_search.php?mode=submit", - )); + 'SESSION_ID' => $userdata['session_id'], + + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_REBUILD_SEARCH_ACTION' => 'admin_rebuild_search.php?mode=submit', + )); } print_page('admin_rebuild_search.tpl', 'admin'); @@ -449,124 +424,117 @@ print_page('admin_rebuild_search.tpl', 'admin'); // // Functions // -function get_db_sizes () +function get_db_sizes() { - $search_data_size = $search_index_size = 0; - $search_table_like = DB()->escape(BB_POSTS_SEARCH); + $search_data_size = $search_index_size = 0; + $search_table_like = DB()->escape(BB_POSTS_SEARCH); - $sql = "SHOW TABLE STATUS FROM `". DB()->selected_db ."` LIKE '$search_table_like'"; + $sql = 'SHOW TABLE STATUS FROM `' . DB()->selected_db . "` LIKE '$search_table_like'"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $search_data_size += $row['Data_length']; - $search_index_size += $row['Index_length']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $search_data_size += $row['Data_length']; + $search_index_size += $row['Index_length']; + } - return array($search_data_size, $search_index_size, $search_data_size+$search_index_size); + return array($search_data_size, $search_index_size, $search_data_size + $search_index_size); } // get the latest post_id in the forum -function get_latest_post_id () +function get_latest_post_id() { - $row = DB()->fetch_row("SELECT MAX(post_id) as post_id FROM ". BB_POSTS_TEXT); + $row = DB()->fetch_row('SELECT MAX(post_id) as post_id FROM ' . BB_POSTS_TEXT); - return (int) $row['post_id']; + return (int)$row['post_id']; } -function get_empty_last_session_data () +function get_empty_last_session_data() { - return array( - 'rebuild_session_id' => 0, - 'start_post_id' => 0, - 'end_post_id' => 0, - 'start_time' => 0, - 'end_time' => 0, - 'last_cycle_time' => 0, - 'session_time' => 0, - 'session_posts' => 0, - 'session_cycles' => 0, - 'search_size' => 0, - 'rebuild_session_status' => REBUILD_SEARCH_COMPLETED, - ); + return array( + 'rebuild_session_id' => 0, + 'start_post_id' => 0, + 'end_post_id' => 0, + 'start_time' => 0, + 'end_time' => 0, + 'last_cycle_time' => 0, + 'session_time' => 0, + 'session_posts' => 0, + 'session_cycles' => 0, + 'search_size' => 0, + 'rebuild_session_status' => REBUILD_SEARCH_COMPLETED, + ); } // get some or all of the rebuild details of a specific session or of the last session // $id is the id or the 'last' id // $details is one of the fields or 'all' of them -function get_rebuild_session_details ($id, $details = 'all') +function get_rebuild_session_details($id, $details = 'all') { - $session_details = get_empty_last_session_data(); + $session_details = get_empty_last_session_data(); - if ($id != 'last') - { - $sql = "SELECT * FROM ". BB_SEARCH_REBUILD ." WHERE rebuild_session_id = $id"; - } - else - { - $sql = "SELECT * FROM ". BB_SEARCH_REBUILD ." ORDER BY rebuild_session_id DESC LIMIT 1"; - } + if ($id != 'last') { + $sql = 'SELECT * FROM ' . BB_SEARCH_REBUILD . " WHERE rebuild_session_id = $id"; + } else { + $sql = 'SELECT * FROM ' . BB_SEARCH_REBUILD . ' ORDER BY rebuild_session_id DESC LIMIT 1'; + } - if ($row = DB()->fetch_row($sql)) - { - $session_details = ($details == 'all') ? $row : $row[$details]; - } + if ($row = DB()->fetch_row($sql)) { + $session_details = ($details == 'all') ? $row : $row[$details]; + } - return $session_details; + return $session_details; } // get the number of processed posts in the last session or in all sessions // 'total' to get the sum of posts of all sessions // 'session' to get the posts of the last session -function get_processed_posts ($mode = 'session') +function get_processed_posts($mode = 'session') { - global $last_session_data; + global $last_session_data; + $row = []; - if ($mode == 'total') - { - $sql = "SELECT SUM(session_posts) as posts FROM ". BB_SEARCH_REBUILD; - $row = DB()->fetch_row($sql); - } - else - { - $row['posts'] = $last_session_data['session_posts']; - } + if ($mode == 'total') { + $sql = 'SELECT SUM(session_posts) as posts FROM ' . BB_SEARCH_REBUILD; + $row = DB()->fetch_row($sql); + } else { + $row['posts'] = $last_session_data['session_posts']; + } - return (int) $row['posts']; + return (int)$row['posts']; } // how many posts are in the db before or after a specific post_id // after/before require and the post_id -function get_total_posts ($mode = 'after', $post_id = 0) +function get_total_posts($mode = 'after', $post_id = 0) { - if ($post_id) - { - $sql = "SELECT COUNT(post_id) as total_posts FROM " . BB_POSTS_TEXT . " - WHERE post_id " . (($mode == 'after') ? '>= ' : '<= ' ) . (int) $post_id; - } - else - { - $sql = "SELECT COUNT(*) as total_posts FROM " . BB_POSTS_TEXT; - } + if ($post_id) { + $sql = 'SELECT COUNT(post_id) as total_posts FROM ' . BB_POSTS_TEXT . ' + WHERE post_id ' . (($mode == 'after') ? '>= ' : '<= ') . (int)$post_id; + } else { + $sql = 'SELECT COUNT(*) as total_posts FROM ' . BB_POSTS_TEXT; + } - $row = DB()->fetch_row($sql); + $row = DB()->fetch_row($sql); + $totalPosts = (int)$row['total_posts']; - return (int) $row['total_posts']; + if ($totalPosts < 0) { + return 0; + } + + return $totalPosts; } -function clear_search_tables ($mode = '') +function clear_search_tables($mode = '') { - DB()->query("DELETE FROM ". BB_SEARCH_REBUILD); + DB()->query('DELETE FROM ' . BB_SEARCH_REBUILD); - if ($mode) - { - $table_ary = array(BB_POSTS_SEARCH); + if ($mode) { + $table_ary = array(BB_POSTS_SEARCH); - foreach ($table_ary as $table) - { - $sql = (($mode == 1) ? "DELETE FROM " : "TRUNCATE TABLE ") . $table; - DB()->query($sql); - } - } + foreach ($table_ary as $table) { + $sql = (($mode == 1) ? 'DELETE FROM ' : 'TRUNCATE TABLE ') . $table; + DB()->query($sql); + } + } } // Create the percent color @@ -576,49 +544,45 @@ function clear_search_tables ($mode = '') // We limit the result to 200, in order to avoid white (255). function create_percent_color($percent) { - $percent_ary = array( - 'r' => array(86, 100), - 'g' => array(0, 50), - 'b' => array(51, 85), - ); + $percent_color = null; + $percent_ary = array( + 'r' => array(86, 100), + 'g' => array(0, 50), + 'b' => array(51, 85), + ); - foreach ($percent_ary as $key => $value) - { - if ( $percent <= $value[1] ) - { - $percent_color = create_color($key, round(200-($percent-$value[0])*(200/($value[1]-$value[0])))); - break; - } - } + foreach ($percent_ary as $key => $value) { + if ($percent <= $value[1]) { + $percent_color = create_color($key, round(200 - ($percent - $value[0]) * (200 / ($value[1] - $value[0])))); + break; + } + } - return $percent_color; + return $percent_color; } // create the hex representation of color function create_color($mode, $code) { - return (($mode == 'r') ? 'FF': sprintf("%02X", $code)) . (($mode == 'g') ? 'FF': sprintf("%02X", $code)) . (($mode == 'b') ? 'FF': sprintf("%02X", $code)); + return (($mode == 'r') ? 'FF' : sprintf('%02X', $code)) . (($mode == 'g') ? 'FF' : sprintf('%02X', $code)) . (($mode == 'b') ? 'FF' : sprintf('%02X', $code)); } // create the percent bar & box function create_percent_box($box, $percent_color, $percent_width) { - global $template; + global $template; - if ($box == 'session') - { - $template->assign_vars(array( - 'SESSION_PERCENT_BOX' => true, - 'SESSION_PERCENT_COLOR' => $percent_color, - 'SESSION_PERCENT_WIDTH' => round($percent_width), - )); - } - else - { - $template->assign_vars(array( - 'TOTAL_PERCENT_BOX' => true, - 'TOTAL_PERCENT_COLOR' => $percent_color, - 'TOTAL_PERCENT_WIDTH' => round($percent_width), - )); - } -} \ No newline at end of file + if ($box == 'session') { + $template->assign_vars(array( + 'SESSION_PERCENT_BOX' => true, + 'SESSION_PERCENT_COLOR' => $percent_color, + 'SESSION_PERCENT_WIDTH' => round($percent_width), + )); + } else { + $template->assign_vars(array( + 'TOTAL_PERCENT_BOX' => true, + 'TOTAL_PERCENT_COLOR' => $percent_color, + 'TOTAL_PERCENT_WIDTH' => round($percent_width), + )); + } +} diff --git a/admin/admin_robots.php b/admin/admin_robots.php new file mode 100644 index 000000000..44d73d52b --- /dev/null +++ b/admin/admin_robots.php @@ -0,0 +1,45 @@ +
' . sprintf($lang['CLICK_RETURN_ROBOTS_TXT_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); +} + +$current_content = ''; +if (is_file($robots_file)) { + $current_content = file_get_contents($robots_file); +} + +$template->assign_vars([ + 'S_ACTION' => 'admin_robots.php', + 'ROBOTS_TXT' => htmlCHR($current_content), +]); + +print_page('admin_robots.tpl', 'admin'); diff --git a/admin/admin_sitemap.php b/admin/admin_sitemap.php index 3976758af..66e2f800b 100644 --- a/admin/admin_sitemap.php +++ b/admin/admin_sitemap.php @@ -1,52 +1,50 @@ sql_query($sql)) -{ - bb_die('Could not query config information in admin_sitemap'); -} -else -{ - $new_params = array(); - - while ($row = DB()->sql_fetchrow($result)) - { - $config_name = $row['config_name']; - $config_value = $row['config_value']; - $default_config[$config_name] = $config_value; - $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; - - if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) - { - $new_params[$config_name] = $new[$config_name]; - } - } - - if (isset($_POST['submit'])) - { - if (!empty($new_params)) - { - bb_update_config($new_params); - } - } +if (!empty($setmodules)) { + $module['MODS']['SITEMAP'] = basename(__FILE__); + return; } -$s_mess = $lang['SITEMAP_CREATED'].': '.bb_date($new['sitemap_time'], $bb_cfg['post_date_format']).' '.$lang['SITEMAP_AVAILABLE'].': '.make_url('sitemap.xml').''; -$message = (@file_exists(BB_ROOT. "/internal_data/sitemap/sitemap.xml")) ? $s_mess : $lang['SITEMAP_NOT_CREATED']; +require __DIR__ . '/pagestart.php'; -$template->assign_vars(array( - 'STATIC_SITEMAP' => $new['static_sitemap'], - 'MESSAGE' => $message, -)); +$sql = "SELECT * FROM " . BB_CONFIG . " WHERE config_name IN('sitemap_time', 'static_sitemap')"; -print_page('admin_sitemap.tpl', 'admin'); \ No newline at end of file +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query config information in admin_sitemap'); +} else { + $new_params = []; + + while ($row = DB()->sql_fetchrow($result)) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; + $default_config[$config_name] = $config_value; + $new[$config_name] = $_POST[$config_name] ?? $default_config[$config_name]; + + if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) { + $new_params[$config_name] = $new[$config_name]; + } + } + + if (isset($_POST['submit'])) { + if (!empty($new_params)) { + bb_update_config($new_params); + } + } +} + +$s_mess = $lang['SITEMAP_CREATED'] . ': ' . bb_date($new['sitemap_time'], config()->get('post_date_format')) . ' ' . $lang['SITEMAP_AVAILABLE'] . ': ' . make_url('sitemap/sitemap.xml') . ''; +$message = is_file(SITEMAP_DIR . '/sitemap.xml') ? $s_mess : $lang['SITEMAP_NOT_CREATED']; + +$template->assign_vars([ + 'STATIC_SITEMAP' => $new['static_sitemap'], + 'MESSAGE' => $message +]); + +print_page('admin_sitemap.tpl', 'admin'); diff --git a/admin/admin_smilies.php b/admin/admin_smilies.php index 4d60e7090..9e84c3ea0 100644 --- a/admin/admin_smilies.php +++ b/admin/admin_smilies.php @@ -1,370 +1,334 @@ get('smilies_path'); +$delimeter = '=+:'; +$s_hidden_fields = ''; +$smiley_paks = $smiley_images = []; + +// Read a listing of uploaded smiles +$smilesDirectory = new DirectoryIterator($pathToSmilesDir); + +foreach ($smilesDirectory as $files) { + if ($files->isFile()) { + $extension = strtolower(pathinfo($files->getFilename(), PATHINFO_EXTENSION)); + if (in_array($extension, ['png', 'gif'], true) && getimagesize($pathToSmilesDir . '/' . $files->getFilename())) { + $smiley_images[] = $files->getFilename(); + } else if ($extension === 'pak') { + $smiley_paks[] = $files->getFilename(); + } + } +} // Select main mode -if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) -{ - $smile_pak = (string) request_var('smile_pak', ''); - $clear_current = (int) request_var('clear_current', ''); - $replace_existing = (int) request_var('replace', ''); +if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) { + $smile_pak = (string)request_var('smile_pak', ''); + $clear_current = (int)request_var('clear_current', ''); + $replace_existing = (int)request_var('replace', ''); - if (!empty($smile_pak)) - { - // The user has already selected a smile_pak file.. Import it - if (!empty($clear_current)) - { - $sql = "DELETE FROM " . BB_SMILIES; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not delete current smilies'); - } - $datastore->update('smile_replacements'); - } - else - { - $sql = "SELECT code FROM ". BB_SMILIES; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get current smilies'); - } + if (!empty($smile_pak)) { + // The user has already selected a smile_pak file.. Import it + if (!empty($clear_current)) { + $sql = 'DELETE FROM ' . BB_SMILIES; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not delete current smilies'); + } + $datastore->update('smile_replacements'); + } else { + $sql = 'SELECT code FROM ' . BB_SMILIES; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get current smilies'); + } - $cur_smilies = DB()->sql_fetchrowset($result); + $cur_smilies = DB()->sql_fetchrowset($result); - for ($i = 0; $i < count($cur_smilies); $i++) - { - $k = $cur_smilies[$i]['code']; - $smiles[$k] = 1; - } - } + for ($i = 0, $iMax = count($cur_smilies); $i < $iMax; $i++) { + $k = $cur_smilies[$i]['code']; + $smiles[$k] = 1; + } + } - $fcontents = @file(BB_ROOT . $bb_cfg['smilies_path'] . '/'. $smile_pak); + $fcontents = file($pathToSmilesDir . '/' . $smile_pak); - if (empty($fcontents)) - { - bb_die('Could not read smiley pak file'); - } + if (empty($fcontents)) { + bb_die('Could not read smiley pak file'); + } - for ($i = 0; $i < count($fcontents); $i++) - { - $smile_data = explode($delimeter, trim(addslashes($fcontents[$i]))); + foreach ($fcontents as $i => $iValue) { + $smile_data = explode($delimeter, trim(addslashes($fcontents[$i]))); - for ($j = 2; $j < count($smile_data); $j++) - { - // Replace > and < with the proper html_entities for matching - $smile_data[$j] = str_replace('<', '<', $smile_data[$j]); - $smile_data[$j] = str_replace('>', '>', $smile_data[$j]); - $k = $smile_data[$j]; + for ($j = 2, $jMax = count($smile_data); $j < $jMax; $j++) { + // Replace > and < with the proper html_entities for matching + $smile_data[$j] = str_replace('<', '<', $smile_data[$j]); + $smile_data[$j] = str_replace('>', '>', $smile_data[$j]); + $k = $smile_data[$j]; - if (isset($smiles[$k])) - { - if( !empty($replace_existing) ) - { - $sql = "UPDATE " . BB_SMILIES . " + if (isset($smiles[$k])) { + if (!empty($replace_existing)) { + $sql = 'UPDATE ' . BB_SMILIES . " SET smile_url = '" . DB()->escape($smile_data[0]) . "', emoticon = '" . DB()->escape($smile_data[1]) . "' WHERE code = '" . DB()->escape($smile_data[$j]) . "'"; - } - else - { - $sql = ''; - } - } - else - { - $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) + } else { + $sql = ''; + } + } else { + $sql = 'INSERT INTO ' . BB_SMILIES . " (code, smile_url, emoticon) VALUES('" . DB()->escape($smile_data[$j]) . "', '" . DB()->escape($smile_data[0]) . "', '" . DB()->escape($smile_data[1]) . "')"; - } + } - if ($sql != '') - { - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not update smilies #1'); - } - $datastore->update('smile_replacements'); - } - } - } + if ($sql != '') { + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not update smilies #1'); + } + $datastore->update('smile_replacements'); + } + } + } - bb_die($lang['SMILEY_IMPORT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } - else - { - // Display the script to get the smile_pak cfg file - $smile_paks_select = ''; + bb_die($lang['SMILEY_IMPORT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + // Display the script to get the smile_pak cfg file + $smile_paks_select = ''; - $hidden_vars = ''; + $hidden_vars = ''; - $template->assign_vars(array( - 'TPL_SMILE_IMPORT' => true, + $template->assign_vars([ + 'TPL_SMILE_IMPORT' => true, - 'S_SMILEY_ACTION' => 'admin_smilies.php', - 'S_SMILE_SELECT' => $smile_paks_select, - 'S_HIDDEN_FIELDS' => $hidden_vars, - )); - } -} -else if (isset($_POST['export_pack']) || isset($_GET['export_pack'])) -{ - $export_pack = (string) request_var('export_pack', ''); + 'S_SMILEY_ACTION' => 'admin_smilies.php', + 'S_SMILE_SELECT' => $smile_paks_select, + 'S_HIDDEN_FIELDS' => $hidden_vars + ]); + } +} elseif (isset($_POST['export_pack']) || isset($_GET['export_pack'])) { + $export_pack = (string)request_var('export_pack', ''); - if ($export_pack == 'send') - { - $sql = "SELECT * FROM " . BB_SMILIES; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get smiley list'); - } + if ($export_pack == 'send') { + $sql = 'SELECT * FROM ' . BB_SMILIES; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get smiley list'); + } - $resultset = DB()->sql_fetchrowset($result); + $resultset = DB()->sql_fetchrowset($result); - $smile_pak = ''; - for ($i = 0; $i < count($resultset); $i++) - { - $smile_pak .= $resultset[$i]['smile_url'] . $delimeter; - $smile_pak .= $resultset[$i]['emoticon'] . $delimeter; - $smile_pak .= $resultset[$i]['code'] . "\n"; - } + $smile_pak = ''; + for ($i = 0, $iMax = count($resultset); $i < $iMax; $i++) { + $smile_pak .= $resultset[$i]['smile_url'] . $delimeter; + $smile_pak .= $resultset[$i]['emoticon'] . $delimeter; + $smile_pak .= $resultset[$i]['code'] . "\n"; + } - header("Content-Type: text/x-delimtext; name=\"smiles.pak\""); - header("Content-disposition: attachment; filename=smiles.pak"); + header('Content-Type: text/x-delimtext; name="smiles.pak"'); + header('Content-disposition: attachment; filename=smiles.pak'); - echo $smile_pak; + echo $smile_pak; - exit; - } + exit; + } - bb_die(sprintf($lang['EXPORT_SMILES'], '', '') . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); -} -else if (isset($_POST['add']) || isset($_GET['add'])) -{ - $filename_list = ''; - for ($i = 0; $i < count($smiley_images); $i++) - { - $filename_list .= ''; - } + bb_die(sprintf($lang['EXPORT_SMILES'], '', '') . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); +} elseif (isset($_POST['add']) || isset($_GET['add'])) { + $filename_list = ''; + for ($i = 0, $iMax = count($smiley_images); $i < $iMax; $i++) { + $filename_list .= ''; + } - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $template->assign_vars(array( - 'TPL_SMILE_EDIT' => true, - 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smiley_images[0], - 'S_SMILEY_ACTION' => "admin_smilies.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_FILENAME_OPTIONS' => $filename_list, - 'S_SMILEY_BASEDIR' => BB_ROOT . $bb_cfg['smilies_path'] - )); -} -else if ( $mode != '' ) -{ - switch( $mode ) - { - case 'delete': - $smiley_id = ( !empty($_POST['id']) ) ? $_POST['id'] : $_GET['id']; - $smiley_id = intval($smiley_id); + $template->assign_vars([ + 'TPL_SMILE_EDIT' => true, + 'SMILEY_IMG' => $pathToSmilesDir . '/' . $smiley_images[0], + 'S_SMILEY_ACTION' => 'admin_smilies.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_FILENAME_OPTIONS' => $filename_list, + 'S_SMILEY_BASEDIR' => $pathToSmilesDir + ]); +} elseif ($mode != '') { + switch ($mode) { + case 'delete': + $confirmed = isset($_POST['confirm']); + $smiley_id = (!empty($_POST['id'])) ? $_POST['id'] : $_GET['id']; + $smiley_id = (int)$smiley_id; - $sql = "DELETE FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not delete smiley'); - } - $datastore->update('smile_replacements'); + if ($confirmed) { + $sql = 'DELETE FROM ' . BB_SMILIES . ' WHERE smilies_id = ' . $smiley_id; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not delete smiley'); + } - bb_die($lang['SMILEY_DEL_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + $datastore->update('smile_replacements'); + bb_die($lang['SMILEY_DEL_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + $hidden_fields = ''; + $hidden_fields .= ''; - case 'edit': - $smiley_id = ( !empty($_POST['id']) ) ? $_POST['id'] : $_GET['id']; - $smiley_id = intval($smiley_id); + print_confirmation([ + 'FORM_ACTION' => 'admin_smilies.php', + 'HIDDEN_FIELDS' => $hidden_fields, + ]); + } + break; - $sql = "SELECT * FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not obtain emoticon information'); - } - $smile_data = DB()->sql_fetchrow($result); + case 'edit': + $smiley_id = (!empty($_POST['id'])) ? $_POST['id'] : $_GET['id']; + $smiley_id = (int)$smiley_id; - $filename_list = ''; - for ($i = 0; $i < count($smiley_images); $i++) - { - if ($smiley_images[$i] == $smile_data['smile_url']) - { - $smiley_selected = 'selected="selected"'; - $smiley_edit_img = $smiley_images[$i]; - } - else - { - $smiley_selected = ''; - } - $filename_list .= ''; - } + $sql = 'SELECT * FROM ' . BB_SMILIES . ' WHERE smilies_id = ' . $smiley_id; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not obtain emoticon information'); + } + $smile_data = DB()->sql_fetchrow($result); - $s_hidden_fields = ''; + $filename_list = $smiley_edit_img = ''; + for ($i = 0, $iMax = count($smiley_images); $i < $iMax; $i++) { + if ($smiley_images[$i] == $smile_data['smile_url']) { + $smiley_selected = 'selected'; + $smiley_edit_img = $smiley_images[$i]; + } else { + $smiley_selected = ''; + } + $filename_list .= ''; + } - $template->assign_vars(array( - 'TPL_SMILE_EDIT' => true, - 'SMILEY_CODE' => $smile_data['code'], - 'SMILEY_EMOTICON' => $smile_data['emoticon'], - 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smiley_edit_img, - 'S_SMILEY_ACTION' => "admin_smilies.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_FILENAME_OPTIONS' => $filename_list, - 'S_SMILEY_BASEDIR' => BB_ROOT . $bb_cfg['smilies_path'], - )); + $s_hidden_fields = ''; - break; + $template->assign_vars([ + 'TPL_SMILE_EDIT' => true, + 'SMILEY_CODE' => $smile_data['code'], + 'SMILEY_EMOTICON' => $smile_data['emoticon'], + 'SMILEY_IMG' => $pathToSmilesDir . '/' . $smiley_edit_img, + 'S_SMILEY_ACTION' => 'admin_smilies.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_FILENAME_OPTIONS' => $filename_list, + 'S_SMILEY_BASEDIR' => $pathToSmilesDir + ]); - case 'save': - $smile_code = ( isset($_POST['smile_code']) ) ? trim($_POST['smile_code']) : trim($_GET['smile_code']); - $smile_url = ( isset($_POST['smile_url']) ) ? trim($_POST['smile_url']) : trim($_GET['smile_url']); - $smile_url = bb_ltrim(basename($smile_url), "'"); - $smile_emotion = ( isset($_POST['smile_emotion']) ) ? trim($_POST['smile_emotion']) : trim($_GET['smile_emotion']); - $smile_id = ( isset($_POST['smile_id']) ) ? intval($_POST['smile_id']) : intval($_GET['smile_id']); + break; - // If no code was entered complain - if ($smile_code == '' || $smile_url == '') - { - bb_die($lang['FIELDS_EMPTY']); - } + case 'save': + $smile_code = isset($_POST['smile_code']) ? trim($_POST['smile_code']) : trim($_GET['smile_code']); + $smile_url = isset($_POST['smile_url']) ? trim($_POST['smile_url']) : trim($_GET['smile_url']); + $smile_url = ltrim(basename($smile_url), "'"); + $smile_emotion = isset($_POST['smile_emotion']) ? trim($_POST['smile_emotion']) : trim($_GET['smile_emotion']); + $smile_id = isset($_POST['smile_id']) ? (int)$_POST['smile_id'] : (int)$_GET['smile_id']; - // Convert < and > to proper htmlentities for parsing - $smile_code = str_replace('<', '<', $smile_code); - $smile_code = str_replace('>', '>', $smile_code); + // If no code was entered complain + if ($smile_code == '' || $smile_url == '') { + bb_die($lang['FIELDS_EMPTY']); + } - // Proceed with updating the smiley table - $sql = "UPDATE " . BB_SMILIES . " + // Convert < and > to proper htmlentities for parsing + $smile_code = str_replace(['<', '>'], ['<', '>'], $smile_code); + + // Proceed with updating the smiley table + $sql = 'UPDATE ' . BB_SMILIES . " SET code = '" . DB()->escape($smile_code) . "', smile_url = '" . DB()->escape($smile_url) . "', emoticon = '" . DB()->escape($smile_emotion) . "' WHERE smilies_id = $smile_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update smilies #2'); - } - $datastore->update('smile_replacements'); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update smilies #2'); + } + $datastore->update('smile_replacements'); - bb_die($lang['SMILEY_EDIT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + bb_die($lang['SMILEY_EDIT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; - case 'savenew': - $smile_code = ( isset($_POST['smile_code']) ) ? $_POST['smile_code'] : $_GET['smile_code']; - $smile_url = ( isset($_POST['smile_url']) ) ? $_POST['smile_url'] : $_GET['smile_url']; - $smile_url = bb_ltrim(basename($smile_url), "'"); - $smile_emotion = ( isset($_POST['smile_emotion']) ) ? $_POST['smile_emotion'] : $_GET['smile_emotion']; - $smile_code = trim($smile_code); - $smile_url = trim($smile_url); - $smile_emotion = trim($smile_emotion); + case 'savenew': + $smile_code = $_POST['smile_code'] ?? $_GET['smile_code']; + $smile_url = $_POST['smile_url'] ?? $_GET['smile_url']; + $smile_url = ltrim(basename($smile_url), "'"); + $smile_emotion = $_POST['smile_emotion'] ?? $_GET['smile_emotion']; + $smile_code = trim($smile_code); + $smile_url = trim($smile_url); + $smile_emotion = trim($smile_emotion); - // If no code was entered complain - if ($smile_code == '' || $smile_url == '') - { - bb_die($lang['FIELDS_EMPTY']); - } + // If no code was entered complain + if ($smile_code == '' || $smile_url == '') { + bb_die($lang['FIELDS_EMPTY']); + } - // Convert < and > to proper htmlentities for parsing - $smile_code = str_replace('<', '<', $smile_code); - $smile_code = str_replace('>', '>', $smile_code); + // Convert < and > to proper htmlentities for parsing + $smile_code = str_replace(['<', '>'], ['<', '>'], $smile_code); - // Save the data to the smiley table - $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) + // Save the data to the smiley table + $sql = 'INSERT INTO ' . BB_SMILIES . " (code, smile_url, emoticon) VALUES ('" . DB()->escape($smile_code) . "', '" . DB()->escape($smile_url) . "', '" . DB()->escape($smile_emotion) . "')"; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not insert new smiley'); - } - $datastore->update('smile_replacements'); + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not insert new smiley'); + } + $datastore->update('smile_replacements'); - bb_die($lang['SMILEY_ADD_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; - } -} -else -{ - $sql = "SELECT * FROM " . BB_SMILIES; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not obtain smileys from database'); - } + bb_die($lang['SMILEY_ADD_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; + } +} else { + $sql = 'SELECT * FROM ' . BB_SMILIES; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not obtain smileys from database'); + } - $smilies = DB()->sql_fetchrowset($result); + $smilies = DB()->sql_fetchrowset($result); - $template->assign_vars(array( - 'TPL_SMILE_MAIN' => true, - 'S_HIDDEN_FIELDS' => @$s_hidden_fields, - 'S_SMILEY_ACTION' => 'admin_smilies.php', - )); + $template->assign_vars([ + 'TPL_SMILE_MAIN' => true, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_SMILEY_ACTION' => 'admin_smilies.php' + ]); - // Loop throuh the rows of smilies setting block vars for the template - for ($i = 0; $i < count($smilies); $i++) - { - // Replace htmlentites for < and > with actual character - $smilies[$i]['code'] = str_replace('<', '<', $smilies[$i]['code']); - $smilies[$i]['code'] = str_replace('>', '>', $smilies[$i]['code']); + // Loop throuh the rows of smilies setting block vars for the template + for ($i = 0, $iMax = count($smilies); $i < $iMax; $i++) { + // Replace htmlentites for < and > with actual character + $smilies[$i]['code'] = str_replace('<', '<', $smilies[$i]['code']); + $smilies[$i]['code'] = str_replace('>', '>', $smilies[$i]['code']); - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('smiles', array( - 'ROW_CLASS' => $row_class, + $template->assign_block_vars('smiles', [ + 'ROW_CLASS' => $row_class, - 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] .'/'. $smilies[$i]['smile_url'], - 'CODE' => $smilies[$i]['code'], - 'EMOT' => $smilies[$i]['emoticon'], + 'SMILEY_IMG' => $pathToSmilesDir . '/' . $smilies[$i]['smile_url'], + 'CODE' => $smilies[$i]['code'], + 'EMOT' => $smilies[$i]['emoticon'], - 'U_SMILEY_EDIT' => "admin_smilies.php?mode=edit&id=". $smilies[$i]['smilies_id'], - 'U_SMILEY_DELETE' => "admin_smilies.php?mode=delete&id=". $smilies[$i]['smilies_id'], - )); - } + 'U_SMILEY_EDIT' => 'admin_smilies.php?mode=edit&id=' . $smilies[$i]['smilies_id'], + 'U_SMILEY_DELETE' => 'admin_smilies.php?mode=delete&id=' . $smilies[$i]['smilies_id'], + ]); + } } -print_page('admin_smilies.tpl', 'admin'); \ No newline at end of file +print_page('admin_smilies.tpl', 'admin'); diff --git a/admin/admin_terms.php b/admin/admin_terms.php index cb9437927..45acd875c 100644 --- a/admin/admin_terms.php +++ b/admin/admin_terms.php @@ -1,25 +1,32 @@ $_POST['message'])); - bb_die($lang['CONFIG_UPDATED']); +if (!empty($setmodules)) { + $module['GENERAL']['TERMS'] = basename(__FILE__); + return; } -$template->assign_vars(array( - 'S_ACTION' => 'admin_terms.php', - 'EXT_LINK_NW' => $bb_cfg['ext_link_new_win'], - 'MESSAGE' => ($bb_cfg['terms']) ? $bb_cfg['terms'] : '', - 'PREVIEW_HTML' => (isset($_REQUEST['preview'])) ? bbcode2html($_POST['message']) : '', -)); +require __DIR__ . '/pagestart.php'; +require INC_DIR . '/bbcode.php'; -print_page('admin_terms.tpl', 'admin'); \ No newline at end of file +$preview = isset($_POST['preview']); + +if (isset($_POST['post']) && (config()->get('terms') !== $_POST['message'])) { + bb_update_config(['terms' => $_POST['message']]); + bb_die($lang['TERMS_UPDATED_SUCCESSFULLY'] . '

' . sprintf($lang['CLICK_RETURN_TERMS_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); +} + +$template->assign_vars([ + 'S_ACTION' => 'admin_terms.php', + 'EXT_LINK_NW' => config()->get('ext_link_new_win'), + 'MESSAGE' => $preview ? $_POST['message'] : config()->get('terms'), + 'PREVIEW_HTML' => $preview ? bbcode2html($_POST['message']) : '', +]); + +print_page('admin_terms.tpl', 'admin'); diff --git a/admin/admin_ug_auth.php b/admin/admin_ug_auth.php index 1fd568925..7cef20864 100644 --- a/admin/admin_ug_auth.php +++ b/admin/admin_ug_auth.php @@ -1,474 +1,426 @@ fetch_row($sql)) - { - $group_id = $row['group_id']; - } - else - { - $group_id = create_user_group($user_id); - } + if ($row = DB()->fetch_row($sql)) { + $group_id = $row['group_id']; + } else { + $group_id = \TorrentPier\Legacy\Group::create_user_group($user_id); + } - if (!$group_id || !$user_id || is_null($this_user_level)) - { - trigger_error('data missing', E_USER_ERROR); - } + if (!$group_id || !$user_id || null === $this_user_level) { + trigger_error('data missing', E_USER_ERROR); + } - // Make user an admin (if already user) - if (@$_POST['userlevel'] === 'admin') - { - if ($userdata['user_id'] == $user_id || $user_id == GUEST_UID || $user_id == BOT_UID) - { - bb_die("Could not update admin status"); - } + // Make user an admin (if already user) + if (isset($_POST['userlevel'])) { + if ($_POST['userlevel'] === 'admin') { + if ($userdata['user_id'] == $user_id || $user_id == GUEST_UID || $user_id == BOT_UID) { + bb_die($lang['AUTH_GENERAL_ERROR']); + } - DB()->query("UPDATE ". BB_USERS ." SET user_level = ". ADMIN ." WHERE user_id = $user_id LIMIT 1"); + DB()->query('UPDATE ' . BB_USERS . ' SET user_level = ' . ADMIN . " WHERE user_id = $user_id"); - // Delete any entries in auth_access, they are not required if user is becoming an admin - delete_permissions($group_id, $user_id); + // Delete any entries in auth_access, they are not required if user is becoming an admin + \TorrentPier\Legacy\Group::delete_permissions($group_id, $user_id); - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - // Make admin a user (if already admin) - else if (@$_POST['userlevel'] === 'user') - { - // ignore if you're trying to change yourself from an admin to user! - if ($userdata['user_id'] == $user_id) - { - bb_die("Could not update admin status

Could not change yourself from an admin to user"); - } - // Update users level, reset to USER - DB()->query("UPDATE ". BB_USERS ." SET user_level = ". USER ." WHERE user_id = $user_id LIMIT 1"); + bb_die($message); + } // Make admin a user (if already admin) + elseif ($_POST['userlevel'] === 'user') { + // ignore if you're trying to change yourself from an admin to user! + if ($userdata['user_id'] == $user_id) { + bb_die($lang['AUTH_SELF_ERROR']); + } + // Update users level, reset to USER + DB()->query('UPDATE ' . BB_USERS . ' SET user_level = ' . USER . " WHERE user_id = $user_id"); - delete_permissions($group_id, $user_id); + \TorrentPier\Legacy\Group::delete_permissions($group_id, $user_id); - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } + bb_die($message); + } + } - // - // Submit new USER permissions - // - $auth = array(); + // + // Submit new USER permissions + // + $auth = []; - if (is_array(@$_POST['auth'])) - { - array_deep($_POST['auth'], 'intval'); + if (!empty($_POST['auth']) && is_array($_POST['auth'])) { + array_deep($_POST['auth'], 'intval'); - foreach ($_POST['auth'] as $f_id => $bf_ary) - { - if (array_sum($bf_ary)) - { - $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); - } - } - } + foreach ($_POST['auth'] as $f_id => $bf_ary) { + if (array_sum($bf_ary)) { + $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); + } + } + } - delete_permissions($group_id, null, $cat_id); - store_permissions($group_id, $auth); + \TorrentPier\Legacy\Group::delete_permissions($group_id, null, $cat_id); + \TorrentPier\Legacy\Group::store_permissions($group_id, $auth); + \TorrentPier\Legacy\Group::update_user_level($user_id); - update_user_level($user_id); + $l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH']; + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($l_auth_return, '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - $l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH']; - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($l_auth_return, '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - - bb_die($message); + bb_die($message); } // // Submit new GROUP permissions // -else if ($submit && $mode == 'group' && is_array(@$_POST['auth'])) -{ - if (!$group_data = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } +elseif ($submit && $mode == 'group' && (!empty($_POST['auth']) && is_array($_POST['auth']))) { + if (!$group_data = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } - $auth = array(); - array_deep($_POST['auth'], 'intval'); + $auth = []; + array_deep($_POST['auth'], 'intval'); - foreach ($_POST['auth'] as $f_id => $bf_ary) - { - if (array_sum($bf_ary)) - { - $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); - } - } + foreach ($_POST['auth'] as $f_id => $bf_ary) { + if (array_sum($bf_ary)) { + $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); + } + } - delete_permissions($group_id, null, $cat_id); - store_permissions($group_id, $auth); + \TorrentPier\Legacy\Group::delete_permissions($group_id, null, $cat_id); + \TorrentPier\Legacy\Group::store_permissions($group_id, $auth); + \TorrentPier\Legacy\Group::update_user_level('all'); - update_user_level('all'); + $l_auth_return = $lang['CLICK_RETURN_GROUPAUTH']; + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($l_auth_return, '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - $l_auth_return = $lang['CLICK_RETURN_GROUPAUTH']; - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($l_auth_return, '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - - bb_die($message); + bb_die($message); } // // Front end (changing permissions) // -if ($mode == 'user' && (!empty($_POST['username']) || $user_id)) -{ - $page_cfg['quirks_mode'] = true; +if ($mode == 'user' && (!empty($_POST['username']) || $user_id)) { + $page_cfg['quirks_mode'] = true; - if (!empty($_POST['username'])) - { - $this_userdata = get_userdata($_POST['username'], true); - $user_id = $this_userdata['user_id']; - } - else - { - $this_userdata = get_userdata($user_id); - } - if (!$this_userdata) - { - bb_die($lang['NO_SUCH_USER']); - } + if (!empty($_POST['username'])) { + $this_userdata = get_userdata($_POST['username'], true); + $user_id = $this_userdata['user_id']; + } else { + $this_userdata = get_userdata($user_id); + } + if (!$this_userdata) { + bb_die($lang['NO_SUCH_USER']); + } - if (!$forums = $datastore->get('cat_forums')) - { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } - $base_url = basename(__FILE__) ."?mode=user&u=$user_id"; + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } + $base_url = basename(__FILE__) . "?mode=user&" . POST_USERS_URL . "=$user_id"; - $ug_data = $this_userdata; - $ug_data['session_logged_in'] = 1; + $ug_data = $this_userdata; + $ug_data['session_logged_in'] = 1; - $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_USER_ONLY); - $g_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_GROUP_ONLY); + $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, [], UG_PERM_USER_ONLY); + $g_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, [], UG_PERM_GROUP_ONLY); - foreach ($forums['c'] as $c_id => $c_data) - { - $template->assign_block_vars('c', array( - 'CAT_ID' => $c_id, - 'CAT_TITLE' => $forums['cat_title_html'][$c_id], - 'CAT_HREF' => "$base_url&c=$c_id", - )); + foreach ($forums['c'] as $c_id => $c_data) { + $template->assign_block_vars('c', array( + 'CAT_ID' => $c_id, + 'CAT_TITLE' => $forums['cat_title_html'][$c_id], + 'CAT_HREF' => "$base_url&" . POST_CAT_URL . "=$c_id", + )); - if (!$c =& $_REQUEST['c'] OR !in_array($c, array('all', $c_id)) OR empty($c_data['forums'])) - { - continue; - } + if (!$c =& $_REQUEST[POST_CAT_URL] or !in_array($c, array('all', $c_id)) or empty($c_data['forums'])) { + continue; + } - foreach ($c_data['forums'] as $f_id) - { - $f_data = $forums['f'][$f_id]; - $auth_mod = ($u_access[$f_id]['auth_mod'] || $g_access[$f_id]['auth_mod']); - $disabled = $g_access[$f_id]['auth_mod']; + foreach ($c_data['forums'] as $f_id) { + $f_data = $forums['f'][$f_id]; + $auth_mod = ($u_access[$f_id]['auth_mod'] || $g_access[$f_id]['auth_mod']); + $disabled = $g_access[$f_id]['auth_mod']; - $template->assign_block_vars('c.f', array( - 'DISABLED' => $disabled, - 'FORUM_ID' => $f_id, - 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), - 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', - 'IS_MODERATOR' => (bool) $auth_mod, - 'MOD_STATUS' => ($auth_mod) ? $lang['MODERATOR'] : $lang['NONE'], - 'MOD_CLASS' => ($auth_mod) ? (($disabled) ? 'yesDisabled' : 'yesMOD') : 'noMOD', - 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, - )); + $template->assign_block_vars('c.f', array( + 'DISABLED' => $disabled, + 'FORUM_ID' => $f_id, + 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), + 'SF_SPACER' => $f_data['forum_parent'] ? HTML_SF_SPACER : '', + 'IS_MODERATOR' => (bool)$auth_mod, + 'MOD_STATUS' => $auth_mod ? $lang['MODERATOR'] : $lang['NONE'], + 'MOD_CLASS' => $auth_mod ? ($disabled ? 'yesDisabled' : 'yesMOD') : 'noMOD', + 'AUTH_MOD_VAL' => $auth_mod ? 1 : 0, + )); - foreach ($forum_auth_fields as $auth_type) - { - $bf_num = $bf['forum_perm'][$auth_type]; - $f_perm = $f_data[$auth_type]; - $auth_via_acl = ($u_access[$f_id][$auth_type] || $g_access[$f_id][$auth_type]); + foreach ($forum_auth_fields as $auth_type) { + $bf_num = $bf['forum_perm'][$auth_type]; + $f_perm = $f_data[$auth_type]; + $auth_via_acl = ($u_access[$f_id][$auth_type] || $g_access[$f_id][$auth_type]); - if ($f_perm == AUTH_ACL) - { - $disabled = ($auth_mod || $g_access[$f_id][$auth_type]); - $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; - } - else - { - $disabled = true; - $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl) ? 'yes' : 'no'; - } + if ($f_perm == AUTH_ACL) { + $disabled = ($auth_mod || $g_access[$f_id][$auth_type]); + $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; + $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; + } else { + $disabled = true; + $perm_sign = $auth_via_acl ? $yes_sign : $no_sign; + $acl_class = $auth_via_acl ? 'yes' : 'no'; + } - $template->assign_block_vars('c.f.acl', array( - 'DISABLED' => $disabled, - 'PERM_SIGN' => $perm_sign, - 'ACL_CLASS' => $acl_class, - 'FORUM_ID' => $f_id, - 'ACL_TYPE_BF' => $bf_num, - 'ACL_VAL' => ($auth_via_acl) ? 1 : 0, - )); - } - } - } + $template->assign_block_vars('c.f.acl', array( + 'DISABLED' => $disabled, + 'PERM_SIGN' => $perm_sign, + 'ACL_CLASS' => $acl_class, + 'FORUM_ID' => $f_id, + 'ACL_TYPE_BF' => $bf_num, + 'ACL_VAL' => $auth_via_acl ? 1 : 0, + )); + } + } + } - $template->assign_vars(array( - 'AUTH_MOD_BF' => AUTH_MOD, - )); + $template->assign_vars(array( + 'AUTH_MOD_BF' => AUTH_MOD, + )); - $s_column_span = 2; + $s_column_span = 2; - foreach ($forum_auth_fields as $auth_type) - { - $template->assign_block_vars('acltype', array( - 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1
", $lang[strtoupper($auth_type)]), - 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], - )); - $s_column_span++; - } + foreach ($forum_auth_fields as $auth_type) { + $template->assign_block_vars('acltype', array( + 'ACL_TYPE_NAME' => preg_replace('#(.{5})#u', "\\1
", $lang[strtoupper($auth_type)]), + 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], + )); + $s_column_span++; + } - unset($forums, $u_access, $g_access); - $datastore->rm('cat_forums'); + unset($forums, $u_access, $g_access); + $datastore->rm('cat_forums'); - $s_hidden_fields = ' - - + $s_hidden_fields = ' + + '; - $s_user_type = ($this_userdata['user_level'] == ADMIN) ? ' + $s_user_type = ($this_userdata['user_level'] == ADMIN) ? ' ' : ' '; - $template->assign_block_vars('switch_user_auth', array()); + $template->assign_block_vars('switch_user_auth', []); - $template->assign_vars(array( - 'TPL_AUTH_UG_MAIN' => true, + $template->assign_vars(array( + 'TPL_AUTH_UG_MAIN' => true, + 'USER_OR_GROUPNAME' => profile_url($this_userdata, true), + 'USER_LEVEL' => $lang['USER_LEVEL'] . ' : ' . $s_user_type, + 'T_USER_OR_GROUPNAME' => $lang['USERNAME'], + 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_USER'], + 'T_AUTH_EXPLAIN' => $lang['USER_AUTH_EXPLAIN'], + 'S_COLUMN_SPAN' => $s_column_span, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); +} elseif ($mode == 'group' && $group_id) { + $page_cfg['quirks_mode'] = true; - 'USER_OR_GROUPNAME' => $this_userdata['username'], - 'USER_LEVEL' => $lang['USER_LEVEL'] .' : '. $s_user_type, - 'USER_GROUP_MEMBERSHIPS' => $lang['GROUP_MEMBERSHIPS'], - )); + if (!$group_data = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } - $template->assign_vars(array( - 'T_USER_OR_GROUPNAME' => $lang['USERNAME'], - 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_USER'], - 'T_AUTH_EXPLAIN' => $lang['USER_AUTH_EXPLAIN'], + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } + $base_url = basename(__FILE__) . "?mode=group&" . POST_GROUPS_URL . "=$group_id"; - 'S_COLUMN_SPAN' => $s_column_span, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); -} -else if ($mode == 'group' && $group_id) -{ - $page_cfg['quirks_mode'] = true; + $ug_data = array('group_id' => $group_id); + $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data); - if (!$group_data = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } + foreach ($forums['c'] as $c_id => $c_data) { + $template->assign_block_vars('c', array( + 'CAT_ID' => $c_id, + 'CAT_TITLE' => $forums['cat_title_html'][$c_id], + 'CAT_HREF' => "$base_url&" . POST_CAT_URL . "=$c_id", + )); - if (!$forums = $datastore->get('cat_forums')) - { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } - $base_url = basename(__FILE__) ."?mode=group&g=$group_id"; + if (!($c =& $_REQUEST[POST_CAT_URL]) || !in_array($c, array('all', $c_id)) || empty($c_data['forums'])) { + continue; + } - $ug_data = array('group_id' => $group_id); - $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data); + foreach ($c_data['forums'] as $f_id) { + $f_data = $forums['f'][$f_id]; + $auth_mod = $u_access[$f_id]['auth_mod']; - foreach ($forums['c'] as $c_id => $c_data) - { - $template->assign_block_vars('c', array( - 'CAT_ID' => $c_id, - 'CAT_TITLE' => $forums['cat_title_html'][$c_id], - 'CAT_HREF' => "$base_url&c=$c_id", - )); + $template->assign_block_vars('c.f', array( + 'DISABLED' => false, + 'FORUM_ID' => $f_id, + 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), + 'SF_SPACER' => $f_data['forum_parent'] ? HTML_SF_SPACER : '', + 'IS_MODERATOR' => (bool)$auth_mod, + 'MOD_STATUS' => $auth_mod ? $lang['MODERATOR'] : $lang['NO'], + 'MOD_CLASS' => $auth_mod ? 'yesMOD' : 'noMOD', + 'AUTH_MOD_VAL' => $auth_mod ? 1 : 0, + )); - if (!$c =& $_REQUEST['c'] OR !in_array($c, array('all', $c_id)) OR empty($c_data['forums'])) - { - continue; - } + foreach ($forum_auth_fields as $auth_type) { + $bf_num = $bf['forum_perm'][$auth_type]; + $f_perm = $f_data[$auth_type]; + $auth_via_acl = $u_access[$f_id][$auth_type]; - foreach ($c_data['forums'] as $f_id) - { - $f_data = $forums['f'][$f_id]; - $auth_mod = $u_access[$f_id]['auth_mod']; + if ($f_perm == AUTH_ACL) { + $disabled = $auth_mod; + $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; + $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; + } else { + $disabled = true; + $perm_sign = $auth_via_acl ? $yes_sign : $no_sign; + $acl_class = $auth_via_acl ? 'yes' : 'no'; + } - $template->assign_block_vars('c.f', array( - 'DISABLED' => false, - 'FORUM_ID' => $f_id, - 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), - 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', - 'IS_MODERATOR' => (bool) $auth_mod, - 'MOD_STATUS' => ($auth_mod) ? $lang['MODERATOR'] : $lang['NO'], - 'MOD_CLASS' => ($auth_mod) ? 'yesMOD' : 'noMOD', - 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, - )); + $template->assign_block_vars('c.f.acl', array( + 'DISABLED' => $disabled, + 'PERM_SIGN' => $perm_sign, + 'ACL_CLASS' => $acl_class, + 'FORUM_ID' => $f_id, + 'ACL_TYPE_BF' => $bf_num, + 'ACL_VAL' => $auth_via_acl ? 1 : 0, + )); + } + } + } - foreach ($forum_auth_fields as $auth_type) - { - $bf_num = $bf['forum_perm'][$auth_type]; - $f_perm = $f_data[$auth_type]; - $auth_via_acl = $u_access[$f_id][$auth_type]; + $template->assign_vars(array( + 'AUTH_MOD_BF' => AUTH_MOD, + )); - if ($f_perm == AUTH_ACL) - { - $disabled = $auth_mod; - $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; - } - else - { - $disabled = true; - $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl) ? 'yes' : 'no'; - } + $s_column_span = 2; - $template->assign_block_vars('c.f.acl', array( - 'DISABLED' => $disabled, - 'PERM_SIGN' => $perm_sign, - 'ACL_CLASS' => $acl_class, - 'FORUM_ID' => $f_id, - 'ACL_TYPE_BF' => $bf_num, - 'ACL_VAL' => ($auth_via_acl) ? 1 : 0, - )); - } - } - } + foreach ($forum_auth_fields as $auth_type) { + $template->assign_block_vars('acltype', array( + 'ACL_TYPE_NAME' => preg_replace('#(.{5})#u', "\\1
", $lang[strtoupper($auth_type)]), + 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], + )); + $s_column_span++; + } - $template->assign_vars(array( - 'AUTH_MOD_BF' => AUTH_MOD, - )); + unset($forums, $ug_data, $u_access); + $datastore->rm('cat_forums'); - $s_column_span = 2; - - foreach ($forum_auth_fields as $auth_type) - { - $template->assign_block_vars('acltype', array( - 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1
", $lang[strtoupper($auth_type)]), - 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], - )); - $s_column_span++; - } - - unset($forums, $ug_data, $u_access); - $datastore->rm('cat_forums'); - - $s_hidden_fields = ' - - + $s_hidden_fields = ' + + '; - $template->assign_vars(array( - 'TPL_AUTH_UG_MAIN' => true, + $template->assign_vars(array( + 'TPL_AUTH_UG_MAIN' => true, + 'T_USER_OR_GROUPNAME' => $lang['GROUP_NAME'], + 'USER_LEVEL' => false, + 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_GROUP'], + 'T_AUTH_EXPLAIN' => $lang['GROUP_AUTH_EXPLAIN'], + 'USER_OR_GROUPNAME' => ('' . htmlCHR($group_data['group_name']) . ''), + 'S_COLUMN_SPAN' => $s_column_span, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); +} else { + // Select a user/group + if ($mode == 'user') { + $template->assign_vars(array( + 'TPL_SELECT_USER' => true, + 'U_SEARCH_USER' => BB_ROOT . 'search.php?mode=searchuser', + )); + } else { + $template->assign_vars(array( + 'TPL_SELECT_GROUP' => true, + 'S_GROUP_SELECT' => get_select('groups'), + )); + } - 'T_USER_OR_GROUPNAME' => $lang['GROUP_NAME'], - 'USER_LEVEL' => false, - 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_GROUP'], - 'T_AUTH_EXPLAIN' => $lang['GROUP_AUTH_EXPLAIN'], - 'USER_OR_GROUPNAME' => htmlCHR($group_data['group_name']), - 'S_COLUMN_SPAN' => $s_column_span, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); -} -else -{ - // Select a user/group - if ($mode == 'user') - { - $template->assign_vars(array( - 'TPL_SELECT_USER' => true, - 'U_SEARCH_USER' => BB_ROOT ."search.php?mode=searchuser", - )); - } - else - { - $template->assign_vars(array( - 'TPL_SELECT_GROUP' => true, - 'S_GROUP_SELECT' => get_select('groups'), - )); - } + $s_hidden_fields = ''; - $s_hidden_fields = ''; - - $template->assign_vars(array( - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); + $template->assign_vars(array( + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); } $template->assign_vars(array( - 'YES_SIGN' => $yes_sign, - 'NO_SIGN' => $no_sign, - 'T_MOD_YES' => $lang['MODERATOR'], - 'T_MOD_NO' => $lang['NO'], - 'S_AUTH_ACTION' => "admin_ug_auth.php", - 'SELECTED_CAT' => !empty($_REQUEST['c']) ? $_REQUEST['c'] : '', - 'U_ALL_FORUMS' => !empty($base_url) ? "$base_url&c=all" : '', + 'YES_SIGN' => $yes_sign, + 'NO_SIGN' => $no_sign, + 'S_AUTH_ACTION' => 'admin_ug_auth.php', + 'SELECTED_CAT' => !empty($_REQUEST[POST_CAT_URL]) ? $_REQUEST[POST_CAT_URL] : '', + 'U_ALL_FORUMS' => !empty($base_url) ? "$base_url&" . POST_CAT_URL . "=all" : '', )); -print_page('admin_ug_auth.tpl', 'admin'); \ No newline at end of file +print_page('admin_ug_auth.tpl', 'admin'); diff --git a/admin/admin_user_ban.php b/admin/admin_user_ban.php index 72cbac3ff..af4c31b81 100644 --- a/admin/admin_user_ban.php +++ b/admin/admin_user_ban.php @@ -1,362 +1,81 @@ sql_query($sql))) - { - bb_die('Could not obtain banlist information'); - } - - $current_banlist = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); - - $kill_session_sql = ''; - for ($i = 0; $i < count($user_list); $i++) - { - $in_banlist = false; - for ($j = 0; $j < count($current_banlist); $j++) - { - if ($user_list[$i] == $current_banlist[$j]['ban_userid']) - { - $in_banlist = true; - } - } - - if (!$in_banlist) - { - $kill_session_sql .= ( ( $kill_session_sql != '' ) ? ' OR ' : '' ) . "session_user_id = " . $user_list[$i]; - - $sql = "INSERT INTO " . BB_BANLIST . " (ban_userid) VALUES (" . $user_list[$i] . ")"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not insert ban_userid info into database'); - } - } - } - - for ($i = 0; $i < count($ip_list); $i++) - { - $in_banlist = false; - for ($j = 0; $j < count($current_banlist); $j++) - { - if ($ip_list[$i] == $current_banlist[$j]['ban_ip']) - { - $in_banlist = true; - } - } - - if (!$in_banlist) - { - if (preg_match('/(ff\.)|(\.ff)/is', chunk_split($ip_list[$i], 2, '.'))) - { - $kill_ip_sql = "session_ip LIKE '" . str_replace('.', '', preg_replace('/(ff\.)|(\.ff)/is', '%', chunk_split($ip_list[$i], 2, "."))) . "'"; - } - else - { - $kill_ip_sql = "session_ip = '" . $ip_list[$i] . "'"; - } - - $kill_session_sql .= ( ( $kill_session_sql != '' ) ? ' OR ' : '' ) . $kill_ip_sql; - - $sql = "INSERT INTO " . BB_BANLIST . " (ban_ip) VALUES ('" . $ip_list[$i] . "')"; - if ( !DB()->sql_query($sql) ) - { - bb_die('Could not insert ban_ip info into database'); - } - } - } - - // Now we'll delete all entries from the session table - if ($kill_session_sql != '') - { - $sql = "DELETE FROM " . BB_SESSIONS . " WHERE $kill_session_sql"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not delete banned sessions from database'); - } - } - - for ($i = 0; $i < count($email_list); $i++) - { - $in_banlist = false; - for ($j = 0; $j < count($current_banlist); $j++) - { - if ($email_list[$i] == $current_banlist[$j]['ban_email']) - { - $in_banlist = true; - } - } - - if (!$in_banlist) - { - $sql = "INSERT INTO " . BB_BANLIST . " (ban_email) VALUES ('" . DB()->escape($email_list[$i]) . "')"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not insert ban_email info into database'); - } - } - } - - $where_sql = ''; - - if (isset($_POST['unban_user'])) - { - $user_list = $_POST['unban_user']; - - for ($i = 0; $i < count($user_list); $i++) - { - if ($user_list[$i] != -1) - { - $where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . intval($user_list[$i]); - } - } - } - - if (isset($_POST['unban_ip'])) - { - $ip_list = $_POST['unban_ip']; - - for ($i = 0; $i < count($ip_list); $i++) - { - if ($ip_list[$i] != -1) - { - $where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . DB()->escape($ip_list[$i]); - } - } - } - - if (isset($_POST['unban_email'])) - { - $email_list = $_POST['unban_email']; - - for ($i = 0; $i < count($email_list); $i++) - { - if ($email_list[$i] != -1) - { - $where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . DB()->escape($email_list[$i]); - } - } - } - - if ($where_sql != '') - { - $sql = "DELETE FROM " . BB_BANLIST . " WHERE ban_id IN ($where_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not delete ban info from database'); - } - } - - bb_die($lang['BAN_UPDATE_SUCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_BANADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); -} -else -{ - $template->assign_vars(array( - 'S_BANLIST_ACTION' => 'admin_user_ban.php', - )); - - $userban_count = 0; - $ipban_count = 0; - $emailban_count = 0; - - $sql = "SELECT b.ban_id, u.user_id, u.username - FROM " . BB_BANLIST . " b, " . BB_USERS . " u - WHERE u.user_id = b.ban_userid - AND b.ban_userid <> 0 - AND u.user_id <> " . GUEST_UID . " - ORDER BY u.username ASC"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select current user_id ban list'); - } - - $user_list = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); - - $select_userlist = ''; - for ($i = 0; $i < count($user_list); $i++) - { - $select_userlist .= ''; - $userban_count++; - } - - if ($select_userlist == '') - { - $select_userlist = ''; - } - - $select_userlist = ''; - - $sql = "SELECT ban_id, ban_ip, ban_email FROM ". BB_BANLIST ." ORDER BY ban_ip"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select current ip ban list'); - } - - $banlist = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); - - $select_iplist = ''; - $select_emaillist = ''; - - for ($i = 0; $i < count($banlist); $i++) - { - $ban_id = $banlist[$i]['ban_id']; - - if (!empty($banlist[$i]['ban_ip'])) - { - $ban_ip = str_replace('255', '*', decode_ip($banlist[$i]['ban_ip'])); - $select_iplist .= ''; - $ipban_count++; - } - else if (!empty($banlist[$i]['ban_email'])) - { - $ban_email = $banlist[$i]['ban_email']; - $select_emaillist .= ''; - $emailban_count++; - } - } - - if ($select_iplist == '') - { - $select_iplist = ''; - } - - if ($select_emaillist == '') - { - $select_emaillist = ''; - } - - $select_iplist = ''; - $select_emaillist = ''; - - $template->assign_vars(array( - 'U_SEARCH_USER' => './../search.php?mode=searchuser', - 'S_UNBAN_USERLIST_SELECT' => $select_userlist, - 'S_UNBAN_IPLIST_SELECT' => $select_iplist, - 'S_UNBAN_EMAILLIST_SELECT' => $select_emaillist, - 'S_BAN_ACTION' => 'admin_user_ban.php', - )); +if (!empty($setmodules)) { + $module['USERS']['BAN_MANAGEMENT'] = basename(__FILE__); + return; } -print_page('admin_user_ban.tpl', 'admin'); \ No newline at end of file +require __DIR__ . '/pagestart.php'; + +$submit = isset($_POST['submit']); + +// Check for demo mode +if (IN_DEMO_MODE && $submit) { + bb_die($lang['CANT_EDIT_IN_DEMO_MODE']); +} + +if ($submit) { + // Ban action + if (!empty($_POST['username'])) { + if (!$this_userdata = get_userdata($_POST['username'], true)) { + bb_die($lang['NO_USER_ID_SPECIFIED'] . '

' . sprintf($lang['CLICK_RETURN_BANADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } + + if (!getBanInfo((int)$this_userdata['user_id'])) { + $sql = 'INSERT INTO ' . BB_BANLIST . ' (ban_userid) VALUES (' . $this_userdata['user_id'] . ')'; + if (!DB()->sql_query($sql)) { + bb_die('Could not insert ban_userid info into database'); + } + } + } + + // Unban action + $where_sql = ''; + + if (!empty($_POST['unban_user'])) { + $user_list = $_POST['unban_user']; + + for ($i = 0, $iMax = count($user_list); $i < $iMax; $i++) { + if ($user_list[$i] != -1) { + $where_sql .= (($where_sql != '') ? ', ' : '') . (int)$user_list[$i]; + } + } + + if ($where_sql != '') { + $sql = 'DELETE FROM ' . BB_BANLIST . " WHERE ban_id IN ($where_sql)"; + if (!DB()->sql_query($sql)) { + bb_die('Could not delete ban info from database'); + } + } + } + + $datastore->update('ban_list'); + bb_die($lang['BAN_UPDATE_SUCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_BANADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); +} else { + $template->assign_vars(['S_BANLIST_ACTION' => 'admin_user_ban.php']); + + $select_userlist = ''; + foreach (getBanInfo() as $ban) { + $select_userlist .= ''; + } + + if ($select_userlist == '') { + $select_userlist = ''; + } + $select_userlist = ''; + + $template->assign_vars([ + 'U_SEARCH_USER' => './../search.php?mode=searchuser', + 'S_UNBAN_USERLIST_SELECT' => $select_userlist, + 'S_BAN_ACTION' => 'admin_user_ban.php' + ]); +} + +print_page('admin_user_ban.tpl', 'admin'); diff --git a/admin/admin_user_search.php b/admin/admin_user_search.php index 31d3465ad..d383e5a29 100644 --- a/admin/admin_user_search.php +++ b/admin/admin_user_search.php @@ -1,1052 +1,937 @@ sql_query($sql)) - { - bb_die('Could not select group data #1'); - } - - $group_list = ''; - - if (DB()->num_rows($result) != 0) - { - $template->assign_block_vars('groups_exist', array()); - - while ($row = DB()->sql_fetchrow($result)) - { - $group_list .= ''; - } - } - - $sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_special = 1 ORDER BY rank_title"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not obtain ranks data'); - } - $rank_select_box = ''; - if (DB()->num_rows($result) != 0) - { - $template->assign_block_vars('ranks_exist', array()); - while( $row = DB()->sql_fetchrow($result) ) - { - $rank = $row['rank_title']; - $rank_id = $row['rank_id']; - $rank_select_box .= ''; - } - } - - $language_list = language_select('', 'language_type'); - $timezone_list = tz_select('', 'timezone_type'); - - $sql = "SELECT f.forum_id, f.forum_name, f.forum_parent, c.cat_id, c.cat_title - FROM ( ". BB_FORUMS ." AS f INNER JOIN ". BB_CATEGORIES ." AS c ON c.cat_id = f.cat_id ) - ORDER BY c.cat_order, f.forum_order ASC"; - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select forum data'); - } - - $forums = array(); - - if (DB()->num_rows($result) != 0) - { - $template->assign_block_vars('forums_exist', array()); - - $last_cat_id = -1; - $forums_list = ''; - - while ($row = DB()->sql_fetchrow($result)) - { - if ($row['cat_id'] != $last_cat_id) - { - $forums_list .= ''; - $last_cat_id = $row['cat_id']; - } - - $forums_list .= ''; - } - } - - $lastvisited = array(1, 7, 14, 30, 60, 120, 365, 500, 730, 1000); - $lastvisited_list = ''; - - foreach ($lastvisited as $days) - { - $lastvisited_list .= ''; - } - - $template->assign_vars(array( - 'TPL_ADMIN_USER_SEARCH_MAIN' => true, - - 'YEAR' => date("Y"), - 'MONTH' => date("m"), - 'DAY' => date("d"), - 'GROUP_LIST' => $group_list, - 'RANK_SELECT_BOX' => $rank_select_box, - 'LANGUAGE_LIST' => $language_list, - 'TIMEZONE_LIST' => $timezone_list, - 'FORUMS_LIST' => $forums_list, - 'LASTVISITED_LIST' => $lastvisited_list, - - 'S_SEARCH_ACTION' => 'admin_user_search.php', - )); -} -else -{ - $mode = ''; - - // validate mode - if (isset($_REQUEST['search_username'])) - { - $mode = 'search_username'; - } - elseif (isset($_REQUEST['search_email'])) - { - $mode = 'search_email'; - } - elseif (isset($_REQUEST['search_ip'])) - { - $mode = 'search_ip'; - } - elseif (isset($_REQUEST['search_joindate'])) - { - $mode = 'search_joindate'; - } - elseif (isset($_REQUEST['search_group'])) - { - $mode = 'search_group'; - } - elseif (isset($_REQUEST['search_rank'])) - { - $mode = 'search_rank'; - } - elseif (isset($_REQUEST['search_postcount'])) - { - $mode = 'search_postcount'; - } - elseif (isset($_REQUEST['search_userfield'])) - { - $mode = 'search_userfield'; - } - elseif (isset($_REQUEST['search_lastvisited'])) - { - $mode = 'search_lastvisited'; - } - elseif (isset($_REQUEST['search_language'])) - { - $mode = 'search_language'; - } - elseif (isset($_REQUEST['search_timezone'])) - { - $mode = 'search_timezone'; - } - elseif (isset($_REQUEST['search_moderators'])) - { - $mode = 'search_moderators'; - } - elseif (isset($_REQUEST['search_misc'])) - { - $mode = 'search_misc'; - } - - // validate fields (that they exist) - switch ($mode) - { - case 'search_username': - $username = $_REQUEST['username']; - if (!$username) bb_die($lang['SEARCH_INVALID_USERNAME']); - break; - - case 'search_email': - $email = $_REQUEST['email']; - if (!$email) bb_die($lang['SEARCH_INVALID_EMAIL']); - break; - - case 'search_ip': - $ip_address = $_REQUEST['ip_address']; - if (!$ip_address) bb_die($lang['SEARCH_INVALID_IP']); - break; - - case 'search_joindate': - $date_type = $_REQUEST['date_type']; - $date_day = $_REQUEST['date_day']; - $date_month = $_REQUEST['date_month']; - $date_year = $_REQUEST['date_year']; - if (!($date_type || $date_day || $date_month || $date_year)) bb_die($lang['SEARCH_INVALID_DATE']); - break; - - case 'search_group': - $group_id = $_REQUEST['group_id']; - if (!$group_id) bb_die($lang['SEARCH_INVALID_GROUP']); - break; - - case 'search_rank': - $rank_id = $_REQUEST['rank_id']; - if (!$rank_id) bb_die($lang['SEARCH_INVALID_RANK']); - break; - - case 'search_postcount': - $postcount_type = $_REQUEST['postcount_type']; - $postcount_value = $_REQUEST['postcount_value']; - if (!$postcount_type || (!$postcount_value && $postcount_value != 0)) bb_die($lang['SEARCH_INVALID_POSTCOUNT']); - break; - - case 'search_userfield': - $userfield_type = $_REQUEST['userfield_type']; - $userfield_value = $_REQUEST['userfield_value']; - if (!$userfield_type || !$userfield_value) bb_die($lang['SEARCH_INVALID_USERFIELD']); - break; - - case 'search_lastvisited': - $lastvisited_days = $_REQUEST['lastvisited_days']; - $lastvisited_type = $_REQUEST['lastvisited_type']; - if (!$lastvisited_days || !$lastvisited_type) bb_die($lang['SEARCH_INVALID_LASTVISITED']); - break; - - case 'search_language': - $language_type = $_REQUEST['language_type']; - if (!$language_type) bb_die($lang['SEARCH_INVALID_LANGUAGE']); - break; - - case 'search_timezone': - $timezone_type = $_REQUEST['timezone_type']; - if (!$timezone_type && $timezone_type != 0) bb_die($lang['SEARCH_INVALID_TIMEZONE']); - break; - - case 'search_moderators': - $moderators_forum = $_REQUEST['moderators_forum']; - if (!$moderators_forum) bb_die($lang['SEARCH_INVALID_MODERATORS']); - break; - - case 'search_misc': - $misc = $_REQUEST['misc']; - if (!$misc) bb_die($lang['SEARCH_INVALID']); - break; - - default: - bb_die('Invalid mode'); - } - - $base_url = 'admin_user_search.php?dosearch=true'; - - $select_sql = "SELECT u.user_id, u.username, u.user_rank, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit FROM ". BB_USERS ." AS u"; - - $lower_b = 'LOWER('; - $lower_e = ')'; - - // validate data & prepare sql - switch($mode) - { - case 'search_username': - $base_url .= '&search_username=true&username='.rawurlencode(stripslashes($username)); - - $text = sprintf($lang['SEARCH_FOR_USERNAME'], strip_tags(htmlspecialchars(stripslashes($username)))); - - $username = preg_replace('/\*/', '%', trim(strip_tags(strtolower($username)))); - - if (strstr($username, '%')) - { - $op = 'LIKE'; - } - else - { - $op = '='; - } - - if ($username == '') bb_die($lang['SEARCH_INVALID_USERNAME']); - - $total_sql .= "SELECT COUNT(user_id) AS total FROM ".BB_USERS." WHERE {$lower_b}username{$lower_e} $op '".DB()->escape($username)."' AND user_id <> ".GUEST_UID; - $select_sql .= " WHERE {$lower_b}u.username{$lower_e} $op '".DB()->escape($username)."' AND u.user_id <> ".GUEST_UID; - break; - - case 'search_email': - $base_url .= '&search_email=true&email='.rawurlencode(stripslashes($email)); - - $text = sprintf($lang['SEARCH_FOR_EMAIL'], strip_tags(htmlspecialchars(stripslashes($email)))); - - $email = preg_replace('/\*/', '%', trim(strip_tags(strtolower($email)))); - - if (strstr($email, '%')) - { - $op = 'LIKE'; - } - else - { - $op = '='; - } - - if ($email == '') bb_die($lang['SEARCH_INVALID_EMAIL']); - - $total_sql .= "SELECT COUNT(user_id) AS total FROM ".BB_USERS." WHERE {$lower_b}user_email{$lower_e} $op '".DB()->escape($email)."' AND user_id <> ".GUEST_UID; - $select_sql .= " WHERE {$lower_b}u.user_email{$lower_e} $op '".DB()->escape($email)."' AND u.user_id <> ".GUEST_UID; - break; - - case 'search_ip': - $base_url .= '&search_ip=true&ip_address='.rawurlencode(stripslashes($ip_address)); - - $ip_address = trim($ip_address); - - $text = sprintf($lang['SEARCH_FOR_IP'], strip_tags(htmlspecialchars(stripslashes($ip_address)))); - - unset($users); - $users = array(); - - // Let's see if they entered a full valid IPv4 address - if (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) - { - $ip = encode_ip($ip_address); - $users[] = $ip; - } - elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){0,2}\.\*/', $ip_address)) - { - $ip_split = explode('.', $ip_address); - switch (count($ip_split)) - { - case 4: - $users[] = encode_ip($ip_split[0].".".$ip_split[1].".".$ip_split[2].".255"); - break; - case 3: - $users[] = encode_ip($ip_split[0].".".$ip_split[1].".255.255"); - break; - case 2: - $users[] = encode_ip($ip_split[0].".255.255.255"); - break; - } - } - elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}(\s)*-(\s)*([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) - { - $range = preg_split('/[-\s]+/', $ip_address); - $start_range = explode('.', $range[0]); - $end_range = explode('.', $range[1]); - if (($start_range[0].$start_range[1].$start_range[2] != $end_range[0].$end_range[1].$end_range[2]) || ($start_range[3] > $end_range[3])) bb_die($lang['SEARCH_INVALID_IP']); - for ($i = $start_range[3]; $i <= $end_range[3]; $i++) - { - $users[] = encode_ip($start_range[0].".".$start_range[1 ].".".$start_range[2].".".$i); - } - } - else - { - bb_die($lang['SEARCH_INVALID_IP']); - } - - $ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = ''; - - foreach ($users as $address) - { - if (preg_match('/(ff){1,3}$/i', $address)) - { - if (preg_match('/[0-9a-f]{2}ffffff/i', $address)) - { - $ip_start = substr($address, 0, 2); - } - elseif (preg_match('/[0-9a-f]{4}ffff/i', $address)) - { - $ip_start = substr($address, 0, 4); - } - elseif (preg_match('/[0-9a-f]{6}ff/i', $address)) - { - $ip_start = substr($address, 0, 6); - } - $ip_like_sql_flylast = $ip_like_sql . ( $ip_like_sql != '' ) ? " OR user_last_ip LIKE '".$ip_start."%'" : "user_last_ip LIKE '".$ip_start."%'"; - $ip_like_sql_flyreg = $ip_like_sql . ( $ip_like_sql != '' ) ? " OR user_reg_ip LIKE '".$ip_start."%'" : "user_reg_ip LIKE '".$ip_start."%'"; - $ip_like_sql .= ( $ip_like_sql != '' ) ? " OR poster_ip LIKE '".$ip_start."%'" : "poster_ip LIKE '".$ip_start."%'"; - } - else - { - $ip_in_sql .= ( $ip_in_sql == '' ) ? "'$address'" : ", '$address'"; - } - } - - $where_sql = ''; - $where_sql .= ( $ip_in_sql != '' ) ? "poster_ip IN ($ip_in_sql)": ""; - $where_sql .= ( $ip_like_sql != '' ) ? ( $where_sql != "" ) ? " OR $ip_like_sql" : "$ip_like_sql": ""; - - if (!$where_sql) bb_die('invalid request'); - - // start search - $no_result_search = false; - $ip_users_sql = ''; - $sql = "SELECT poster_id FROM ".BB_POSTS." WHERE poster_id <> ".GUEST_UID." AND ($where_sql) GROUP BY poster_id"; - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not count users #1'); - } - - if (DB()->num_rows($result) == 0) - { - $no_result_search = true; - } - else - { - $total_pages['total'] = DB()->num_rows($result); - $total_sql = NULL; - $ip_users_sql = ''; - while($row = DB()->sql_fetchrow($result)) - { - $ip_users_sql .= ( $ip_users_sql == '' ) ? $row['poster_id'] : ', '.$row['poster_id']; - } - } - $where_sql = ''; - $where_sql .= ( $ip_in_sql != '' ) ? "user_last_ip IN ($ip_in_sql)": ""; - $where_sql .= ( $ip_like_sql_flylast != '' ) ? ( $where_sql != "" ) ? " OR $ip_like_sql_flylast" : "$ip_like_sql_flylast": ""; - $sql = "SELECT user_id FROM ".BB_USERS." WHERE user_id <> ".GUEST_UID." AND ($where_sql) GROUP BY user_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not count users #2'); - } - if (DB()->num_rows($result) != 0) - { - if ($no_result_search == true) $no_result_search = false; - $total_pages['total'] = DB()->num_rows($result); - $total_sql = NULL; - while ($row = DB()->sql_fetchrow($result)) - { - $ip_users_sql .= ( $ip_users_sql == '' ) ? $row['user_id'] : ', '.$row['user_id']; - } - } - $where_sql = ''; - $where_sql .= ( $ip_in_sql != '' ) ? "user_reg_ip IN ($ip_in_sql)": ""; - $where_sql .= ( $ip_like_sql_flyreg != '' ) ? ( $where_sql != "" ) ? " OR $ip_like_sql_flyreg" : "$ip_like_sql_flyreg": ""; - $sql = "SELECT user_id FROM ".BB_USERS." WHERE user_id <> ".GUEST_UID." AND ($where_sql) GROUP BY user_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not count users #3'); - } - if (DB()->num_rows($result) != 0) - { - if ($no_result_search == true) $no_result_search = false; - $total_pages['total'] = DB()->num_rows($result); - $total_sql = NULL; - while ($row = DB()->sql_fetchrow($result)) - { - $ip_users_sql .= ( $ip_users_sql == '' ) ? $row['user_id'] : ', '.$row['user_id']; - } - } - if ($no_result_search == true) - { - bb_die($lang['SEARCH_NO_RESULTS']); - } - - $select_sql .= " WHERE u.user_id IN ($ip_users_sql)"; - break; - - case 'search_joindate': - $base_url .= '&search_joindate=true&date_type='. rawurlencode($date_type) .'&date_day='. rawurlencode($date_day) .'&date_month='. rawurlencode($date_month) .'&date_year='. rawurlencode(stripslashes($date_year)); - - $date_type = trim(strtolower($date_type)); - - if ($date_type != 'before' && $date_type != 'after') - { - bb_die($lang['SEARCH_INVALID_DATE']); - } - - $date_day = intval($date_day); - - if (!preg_match('/^([1-9]|[0-2][0-9]|3[0-1])$/', $date_day)) - { - bb_die($lang['SEARCH_INVALID_DAY']); - } - - $date_month = intval($date_month); - - if (!preg_match('/^(0?[1-9]|1[0-2])$/', $date_month)) - { - bb_die($lang['SEARCH_INVALID_MONTH']); - } - - $date_year = intval($date_year); - - if (!preg_match('/^(20[0-9]{2}|19[0-9]{2})$/', $date_year)) - { - bb_die($lang['SEARCH_INVALID_YEAR']); - } - - $text = sprintf($lang['SEARCH_FOR_DATE'], strip_tags(htmlspecialchars(stripslashes($date_type))), $date_year, $date_month, $date_day); - - $time = mktime(0,0,0,$date_month, $date_day, $date_year); - - if ($date_type == 'before') - { - $arg = '<'; - } - else - { - $arg = '>'; - } - - $total_sql .= "SELECT COUNT(user_id) AS total FROM ".BB_USERS." WHERE user_regdate $arg $time AND user_id <> ".GUEST_UID; - $select_sql .= " WHERE u.user_regdate $arg $time AND u.user_id <> ".GUEST_UID; - break; - - case 'search_group': - $group_id = intval($group_id); - - $base_url .= '&search_group=true&group_id='. rawurlencode($group_id); - - if (!$group_id) - { - bb_die($lang['SEARCH_INVALID_GROUP']); - } - - $sql = "SELECT group_name FROM ".BB_GROUPS." WHERE group_id = $group_id AND group_single_user = 0"; - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select group data #2'); - } - - if (DB()->num_rows($result)==0) - { - bb_die($lang['SEARCH_INVALID_GROUP']); - } - - $group_name = DB()->sql_fetchrow($result); - - $text = sprintf($lang['SEARCH_FOR_GROUP'], strip_tags(htmlspecialchars($group_name['group_name']))); - - $total_sql .= "SELECT COUNT(u.user_id) AS total - FROM ".BB_USERS." AS u, ".BB_USER_GROUP." AS ug + ORDER BY group_name ASC'; + + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select group data #1'); + } + + $group_list = ''; + + if (DB()->num_rows($result) != 0) { + $template->assign_block_vars('groups_exist', []); + + while ($row = DB()->sql_fetchrow($result)) { + $group_list .= ''; + } + } + + $sql = 'SELECT * FROM ' . BB_RANKS . ' ORDER BY rank_title'; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain ranks data'); + } + $rank_select_box = ''; + if (DB()->num_rows($result) != 0) { + $template->assign_block_vars('ranks_exist', []); + while ($row = DB()->sql_fetchrow($result)) { + $rank = $row['rank_title']; + $rank_id = $row['rank_id']; + $rank_select_box .= ''; + } + } + + $language_list = \TorrentPier\Legacy\Common\Select::language('', 'language_type'); + $timezone_list = \TorrentPier\Legacy\Common\Select::timezone('', 'timezone_type'); + + $sql = 'SELECT f.forum_id, f.forum_name, f.forum_parent, c.cat_id, c.cat_title + FROM ( ' . BB_FORUMS . ' AS f INNER JOIN ' . BB_CATEGORIES . ' AS c ON c.cat_id = f.cat_id ) + ORDER BY c.cat_order, f.forum_order ASC'; + + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select forum data'); + } + + $forums = []; + $last_cat_id = -1; + $forums_list = ''; + + if (DB()->num_rows($result) != 0) { + $template->assign_block_vars('forums_exist', []); + + while ($row = DB()->sql_fetchrow($result)) { + if ($row['cat_id'] != $last_cat_id) { + $forums_list .= ''; + $last_cat_id = $row['cat_id']; + } + + $forums_list .= ''; + } + } + + $lastvisited = [1, 7, 14, 30, 60, 120, 365, 500, 730, 1000]; + $lastvisited_list = ''; + + foreach ($lastvisited as $days) { + $lastvisited_list .= ''; + } + + $template->assign_vars([ + 'TPL_ADMIN_USER_SEARCH_MAIN' => true, + + 'YEAR' => date('Y'), + 'MONTH' => date('m'), + 'DAY' => date('d'), + 'GROUP_LIST' => $group_list, + 'RANK_SELECT_BOX' => $rank_select_box, + 'LANGUAGE_LIST' => $language_list, + 'TIMEZONE_LIST' => $timezone_list, + 'FORUMS_LIST' => $forums_list, + 'LASTVISITED_LIST' => $lastvisited_list, + + 'U_SEARCH_USER' => BB_ROOT . 'search.php?mode=searchuser', + 'S_SEARCH_ACTION' => 'admin_user_search.php' + ]); +} else { + $mode = ''; + + // validate mode + if (isset($_REQUEST['search_username'])) { + $mode = 'search_username'; + } elseif (isset($_REQUEST['search_email'])) { + $mode = 'search_email'; + } elseif (isset($_REQUEST['search_ip'])) { + $mode = 'search_ip'; + } elseif (isset($_REQUEST['search_joindate'])) { + $mode = 'search_joindate'; + } elseif (isset($_REQUEST['search_group'])) { + $mode = 'search_group'; + } elseif (isset($_REQUEST['search_rank'])) { + $mode = 'search_rank'; + } elseif (isset($_REQUEST['search_postcount'])) { + $mode = 'search_postcount'; + } elseif (isset($_REQUEST['search_userfield'])) { + $mode = 'search_userfield'; + } elseif (isset($_REQUEST['search_lastvisited'])) { + $mode = 'search_lastvisited'; + } elseif (isset($_REQUEST['search_language'])) { + $mode = 'search_language'; + } elseif (isset($_REQUEST['search_timezone'])) { + $mode = 'search_timezone'; + } elseif (isset($_REQUEST['search_moderators'])) { + $mode = 'search_moderators'; + } elseif (isset($_REQUEST['search_misc'])) { + $mode = 'search_misc'; + } + + // validate fields (that they exist) + switch ($mode) { + case 'search_username': + $username = $_REQUEST['username']; + if (!$username) { + bb_die($lang['SEARCH_INVALID_USERNAME']); + } + break; + + case 'search_email': + $email = $_REQUEST['email']; + if (!$email) { + bb_die($lang['SEARCH_INVALID_EMAIL']); + } + break; + + case 'search_ip': + $ip_address = $_REQUEST['ip_address']; + if (!$ip_address) { + bb_die($lang['SEARCH_INVALID_IP']); + } + break; + + case 'search_joindate': + $date_type = $_REQUEST['date_type']; + $date_day = $_REQUEST['date_day']; + $date_month = $_REQUEST['date_month']; + $date_year = $_REQUEST['date_year']; + if (!($date_type || $date_day || $date_month || $date_year)) { + bb_die($lang['SEARCH_INVALID_DATE']); + } + break; + + case 'search_group': + $group_id = $_REQUEST['group_id']; + if (!$group_id) { + bb_die($lang['SEARCH_INVALID_GROUP']); + } + break; + + case 'search_rank': + $rank_id = $_REQUEST['rank_id']; + if (!$rank_id) { + bb_die($lang['SEARCH_INVALID_RANK']); + } + break; + + case 'search_postcount': + $postcount_type = $_REQUEST['postcount_type']; + $postcount_value = $_REQUEST['postcount_value']; + if (!$postcount_type || (!$postcount_value && $postcount_value != 0)) { + bb_die($lang['SEARCH_INVALID_POSTCOUNT']); + } + break; + + case 'search_userfield': + $userfield_type = $_REQUEST['userfield_type']; + $userfield_value = $_REQUEST['userfield_value']; + if (!$userfield_type || !$userfield_value) { + bb_die($lang['SEARCH_INVALID_USERFIELD']); + } + break; + + case 'search_lastvisited': + $lastvisited_days = $_REQUEST['lastvisited_days']; + $lastvisited_type = $_REQUEST['lastvisited_type']; + if (!$lastvisited_days || !$lastvisited_type) { + bb_die($lang['SEARCH_INVALID_LASTVISITED']); + } + break; + + case 'search_language': + $language_type = $_REQUEST['language_type']; + if (!$language_type) { + bb_die($lang['SEARCH_INVALID_LANGUAGE']); + } + break; + + case 'search_timezone': + $timezone_type = $_REQUEST['timezone_type']; + if (!$timezone_type && $timezone_type != 0) { + bb_die($lang['SEARCH_INVALID_TIMEZONE']); + } + break; + + case 'search_moderators': + $moderators_forum = $_REQUEST['moderators_forum']; + if (!$moderators_forum) { + bb_die($lang['SEARCH_INVALID_MODERATORS']); + } + break; + + case 'search_misc': + $misc = $_REQUEST['misc']; + if (!$misc) { + bb_die($lang['SEARCH_INVALID']); + } + break; + + default: + bb_die('Invalid mode'); + } + + $base_url = 'admin_user_search.php?dosearch=true'; + + $select_sql = 'SELECT u.user_id, u.username, u.user_rank, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit FROM ' . BB_USERS . ' AS u'; + + $lower_b = 'LOWER('; + $lower_e = ')'; + + // validate data & prepare sql + switch ($mode) { + case 'search_username': + $base_url .= '&search_username=true&username=' . rawurlencode(stripslashes($username)); + + $text = sprintf($lang['SEARCH_FOR_USERNAME'], strip_tags(htmlspecialchars(stripslashes($username)))); + + $username = str_replace('*', '%', trim(strip_tags(strtolower($username)))); + if (str_contains($username, '%')) { + $op = 'LIKE'; + } else { + $op = '='; + } + + if ($username == '') { + bb_die($lang['SEARCH_INVALID_USERNAME']); + } + + $total_sql .= 'SELECT COUNT(user_id) AS total FROM ' . BB_USERS . " WHERE {$lower_b}username{$lower_e} $op '" . DB()->escape($username) . "' AND user_id <> " . GUEST_UID; + $select_sql .= " WHERE {$lower_b}u.username{$lower_e} $op '" . DB()->escape($username) . "' AND u.user_id <> " . GUEST_UID; + break; + + case 'search_email': + $base_url .= '&search_email=true&email=' . rawurlencode(stripslashes($email)); + + $text = sprintf($lang['SEARCH_FOR_EMAIL'], strip_tags(htmlspecialchars(stripslashes($email)))); + + $email = str_replace('*', '%', trim(strip_tags(strtolower($email)))); + if (str_contains($email, '%')) { + $op = 'LIKE'; + } else { + $op = '='; + } + + if ($email == '') { + bb_die($lang['SEARCH_INVALID_EMAIL']); + } + + $total_sql .= 'SELECT COUNT(user_id) AS total FROM ' . BB_USERS . " WHERE {$lower_b}user_email{$lower_e} $op '" . DB()->escape($email) . "' AND user_id <> " . GUEST_UID; + $select_sql .= " WHERE {$lower_b}u.user_email{$lower_e} $op '" . DB()->escape($email) . "' AND u.user_id <> " . GUEST_UID; + break; + + case 'search_ip': + $base_url .= '&search_ip=true&ip_address=' . rawurlencode(stripslashes($ip_address)); + + $ip_address = trim($ip_address); + + $text = sprintf($lang['SEARCH_FOR_IP'], strip_tags(htmlspecialchars(stripslashes($ip_address)))); + + unset($users); + $users = []; + + if (\TorrentPier\Helpers\IPHelper::isValid($ip_address)) { + $ip = \TorrentPier\Helpers\IPHelper::ip2long($ip_address); + $users[] = $ip; + } else { + bb_die($lang['SEARCH_INVALID_IP']); + } + + $ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = ''; + + foreach ($users as $address) { + $ip_in_sql .= ($ip_in_sql == '') ? "'$address'" : ", '$address'"; + } + + $where_sql = ''; + $where_sql .= ($ip_in_sql != '') ? "poster_ip IN ($ip_in_sql)" : ''; + $where_sql .= ($ip_like_sql != '') ? ($where_sql != '') ? " OR $ip_like_sql" : (string)$ip_like_sql : ''; + + if (!$where_sql) { + bb_die('invalid request'); + } + + // start search + $no_result_search = false; + $ip_users_sql = ''; + $sql = 'SELECT poster_id FROM ' . BB_POSTS . ' WHERE poster_id <> ' . GUEST_UID . " AND ($where_sql) GROUP BY poster_id"; + + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not count users #1'); + } + + if (DB()->num_rows($result) == 0) { + $no_result_search = true; + } else { + $total_pages['total'] = DB()->num_rows($result); + $total_sql = null; + $ip_users_sql = ''; + while ($row = DB()->sql_fetchrow($result)) { + $ip_users_sql .= ($ip_users_sql == '') ? $row['poster_id'] : ', ' . $row['poster_id']; + } + } + $where_sql = ''; + $where_sql .= ($ip_in_sql != '') ? "user_last_ip IN ($ip_in_sql)" : ''; + $where_sql .= ($ip_like_sql_flylast != '') ? ($where_sql != '') ? " OR $ip_like_sql_flylast" : (string)$ip_like_sql_flylast : ''; + $sql = 'SELECT user_id FROM ' . BB_USERS . ' WHERE user_id <> ' . GUEST_UID . " AND ($where_sql) GROUP BY user_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not count users #2'); + } + if (DB()->num_rows($result) != 0) { + if ($no_result_search == true) { + $no_result_search = false; + } + $total_pages['total'] = DB()->num_rows($result); + $total_sql = null; + while ($row = DB()->sql_fetchrow($result)) { + $ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id']; + } + } + $where_sql = ''; + $where_sql .= ($ip_in_sql != '') ? "user_reg_ip IN ($ip_in_sql)" : ''; + $where_sql .= ($ip_like_sql_flyreg != '') ? ($where_sql != '') ? " OR $ip_like_sql_flyreg" : (string)$ip_like_sql_flyreg : ''; + $sql = 'SELECT user_id FROM ' . BB_USERS . ' WHERE user_id <> ' . GUEST_UID . " AND ($where_sql) GROUP BY user_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not count users #3'); + } + if (DB()->num_rows($result) != 0) { + if ($no_result_search == true) { + $no_result_search = false; + } + $total_pages['total'] = DB()->num_rows($result); + $total_sql = null; + while ($row = DB()->sql_fetchrow($result)) { + $ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id']; + } + } + if ($no_result_search == true) { + bb_die($lang['SEARCH_NO_RESULTS']); + } + + $select_sql .= " WHERE u.user_id IN ($ip_users_sql)"; + break; + + case 'search_joindate': + $base_url .= '&search_joindate=true&date_type=' . rawurlencode($date_type) . '&date_day=' . rawurlencode($date_day) . '&date_month=' . rawurlencode($date_month) . '&date_year=' . rawurlencode(stripslashes($date_year)); + + $date_type = strtolower(trim($date_type)); + + if ($date_type != 'before' && $date_type != 'after') { + bb_die($lang['SEARCH_INVALID_DATE']); + } + + $date_day = (int)$date_day; + + if (!preg_match('/^([1-9]|[0-2][0-9]|3[0-1])$/', $date_day)) { + bb_die($lang['SEARCH_INVALID_DAY']); + } + + $date_month = (int)$date_month; + + if (!preg_match('/^(0?[1-9]|1[0-2])$/', $date_month)) { + bb_die($lang['SEARCH_INVALID_MONTH']); + } + + $date_year = (int)$date_year; + + if (!preg_match('/^(20[0-9]{2}|19[0-9]{2})$/', $date_year)) { + bb_die($lang['SEARCH_INVALID_YEAR']); + } + + $text = sprintf($lang['SEARCH_FOR_DATE'], strip_tags(htmlspecialchars(stripslashes($date_type))), $date_year, $date_month, $date_day); + + $time = mktime(0, 0, 0, $date_month, $date_day, $date_year); + + if ($date_type == 'before') { + $arg = '<'; + } else { + $arg = '>'; + } + + $total_sql .= 'SELECT COUNT(user_id) AS total FROM ' . BB_USERS . " WHERE user_regdate $arg $time AND user_id <> " . GUEST_UID; + $select_sql .= " WHERE u.user_regdate $arg $time AND u.user_id <> " . GUEST_UID; + break; + + case 'search_group': + $group_id = (int)$group_id; + + $base_url .= '&search_group=true&group_id=' . rawurlencode($group_id); + + if (!$group_id) { + bb_die($lang['SEARCH_INVALID_GROUP']); + } + + $sql = 'SELECT group_name FROM ' . BB_GROUPS . " WHERE group_id = $group_id AND group_single_user = 0"; + + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select group data #2'); + } + + if (DB()->num_rows($result) == 0) { + bb_die($lang['SEARCH_INVALID_GROUP']); + } + + $group_name = DB()->sql_fetchrow($result); + + $text = sprintf($lang['SEARCH_FOR_GROUP'], strip_tags(htmlspecialchars($group_name['group_name']))); + + $total_sql .= 'SELECT COUNT(u.user_id) AS total + FROM ' . BB_USERS . ' AS u, ' . BB_USER_GROUP . " AS ug WHERE u.user_id = ug.user_id AND ug.group_id = $group_id - AND u.user_id <> ".GUEST_UID; + AND u.user_id <> " . GUEST_UID; - $select_sql .= ", ".BB_USER_GROUP." AS ug + $select_sql .= ', ' . BB_USER_GROUP . " AS ug WHERE u.user_id = ug.user_id AND ug.group_id = $group_id - AND u.user_id <> ".GUEST_UID; - break; + AND u.user_id <> " . GUEST_UID; + break; - case 'search_rank': - $rank_id = intval($rank_id); + case 'search_rank': + $rank_id = (int)$rank_id; - $base_url .= '&search_rank=true&rank_id='. rawurlencode($rank_id); + $base_url .= '&search_rank=true&rank_id=' . rawurlencode($rank_id); - if (!$rank_id) - { - bb_die($lang['SEARCH_INVALID_RANK']); - } + if (!$rank_id) { + bb_die($lang['SEARCH_INVALID_RANK']); + } - $sql = "SELECT rank_title FROM ".BB_RANKS." WHERE rank_id = $rank_id AND rank_special = 1"; + $sql = 'SELECT rank_title FROM ' . BB_RANKS . " WHERE rank_id = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select rank data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select rank data'); + } - if (DB()->num_rows($result)==0) - { - bb_die($lang['SEARCH_INVALID_RANK']); - } + if (DB()->num_rows($result) == 0) { + bb_die($lang['SEARCH_INVALID_RANK']); + } - $rank_title = DB()->sql_fetchrow($result); + $rank_title = DB()->sql_fetchrow($result); - $text = sprintf($lang['SEARCH_FOR_RANK'], strip_tags(htmlspecialchars($rank_title['rank_title']))); + $text = sprintf($lang['SEARCH_FOR_RANK'], strip_tags(htmlspecialchars($rank_title['rank_title']))); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_rank = $rank_id - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_rank = $rank_id - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE u.user_rank = $rank_id + AND u.user_id <> " . GUEST_UID; + break; - case 'search_postcount': - $postcount_type = trim(strtolower($postcount_type)); - $postcount_value = trim(strtolower($postcount_value)); + case 'search_postcount': + $postcount_type = strtolower(trim($postcount_type)); + $postcount_value = strtolower(trim($postcount_value)); - $base_url .= '&search_postcount=true&postcount_type='. rawurlencode($postcount_type) .'&postcount_value='. rawurlencode(stripslashes($postcount_value)); + $base_url .= '&search_postcount=true&postcount_type=' . rawurlencode($postcount_type) . '&postcount_value=' . rawurlencode(stripslashes($postcount_value)); - switch($postcount_type) - { - case 'greater': - $postcount_value = intval($postcount_value); + switch ($postcount_type) { + case 'greater': + $postcount_value = (int)$postcount_value; - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_GREATER'], $postcount_value); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_GREATER'], $postcount_value); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_posts > $postcount_value - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts > $postcount_value - AND u.user_id <> ".GUEST_UID; - break; - case 'lesser': - $postcount_value = intval($postcount_value); + $select_sql .= " WHERE u.user_posts > $postcount_value + AND u.user_id <> " . GUEST_UID; + break; + case 'lesser': + $postcount_value = (int)$postcount_value; - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_LESSER'], $postcount_value); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_LESSER'], $postcount_value); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_posts < $postcount_value - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts < $postcount_value - AND u.user_id <> ".GUEST_UID; - break; - case 'equals': - // looking for a - - if (strstr($postcount_value, '-')) - { - $range = preg_split('/[-\s]+/', $postcount_value); + $select_sql .= " WHERE u.user_posts < $postcount_value + AND u.user_id <> " . GUEST_UID; + break; + case 'equals': + // looking for a - + if (str_contains($postcount_value, '-')) { + $range = preg_split('/[-\s]+/', $postcount_value); - $range_begin = intval($range[0]); - $range_end = intval($range[1]); + $range_begin = (int)$range[0]; + $range_end = (int)$range[1]; - if ($range_begin > $range_end) - { - bb_die($lang['SEARCH_INVALID_POSTCOUNT']); - } + if ($range_begin > $range_end) { + bb_die($lang['SEARCH_INVALID_POSTCOUNT']); + } - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_RANGE'], $range_begin, $range_end); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_RANGE'], $range_begin, $range_end); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_posts >= $range_begin AND user_posts <= $range_end - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts >= $range_begin + $select_sql .= " WHERE u.user_posts >= $range_begin AND u.user_posts <= $range_end - AND u.user_id <> ".GUEST_UID; - } - else - { - $postcount_value = intval($postcount_value); + AND u.user_id <> " . GUEST_UID; + } else { + $postcount_value = (int)$postcount_value; - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_EQUALS'], $postcount_value); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_EQUALS'], $postcount_value); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_posts = $postcount_value - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts = $postcount_value - AND u.user_id <> ".GUEST_UID; - } - break; - default: - bb_die($lang['SEARCH_INVALID']); - } - break; + $select_sql .= " WHERE u.user_posts = $postcount_value + AND u.user_id <> " . GUEST_UID; + } + break; + default: + bb_die($lang['SEARCH_INVALID']); + } + break; - case 'search_userfield': - $base_url .= '&search_userfield=true&userfield_type='. rawurlencode($userfield_type) .'&userfield_value='. rawurlencode(stripslashes($userfield_value)); + case 'search_userfield': + $base_url .= '&search_userfield=true&userfield_type=' . rawurlencode($userfield_type) . '&userfield_value=' . rawurlencode(stripslashes($userfield_value)); - $text = strip_tags(htmlspecialchars(stripslashes($userfield_value))); + $text = strip_tags(htmlspecialchars(stripslashes($userfield_value))); - $userfield_value = preg_replace('/\*/', '%', trim(strip_tags(strtolower($userfield_value)))); + $userfield_value = str_replace('*', '%', trim(strip_tags(strtolower($userfield_value)))); + if (str_contains($userfield_value, '%')) { + $op = 'LIKE'; + } else { + $op = '='; + } - if (strstr($userfield_value, '%')) - { - $op = 'LIKE'; - } - else - { - $op = '='; - } + if ($userfield_value == '') { + bb_die($lang['SEARCH_INVALID_USERFIELD']); + } - if ($userfield_value == '') bb_die($lang['SEARCH_INVALID_USERFIELD']); + $userfield_type = strtolower(trim($userfield_type)); - $userfield_type = trim(strtolower($userfield_type)); + switch ($userfield_type) { + case 'icq': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_ICQ'], $text); + $field = 'user_icq'; + break; + case 'skype': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_SKYPE'], $text); + $field = 'user_skype'; + break; + case 'twitter': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_TWITTER'], $text); + $field = 'user_twitter'; + break; + case 'website': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_WEBSITE'], $text); + $field = 'user_website'; + break; + case 'location': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_LOCATION'], $text); + $field = 'user_from'; + break; + case 'interests': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_INTERESTS'], $text); + $field = 'user_interests'; + break; + case 'occupation': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_OCCUPATION'], $text); + $field = 'user_occ'; + break; + default: + bb_die($lang['SEARCH_INVALID']); + } - switch ($userfield_type) - { - case 'icq': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_ICQ'],$text); - $field = 'user_icq'; - break; - case 'skype': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_SKYPE'],$text); - $field = 'user_skype'; - break; - case 'twitter': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_TWITTER'],$text); - $field = 'user_twitter'; - break; - case 'website': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_WEBSITE'],$text); - $field = 'user_website'; - break; - case 'location': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_LOCATION'],$text); - $field = 'user_from'; - break; - case 'interests': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_INTERESTS'],$text); - $field = 'user_interests'; - break; - case 'occupation': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_OCCUPATION'],$text); - $field = 'user_occ'; - break; - default: - bb_die( $lang['SEARCH_INVALID']); - } + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " + WHERE {$lower_b}$field{$lower_e} $op '" . DB()->escape($userfield_value) . "' + AND user_id <> " . GUEST_UID; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE {$lower_b}$field{$lower_e} $op '".DB()->escape($userfield_value)."' - AND user_id <> ".GUEST_UID; + $select_sql .= " WHERE {$lower_b}u.$field{$lower_e} $op '" . DB()->escape($userfield_value) . "' + AND u.user_id <> " . GUEST_UID; + break; - $select_sql .= " WHERE {$lower_b}u.$field{$lower_e} $op '".DB()->escape($userfield_value)."' - AND u.user_id <> ".GUEST_UID; - break; + case 'search_lastvisited': + $lastvisited_type = strtolower(trim($lastvisited_type)); + $lastvisited_days = (int)$lastvisited_days; - case 'search_lastvisited': - $lastvisited_type = trim(strtolower($lastvisited_type)); - $lastvisited_days = intval($lastvisited_days); + $base_url .= '&search_lastvisited=true&lastvisited_type=' . rawurlencode(stripslashes($lastvisited_type)) . '&lastvisited_days=' . rawurlencode($lastvisited_days); - $base_url .= '&search_lastvisited=true&lastvisited_type='. rawurlencode(stripslashes($lastvisited_type)) .'&lastvisited_days='. rawurlencode($lastvisited_days); + $lastvisited_seconds = (TIMENOW - ((($lastvisited_days * 24) * 60) * 60)); - $lastvisited_seconds = ( TIMENOW - ( ( ( $lastvisited_days * 24 ) * 60 ) * 60 ) ); + switch ($lastvisited_type) { + case 'in': + $text = sprintf($lang['SEARCH_FOR_LASTVISITED_INTHELAST'], delta_time((TIMENOW - 86400 * $lastvisited_days), TIMENOW, 'days')); - switch($lastvisited_type) - { - case 'in': - $text = sprintf($lang['SEARCH_FOR_LASTVISITED_INTHELAST'], $lastvisited_days, ( ( $lastvisited_days > 1 ) ? $lang['DAYS'] : $lang['DAY'] ) ); - - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_lastvisit >= $lastvisited_seconds - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_lastvisit >= $lastvisited_seconds - AND u.user_id <> ".GUEST_UID; - break; - case 'after': - $text = sprintf($lang['SEARCH_FOR_LASTVISITED_AFTERTHELAST'], $lastvisited_days, ( ( $lastvisited_days > 1 ) ? $lang['DAYS'] : $lang['DAY'] )); + $select_sql .= " WHERE u.user_lastvisit >= $lastvisited_seconds + AND u.user_id <> " . GUEST_UID; + break; + case 'after': + $text = sprintf($lang['SEARCH_FOR_LASTVISITED_AFTERTHELAST'], delta_time((TIMENOW - 86400 * $lastvisited_days), TIMENOW, 'days')); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_lastvisit < $lastvisited_seconds - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_lastvisit < $lastvisited_seconds - AND u.user_id <> ".GUEST_UID; + $select_sql .= " WHERE u.user_lastvisit < $lastvisited_seconds + AND u.user_id <> " . GUEST_UID; - break; - default: - bb_die($lang['SEARCH_INVALID_LASTVISITED']); - } - break; + break; + default: + bb_die($lang['SEARCH_INVALID_LASTVISITED']); + } + break; - case 'search_language': - $base_url .= '&search_language=true&language_type='. rawurlencode(stripslashes($language_type)); + case 'search_language': + $base_url .= '&search_language=true&language_type=' . rawurlencode(stripslashes($language_type)); - $language_type = trim(strtolower(stripslashes($language_type))); + $language_type = strtolower(trim(stripslashes($language_type))); - if ($language_type == '') - { - bb_die($lang['SEARCH_INVALID_LANGUAGE']); - } + if ($language_type == '') { + bb_die($lang['SEARCH_INVALID_LANGUAGE']); + } - $text = sprintf($lang['SEARCH_FOR_LANGUAGE'], strip_tags(htmlspecialchars($language_type))); + $text = sprintf($lang['SEARCH_FOR_LANGUAGE'], strip_tags(htmlspecialchars($language_type))); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE user_lang = '".DB()->escape($language_type)."' - AND user_id <> ".GUEST_UID; + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " + WHERE user_lang = '" . DB()->escape($language_type) . "' + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_lang = '".DB()->escape($language_type)."' - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE u.user_lang = '" . DB()->escape($language_type) . "' + AND u.user_id <> " . GUEST_UID; + break; - case 'search_timezone': - $base_url .= '&search_timezone=true&timezone_type='. rawurlencode(stripslashes($timezone_type)); - $text = sprintf($lang['SEARCH_FOR_TIMEZONE'], strip_tags(htmlspecialchars(stripslashes($timezone_type)))); + case 'search_timezone': + $base_url .= '&search_timezone=true&timezone_type=' . rawurlencode(stripslashes($timezone_type)); + $text = sprintf($lang['SEARCH_FOR_TIMEZONE'], strip_tags(htmlspecialchars(stripslashes($timezone_type)))); - $timezone_type = intval($timezone_type); + $timezone_type = (int)$timezone_type; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . " WHERE user_timezone = $timezone_type - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_timezone = $timezone_type - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE u.user_timezone = $timezone_type + AND u.user_id <> " . GUEST_UID; + break; - case 'search_moderators': - $base_url .= '&search_moderators=true&moderators_forum='. rawurlencode(stripslashes($moderators_forum)); - $moderators_forum = intval($moderators_forum); + case 'search_moderators': + $base_url .= '&search_moderators=true&moderators_forum=' . rawurlencode(stripslashes($moderators_forum)); + $moderators_forum = (int)$moderators_forum; - $sql = "SELECT forum_name FROM ".BB_FORUMS." WHERE forum_id = ".$moderators_forum; + $sql = 'SELECT forum_name FROM ' . BB_FORUMS . ' WHERE forum_id = ' . $moderators_forum; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select forum data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select forum data'); + } - if (DB()->num_rows($result)==0) - { - bb_die($lang['SEARCH_INVALID_MODERATORS']); - } + if (DB()->num_rows($result) == 0) { + bb_die($lang['SEARCH_INVALID_MODERATORS']); + } - $forum_name = DB()->sql_fetchrow($result); + $forum_name = DB()->sql_fetchrow($result); - $text = sprintf($lang['SEARCH_FOR_MODERATORS'], htmlCHR($forum_name['forum_name'])); + $text = sprintf($lang['SEARCH_FOR_MODERATORS'], htmlCHR($forum_name['forum_name'])); - $total_sql .= "SELECT COUNT(DISTINCT u.user_id) AS total - FROM ".BB_USERS." AS u, ".BB_GROUPS." AS g, ".BB_USER_GROUP." AS ug, ".BB_AUTH_ACCESS." AS aa + $total_sql .= 'SELECT COUNT(DISTINCT u.user_id) AS total + FROM ' . BB_USERS . ' AS u, ' . BB_GROUPS . ' AS g, ' . BB_USER_GROUP . ' AS ug, ' . BB_AUTH_ACCESS . ' AS aa WHERE u.user_id = ug.user_id AND ug.group_id = g.group_id AND g.group_id = aa.group_id - AND aa.forum_id = ". $moderators_forum ." - AND aa.forum_perm & ". BF_AUTH_MOD ." - AND u.user_id <> ".GUEST_UID; + AND aa.forum_id = ' . $moderators_forum . ' + AND aa.forum_perm & ' . BF_AUTH_MOD . ' + AND u.user_id <> ' . GUEST_UID; - $select_sql .= ", ".BB_GROUPS." AS g, ".BB_USER_GROUP." AS ug, ".BB_AUTH_ACCESS." AS aa + $select_sql .= ', ' . BB_GROUPS . ' AS g, ' . BB_USER_GROUP . ' AS ug, ' . BB_AUTH_ACCESS . ' AS aa WHERE u.user_id = ug.user_id AND ug.group_id = g.group_id AND g.group_id = aa.group_id - AND aa.forum_id = ". $moderators_forum ." - AND aa.forum_perm & ". BF_AUTH_MOD ." - AND u.user_id <> ".GUEST_UID." - GROUP BY u.user_id, u.username, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit"; - break; + AND aa.forum_id = ' . $moderators_forum . ' + AND aa.forum_perm & ' . BF_AUTH_MOD . ' + AND u.user_id <> ' . GUEST_UID . ' + GROUP BY u.user_id, u.username, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit'; + break; - case 'search_misc': - default: - $misc = trim(strtolower($misc)); + case 'search_misc': + default: + $misc = strtolower(trim($misc)); - $base_url .= '&search_misc=true&misc='. rawurlencode(stripslashes($misc)); + $base_url .= '&search_misc=true&misc=' . rawurlencode(stripslashes($misc)); - switch ($misc) - { - case 'admins': - $text = $lang['SEARCH_FOR_ADMINS']; + switch ($misc) { + case 'admins': + $text = $lang['SEARCH_FOR_ADMINS']; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE user_level = ".ADMIN." - AND user_id <> ".GUEST_UID; + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . ' + WHERE user_level = ' . ADMIN . ' + AND user_id <> ' . GUEST_UID; - $select_sql .= " WHERE u.user_level = ".ADMIN." - AND u.user_id <> ".GUEST_UID; - break; - case 'mods': - $text = $lang['SEARCH_FOR_MODS']; + $select_sql .= ' WHERE u.user_level = ' . ADMIN . ' + AND u.user_id <> ' . GUEST_UID; + break; + case 'mods': + $text = $lang['SEARCH_FOR_MODS']; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE user_level = ".MOD." - AND user_id <> ".GUEST_UID; + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . ' + WHERE user_level = ' . MOD . ' + AND user_id <> ' . GUEST_UID; - $select_sql .= " WHERE u.user_level = ".MOD." - AND u.user_id <> ".GUEST_UID; - break; - case 'banned': - $text = $lang['SEARCH_FOR_BANNED']; + $select_sql .= ' WHERE u.user_level = ' . MOD . ' + AND u.user_id <> ' . GUEST_UID; + break; + case 'banned': + $text = $lang['SEARCH_FOR_BANNED']; - $total_sql .= "SELECT COUNT(u.user_id) AS total - FROM ".BB_USERS." AS u, ".BB_BANLIST." AS b + $total_sql .= 'SELECT COUNT(u.user_id) AS total + FROM ' . BB_USERS . ' AS u, ' . BB_BANLIST . ' AS b WHERE u.user_id = b.ban_userid - AND u.user_id <> ".GUEST_UID; + AND u.user_id <> ' . GUEST_UID; - $select_sql .= ", ".BB_BANLIST." AS b + $select_sql .= ', ' . BB_BANLIST . ' AS b WHERE u.user_id = b.ban_userid - AND u.user_id <> ".GUEST_UID; + AND u.user_id <> ' . GUEST_UID; - break; - case 'disabled': - $text = $lang['SEARCH_FOR_DISABLED']; + break; + case 'disabled': + $text = $lang['SEARCH_FOR_DISABLED']; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= 'SELECT COUNT(user_id) AS total + FROM ' . BB_USERS . ' WHERE user_active = 0 - AND user_id <> ".GUEST_UID; + AND user_id <> ' . GUEST_UID; - $select_sql .= " WHERE u.user_active = 0 - AND u.user_id <> ".GUEST_UID; + $select_sql .= ' WHERE u.user_active = 0 + AND u.user_id <> ' . GUEST_UID; - break; - default: - bb_die($lang['SEARCH_INVALID']); - } - } + break; + default: + bb_die($lang['SEARCH_INVALID']); + } + } - $select_sql .= " ORDER BY "; + $select_sql .= ' ORDER BY '; - switch (strtolower(@$_GET['sort'])) - { - case 'regdate': - $sort = 'regdate'; - $select_sql .= 'u.user_regdate'; - break; + if (isset($_GET['sort'])) { + switch (strtolower($_GET['sort'])) { + case 'regdate': + $sort = 'regdate'; + $select_sql .= 'u.user_regdate'; + break; - case 'posts': - $sort = 'posts'; - $select_sql .= 'u.user_posts'; - break; + case 'posts': + $sort = 'posts'; + $select_sql .= 'u.user_posts'; + break; - case 'user_email': - $sort = 'user_email'; - $select_sql .= 'u.user_email'; - break; + case 'user_email': + $sort = 'user_email'; + $select_sql .= 'u.user_email'; + break; - case 'lastvisit': - $sort = 'lastvisit'; - $select_sql .= 'u.user_lastvisit'; - break; + case 'lastvisit': + $sort = 'lastvisit'; + $select_sql .= 'u.user_lastvisit'; + break; - case 'username': - default: - $sort = 'username'; - $select_sql .= 'u.username'; - } + case 'username': + $sort = 'username'; + $select_sql .= 'u.username'; + } + } else { + $sort = 'username'; + $select_sql .= 'u.username'; + } - switch (@$_GET['order']) - { - case 'DESC': - $order = 'DESC'; - $o_order = 'ASC'; - break; + if (isset($_GET['order'])) { + $o_order = 'ASC'; + $order = 'DESC'; + } else { + $o_order = 'DESC'; + $order = 'ASC'; + } - default: - $o_order = 'DESC'; - $order = 'ASC'; - } + $select_sql .= " $order"; - $select_sql .= " $order"; + $page = isset($_GET['page']) ? (int)$_GET['page'] : 0; - $page = ( isset($_GET['page']) ) ? intval($_GET['page']) : intval(trim(@$_POST['page'])); + if ($page < 1) { + $page = 1; + } - if ($page < 1) - { - $page = 1; - } + if ($page == 1) { + $offset = 0; + } else { + $offset = (($page - 1) * config()->get('topics_per_page')); + } - if ($page == 1) - { - $offset = 0; - } - else - { - $offset = ( ($page - 1) * $bb_cfg['topics_per_page']); - } + $limit = "LIMIT $offset, " . config()->get('topics_per_page'); - $limit = "LIMIT $offset, ".$bb_cfg['topics_per_page']; + $select_sql .= " $limit"; - $select_sql .= " $limit"; + if (null !== $total_sql) { + if (!$result = DB()->sql_query($total_sql)) { + bb_die('Could not count users'); + } - if (!is_null($total_sql)) - { - if (!$result = DB()->sql_query($total_sql)) - { - bb_die('Could not count users'); - } + $total_pages = DB()->sql_fetchrow($result); - $total_pages = DB()->sql_fetchrow($result); + if ($total_pages['total'] == 0) { + bb_die($lang['SEARCH_NO_RESULTS']); + } + } + $num_pages = ceil($total_pages['total'] / config()->get('topics_per_page')); - if ($total_pages['total'] == 0) - { - bb_die($lang['SEARCH_NO_RESULTS']); - } - } - $num_pages = ceil( ( $total_pages['total'] / $bb_cfg['topics_per_page'] ) ); + $pagination = ''; - $pagination = ''; + if ($page > 1) { + $pagination .= '' . $lang['BACK'] . ''; + } + if ($page < $num_pages) { + $pagination .= ($pagination == '') ? '' . $lang['NEXT'] . '' : ' | ' . $lang['NEXT'] . ''; + } + if ($num_pages > 2) { + $pagination .= '   '; + } + $template->assign_vars([ + 'TPL_ADMIN_USER_SEARCH_RESULTS' => true, - if ($page > 1) - { - $pagination .= ''. $lang['PREVIOUS'] .''; - } - if ($page < $num_pages) - { - $pagination .= ( $pagination == '' ) ? ''.$lang['NEXT'].'' : ' | '.$lang['NEXT'].''; - } - if ($num_pages > 2) - { - $pagination .= '   '; - } - $template->assign_vars(array( - 'TPL_ADMIN_USER_SEARCH_RESULTS' => true, + 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], $page, $num_pages), + 'PAGINATION' => $pagination, + 'NEW_SEARCH' => sprintf($lang['SEARCH_USERS_NEW'], $text, $total_pages['total'], 'admin_user_search.php'), - 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], $page, $num_pages), - 'PAGINATION' => $pagination, - 'NEW_SEARCH' => sprintf($lang['SEARCH_USERS_NEW'],$text, $total_pages['total'], 'admin_user_search.php'), + 'U_USERNAME' => ($sort == 'username') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=username&order=$order", + 'U_EMAIL' => ($sort == 'user_email') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=user_email&order=$order", + 'U_POSTS' => ($sort == 'posts') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=posts&order=$order", + 'U_JOINDATE' => ($sort == 'regdate') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=regdate&order=$order", + 'U_LASTVISIT' => ($sort == 'lastvisit') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=lastvisit&order=$order", - 'U_USERNAME' => ($sort == 'username') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=username&order=$order", - 'U_EMAIL' => ($sort == 'user_email') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=user_email&order=$order", - 'U_POSTS' => ($sort == 'posts') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=posts&order=$order", - 'U_JOINDATE' => ($sort == 'regdate') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=regdate&order=$order", - 'U_LASTVISIT' => ($sort == 'lastvisit') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=lastvisit&order=$order", + 'S_POST_ACTION' => "$base_url&sort=$sort&order=$order" + ]); - 'S_POST_ACTION' => "$base_url&sort=$sort&order=$order" - )); + if (!$result = DB()->sql_query($select_sql)) { + bb_die('Could not select user data'); + } - if (!$result = DB()->sql_query($select_sql)) - { - bb_die('Could not select user data'); - } + $rowset = DB()->sql_fetchrowset($result); - $rowset = DB()->sql_fetchrowset($result); + $users_sql = ''; - $users_sql = ''; + foreach ($rowset as $array) { + $users_sql .= ($users_sql == '') ? $array['user_id'] : ', ' . $array['user_id']; + } - foreach ($rowset as $array) - { - $users_sql .= ( $users_sql == '' ) ? $array['user_id'] : ', '.$array['user_id']; - } + $sql = 'SELECT ban_userid AS user_id FROM ' . BB_BANLIST . " WHERE ban_userid IN ($users_sql)"; - $sql = "SELECT ban_userid AS user_id FROM ". BB_BANLIST ." WHERE ban_userid IN ($users_sql)"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select banned data'); + } - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select banned data'); - } + unset($banned); - unset($banned); + $banned = []; - $banned = array(); + while ($row = DB()->sql_fetchrow($result)) { + $banned[$row['user_id']] = true; + } - while ($row = DB()->sql_fetchrow($result)) - { - $banned[$row['user_id']] = true; - } + for ($i = 0, $iMax = count($rowset); $i < $iMax; $i++) { + $row_class = !($i % 2) ? 'row1' : 'row2'; - for ($i = 0; $i < count($rowset); $i++) - { - $row_class = !($i % 2) ? 'row1' : 'row2'; + $template->assign_block_vars('userrow', [ + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($rowset[$i], true), + 'EMAIL' => $rowset[$i]['user_email'], + 'JOINDATE' => bb_date($rowset[$i]['user_regdate']), + 'LASTVISIT' => $rowset[$i]['user_lastvisit'] ? bb_date($rowset[$i]['user_lastvisit']) : $lang['NEVER'], + 'POSTS' => $rowset[$i]['user_posts'], + 'BAN' => (!isset($banned[$rowset[$i]['user_id']])) ? $lang['NOT_BANNED'] : $lang['BANNED'], + 'ABLED' => $rowset[$i]['user_active'] ? $lang['ENABLED'] : $lang['DISABLED'], - $template->assign_block_vars('userrow', array( - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($rowset[$i]), - 'EMAIL' => $rowset[$i]['user_email'], - 'JOINDATE' => bb_date($rowset[$i]['user_regdate']), - 'LASTVISIT' => bb_date($rowset[$i]['user_lastvisit']), - 'POSTS' => $rowset[$i]['user_posts'], - 'BAN' => ( ( !isset($banned[$rowset[$i]['user_id']]) ) ? $lang['NOT_BANNED'] : $lang['BANNED'] ), - 'ABLED' => ( ( $rowset[$i]['user_active'] ) ? $lang['ENABLED'] : $lang['DISABLED'] ), - - 'U_VIEWPOSTS' => "../search.php?search_author=1&uid={$rowset[$i]['user_id']}", - 'U_MANAGE' => '../profile.php?mode=editprofile&'. POST_USERS_URL .'='.$rowset[$i]['user_id'].'&admin=1', - 'U_PERMISSIONS' => 'admin_ug_auth.php?mode=user&'. POST_USERS_URL .'='. $rowset[$i]['user_id'], - )); - } + 'U_VIEWPOSTS' => "../search.php?search_author=1&uid={$rowset[$i]['user_id']}", + 'U_MANAGE' => '../profile.php?mode=editprofile&' . POST_USERS_URL . '=' . $rowset[$i]['user_id'] . '&admin=1', + 'U_PERMISSIONS' => 'admin_ug_auth.php?mode=user&' . POST_USERS_URL . '=' . $rowset[$i]['user_id'], + ]); + } } -print_page('admin_user_search.tpl', 'admin'); \ No newline at end of file +print_page('admin_user_search.tpl', 'admin'); diff --git a/admin/admin_words.php b/admin/admin_words.php index e46de3025..94f11caba 100644 --- a/admin/admin_words.php +++ b/admin/admin_words.php @@ -1,157 +1,138 @@
($bb_cfg[\'use_word_censor\'] in config.php)'); +require __DIR__ . '/pagestart.php'; + +if (!config()->get('use_word_censor')) { + bb_die('Word censor disabled

(use_word_censor in config.php)'); } $mode = request_var('mode', ''); $mode = htmlspecialchars($mode); -if (isset($_POST['add'])) -{ - $mode = 'add'; -} -else if (isset($_POST['save'])) -{ - $mode = 'save'; +if (isset($_POST['add'])) { + $mode = 'add'; +} elseif (isset($_POST['save'])) { + $mode = 'save'; } -if ($mode != '') -{ - if ($mode == 'edit' || $mode == 'add') - { - $word_id = intval(request_var('id', 0)); +if ($mode != '') { + if ($mode == 'edit' || $mode == 'add') { + $word_id = (int)request_var('id', 0); - $s_hidden_fields = $word = $replacement = ''; + $s_hidden_fields = $word = $replacement = ''; - if ($mode == 'edit') - { - if ($word_id) - { - $sql = "SELECT * FROM " . BB_WORDS . " WHERE word_id = $word_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not query words table #1'); - } + if ($mode == 'edit') { + if ($word_id) { + $sql = 'SELECT * FROM ' . BB_WORDS . " WHERE word_id = $word_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query words table #1'); + } - $word_info = DB()->sql_fetchrow($result); - $s_hidden_fields .= ''; - $word = $word_info['word']; - $replacement = $word_info['replacement']; - } - else - { - bb_die($lang['NO_WORD_SELECTED']); - } - } + $word_info = DB()->sql_fetchrow($result); + $s_hidden_fields .= ''; + $word = $word_info['word']; + $replacement = $word_info['replacement']; + } else { + bb_die($lang['NO_WORD_SELECTED']); + } + } - $template->assign_vars(array( - 'TPL_ADMIN_WORDS_EDIT' => true, - 'WORD' => $word, - 'REPLACEMENT' => $replacement, - 'S_WORDS_ACTION' => 'admin_words.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); - } - else if ($mode == 'save') - { - $word_id = intval(request_var('id', 0)); - $word = trim(request_var('word', '')); - $replacement = trim(request_var('replacement', '')); + $template->assign_vars([ + 'TPL_ADMIN_WORDS_EDIT' => true, + 'WORD' => $word, + 'REPLACEMENT' => $replacement, + 'S_WORDS_ACTION' => 'admin_words.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + ]); + } elseif ($mode == 'save') { + $word_id = (int)request_var('id', 0); + $word = trim(request_var('word', '')); + $replacement = trim(request_var('replacement', '')); - if ($word == '' || $replacement == '') - { - bb_die($lang['MUST_ENTER_WORD']); - } + if ($word == '' || $replacement == '') { + bb_die($lang['MUST_ENTER_WORD']); + } - if ($word_id) - { - $sql = "UPDATE " . BB_WORDS . " + if ($word_id) { + $sql = 'UPDATE ' . BB_WORDS . " SET word = '" . DB()->escape($word) . "', replacement = '" . DB()->escape($replacement) . "' WHERE word_id = $word_id"; - $message = $lang['WORD_UPDATED']; - } - else - { - $sql = "INSERT INTO " . BB_WORDS . " (word, replacement) + $message = $lang['WORD_UPDATED']; + } else { + $sql = 'INSERT INTO ' . BB_WORDS . " (word, replacement) VALUES ('" . DB()->escape($word) . "', '" . DB()->escape($replacement) . "')"; - $message = $lang['WORD_ADDED']; - } + $message = $lang['WORD_ADDED']; + } - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not insert data into words table'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not insert data into words table'); + } - CACHE('bb_cache')->rm('censored'); - $message .= '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $datastore->update('censor'); + censor()->reload(); // Reload the singleton instance with updated words + $message .= '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else if ($mode == 'delete') - { - $word_id = intval(request_var('id', 0)); + bb_die($message); + } elseif ($mode == 'delete') { + $word_id = (int)request_var('id', 0); - if ($word_id) - { - $sql = "DELETE FROM " . BB_WORDS . " WHERE word_id = $word_id"; + if ($word_id) { + $sql = 'DELETE FROM ' . BB_WORDS . " WHERE word_id = $word_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not remove data from words table'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not remove data from words table'); + } - CACHE('bb_cache')->rm('censored'); + $datastore->update('censor'); + censor()->reload(); // Reload the singleton instance with updated words - bb_die($lang['WORD_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } - else - { - bb_die($lang['NO_WORD_SELECTED']); - } - } -} -else -{ - $sql = "SELECT * FROM " . BB_WORDS . " ORDER BY word"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not query words table #2'); - } + bb_die($lang['WORD_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + bb_die($lang['NO_WORD_SELECTED']); + } + } +} else { + $sql = 'SELECT * FROM ' . BB_WORDS . ' ORDER BY word'; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query words table #2'); + } - $word_rows = DB()->sql_fetchrowset($result); - $word_count = count($word_rows); + $word_rows = DB()->sql_fetchrowset($result); + $word_count = count($word_rows); - $template->assign_vars(array( - 'TPL_ADMIN_WORDS_LIST' => true, - 'S_WORDS_ACTION' => 'admin_words.php', - 'S_HIDDEN_FIELDS' => '', - )); + $template->assign_vars([ + 'TPL_ADMIN_WORDS_LIST' => true, + 'S_WORDS_ACTION' => 'admin_words.php', + 'S_HIDDEN_FIELDS' => '' + ]); - for ($i = 0; $i < $word_count; $i++) - { - $word = $word_rows[$i]['word']; - $replacement = $word_rows[$i]['replacement']; - $word_id = $word_rows[$i]['word_id']; + for ($i = 0; $i < $word_count; $i++) { + $word = $word_rows[$i]['word']; + $replacement = $word_rows[$i]['replacement']; + $word_id = $word_rows[$i]['word_id']; - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('words', array( - 'ROW_CLASS' => $row_class, - 'WORD' => $word, - 'REPLACEMENT' => $replacement, - 'U_WORD_EDIT' => "admin_words.php?mode=edit&id=$word_id", - 'U_WORD_DELETE' => "admin_words.php?mode=delete&id=$word_id", - )); - } + $template->assign_block_vars('words', [ + 'ROW_CLASS' => $row_class, + 'WORD' => $word, + 'REPLACEMENT' => $replacement, + 'U_WORD_EDIT' => "admin_words.php?mode=edit&id=$word_id", + 'U_WORD_DELETE' => "admin_words.php?mode=delete&id=$word_id" + ]); + } } -print_page('admin_words.tpl', 'admin'); \ No newline at end of file +print_page('admin_words.tpl', 'admin'); diff --git a/admin/index.php b/admin/index.php index 1334f3d8b..33cb3411d 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,291 +1,228 @@ get('stats')) { + $datastore->update('stats'); + $stats = $datastore->get('stats'); +} + +// Check for updates +if (!$update_data = $datastore->get('check_updates')) { + $datastore->update('check_updates'); + $update_data = $datastore->get('check_updates'); +} // Generate relevant output -if (isset($_GET['pane']) && $_GET['pane'] == 'left') -{ - if (!$module = CACHE('bb_cache')->get('admin_module')) - { - $dir = @opendir('.'); - $setmodules = 1; - while ($file = @readdir($dir)) - { - if (preg_match('/^admin_.*?\.php$/', $file)) - { - include('./' . $file); - } - } - unset($setmodules); - @closedir($dir); - CACHE('bb_cache')->set('admin_module', $module, 600); - } +if (isset($_GET['pane']) && $_GET['pane'] == 'left') { + $module = []; - $template->assign_vars(array( - 'TPL_ADMIN_NAVIGATE' => true, - 'U_FORUM_INDEX' => '../index.php', - 'U_ADMIN_INDEX' => 'index.php?pane=right', - )); + // Scan modules + if (!CACHE('bb_cache')->get('admin_module_' . $user->id)) { + $dir = opendir('.'); + $setmodules = true; + while ($file = readdir($dir)) { + if (preg_match('/^admin_.*?\.php$/', $file)) { + include './' . $file; + } + } + unset($setmodules); + closedir($dir); - ksort($module); + // Set modules into cache + CACHE('bb_cache')->set('admin_module_' . $user->id, $module, 600); + } - while (list($cat, $action_array) = each($module)) - { - $cat = (!empty($lang[$cat])) ? $lang[$cat] : preg_replace('/_/', ' ', $cat); + // Get modules from cache + $module = CACHE('bb_cache')->get('admin_module_' . $user->id); - $template->assign_block_vars('catrow', array( - 'ADMIN_CATEGORY' => $cat, - )); + $template->assign_vars([ + 'TPL_ADMIN_NAVIGATE' => true, + 'U_FORUM_INDEX' => '../index.php', + 'U_ADMIN_INDEX' => 'index.php?pane=right', + ]); - ksort($action_array); + ksort($module); - $row_count = 0; - while (list($action, $file) = each($action_array)) - { - $row_class = !($row_count % 2) ? 'row1' : 'row2'; + foreach ($module as $cat => $action_array) { + $cat = (!empty($lang[$cat])) ? $lang[$cat] : str_replace("_", ' ', $cat); - $action = (!empty($lang[$action])) ? $lang[$action] : preg_replace('/_/', ' ', $action); + $template->assign_block_vars('catrow', [ + 'ADMIN_CATEGORY' => $cat, + ]); - $template->assign_block_vars('catrow.modulerow', array( - 'ROW_CLASS' => $row_class, - 'ADMIN_MODULE' => $action, - 'U_ADMIN_MODULE' => $file, - )); - $row_count++; - } - } -} -elseif (isset($_GET['pane']) && $_GET['pane'] == 'right') -{ - $template->assign_vars(array( - 'TPL_ADMIN_MAIN' => true, - 'ADMIN_LOCK' => ($bb_cfg['board_disable']) ? true : false, - 'ADMIN_LOCK_CRON' => (file_exists(BB_DISABLED)) ? true :false, - )); + ksort($action_array); - // Get forum statistics - $total_posts = get_db_stat('postcount'); - $total_users = get_db_stat('usercount'); - $total_topics = get_db_stat('topiccount'); - $start_date = bb_date($bb_cfg['board_startdate']); - $boarddays = (TIMENOW - $bb_cfg['board_startdate']) / 86400; + $row_count = 0; + foreach ($action_array as $action => $file) { + $row_class = !($row_count % 2) ? 'row1' : 'row2'; - $posts_per_day = sprintf('%.2f', $total_posts / $boarddays); - $topics_per_day = sprintf('%.2f', $total_topics / $boarddays); - $users_per_day = sprintf('%.2f', $total_users / $boarddays); + $action = (!empty($lang[$action])) ? $lang[$action] : str_replace("_", ' ', $action); - $avatar_dir_size = 0; + $template->assign_block_vars('catrow.modulerow', [ + 'ROW_CLASS' => $row_class, + 'ADMIN_MODULE' => $action, + 'U_ADMIN_MODULE' => $file, + ]); + $row_count++; + } + } +} elseif (isset($_GET['pane']) && $_GET['pane'] == 'right') { + $template->assign_vars([ + 'TPL_ADMIN_MAIN' => true, + 'ADMIN_LOCK' => (bool)config()->get('board_disable'), + 'ADMIN_LOCK_CRON' => is_file(BB_DISABLED), + ]); - if ($avatar_dir = @opendir(BB_ROOT . $bb_cfg['avatar_path'])) - { - while( $file = @readdir($avatar_dir) ) - { - if( $file != '.' && $file != '..' ) - { - $avatar_dir_size += @filesize(BB_ROOT . $bb_cfg['avatar_path'] . '/' . $file); - } - } - @closedir($avatar_dir); + // Check for updates + if (isset($update_data['available_update'])) { + $template->assign_block_vars('updater', [ + 'UPDATE_AVAILABLE' => $update_data['available_update'], + 'NEW_VERSION_NUMBER' => $update_data['latest_version'], + 'NEW_VERSION_SIZE' => $update_data['latest_version_size'], + 'NEW_VERSION_DL_LINK' => $update_data['latest_version_dl_link'], + 'NEW_VERSION_LINK' => $update_data['latest_version_link'], + 'NEW_VERSION_HASH' => $update_data['latest_version_checksum'] + ]); + } - $avatar_dir_size = humn_size($avatar_dir_size); - } - else - { - $avatar_dir_size = $lang['NOT_AVAILABLE']; - } + // Get forum statistics + $total_posts = $stats['postcount']; + $total_topics = $stats['topiccount']; + $total_users = $stats['usercount']; + $start_date = bb_date(config()->get('board_startdate')); + $boarddays = (TIMENOW - config()->get('board_startdate')) / 86400; - if (intval($posts_per_day) > $total_posts) - { - $posts_per_day = $total_posts; - } + $posts_per_day = sprintf('%.2f', $total_posts / $boarddays); + $topics_per_day = sprintf('%.2f', $total_topics / $boarddays); + $users_per_day = sprintf('%.2f', $total_users / $boarddays); - if (intval($topics_per_day) > $total_topics) - { - $topics_per_day = $total_topics; - } + $avatar_dir_size = 0; - if ($users_per_day > $total_users) - { - $users_per_day = $total_users; - } + if ($avatar_dir = opendir(config()->get('avatars.upload_path'))) { + while ($file = readdir($avatar_dir)) { + if ($file != '.' && $file != '..') { + $avatar_dir_size += @filesize(config()->get('avatars.upload_path') . $file); + } + } + closedir($avatar_dir); - // DB size ... MySQL only - $sql = "SELECT VERSION() AS mysql_version"; - if ($result = DB()->sql_query($sql)) - { - $row = DB()->sql_fetchrow($result); - $version = $row['mysql_version']; + $avatar_dir_size = humn_size($avatar_dir_size); + } else { + $avatar_dir_size = $lang['NOT_AVAILABLE']; + } - if (preg_match('/^(3\.23|4\.|5\.|10\.)/', $version)) - { - $dblist = array(); - foreach ($bb_cfg['db'] as $name => $row) - { - $sql = "SHOW TABLE STATUS FROM {$row[1]}"; - if ($result = DB()->sql_query($sql)) - { - $tabledata_ary = DB()->sql_fetchrowset($result); + if ((int)$posts_per_day > $total_posts) { + $posts_per_day = $total_posts; + } - $dbsize = 0; - for ($i = 0; $i < count($tabledata_ary); $i++) - { - if( @$tabledata_ary[$i]['Type'] != 'MRG_MYISAM' ) - { - $dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length']; - } - } - $dblist[] = ''. humn_size($dbsize) .''; - } - } - $dbsize = implode(' | ', $dblist); - } - else - { - $dbsize = $lang['NOT_AVAILABLE']; - } - } - else - { - $dbsize = $lang['NOT_AVAILABLE']; - } + if ((int)$topics_per_day > $total_topics) { + $topics_per_day = $total_topics; + } - $template->assign_vars(array( - 'NUMBER_OF_POSTS' => $total_posts, - 'NUMBER_OF_TOPICS' => $total_topics, - 'NUMBER_OF_USERS' => $total_users, - 'START_DATE' => $start_date, - 'POSTS_PER_DAY' => $posts_per_day, - 'TOPICS_PER_DAY' => $topics_per_day, - 'USERS_PER_DAY' => $users_per_day, - 'AVATAR_DIR_SIZE' => $avatar_dir_size, - 'DB_SIZE' => $dbsize, - 'GZIP_COMPRESSION' => ($bb_cfg['gzip_compress']) ? $lang['ON'] : $lang['OFF'], - )); + if ($users_per_day > $total_users) { + $users_per_day = $total_users; + } - if (@$_GET['users_online']) - { - $template->assign_vars(array( - 'SHOW_USERS_ONLINE' => true, - )); + $template->assign_vars([ + 'NUMBER_OF_POSTS' => $total_posts, + 'NUMBER_OF_TOPICS' => $total_topics, + 'NUMBER_OF_USERS' => $total_users, + 'START_DATE' => $start_date, + 'POSTS_PER_DAY' => $posts_per_day, + 'TOPICS_PER_DAY' => $topics_per_day, + 'USERS_PER_DAY' => $users_per_day, + 'AVATAR_DIR_SIZE' => $avatar_dir_size, + ]); - // Get users online information. - $sql = "SELECT u.user_id, u.username, u.user_rank, s.session_time AS user_session_time, u.user_opt, s.session_logged_in, s.session_ip, s.session_start - FROM " . BB_USERS . " u, " . BB_SESSIONS . " s + if (isset($_GET['users_online'])) { + $template->assign_vars([ + 'SHOW_USERS_ONLINE' => true, + ]); + + // Get users online information. + $sql = 'SELECT u.user_id, u.username, u.user_rank, s.session_time AS user_session_time, u.user_opt, s.session_logged_in, s.session_ip, s.session_start + FROM ' . BB_USERS . ' u, ' . BB_SESSIONS . ' s WHERE s.session_logged_in = 1 AND u.user_id = s.session_user_id - AND u.user_id <> " . GUEST_UID . " - AND s.session_time >= " . ( TIMENOW - 300 ) . " - ORDER BY s.session_ip ASC, s.session_time DESC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain reged user / online information'); - } - $onlinerow_reg = DB()->sql_fetchrowset($result); + AND u.user_id <> ' . GUEST_UID . ' + AND s.session_time >= ' . (TIMENOW - 300) . ' + ORDER BY s.session_ip ASC, s.session_time DESC'; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain reged user / online information'); + } + $onlinerow_reg = DB()->sql_fetchrowset($result); - $sql = "SELECT session_logged_in, session_time, session_ip, session_start - FROM " . BB_SESSIONS . " + // Get guests online information. + $sql = 'SELECT session_logged_in, session_time, session_ip, session_start + FROM ' . BB_SESSIONS . ' WHERE session_logged_in = 0 - AND session_time >= " . ( TIMENOW - 300 ) . " - ORDER BY session_ip ASC, session_time DESC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain guest user / online information'); - } - $onlinerow_guest = DB()->sql_fetchrowset($result); + AND session_time >= ' . (TIMENOW - 300) . ' + ORDER BY session_ip ASC, session_time DESC'; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain guest user / online information'); + } + $onlinerow_guest = DB()->sql_fetchrowset($result); - $reg_userid_ary = array(); + // Reg users + if (count($onlinerow_reg)) { + $users_count = 0; - if (count($onlinerow_reg)) - { - $registered_users = $hidden_users = 0; + for ($i = 0, $iMax = count($onlinerow_reg); $i < $iMax; $i++) { + $users_count++; + $row_class = 'row1'; + $reg_ip = \TorrentPier\Helpers\IPHelper::long2ip_extended($onlinerow_reg[$i]['session_ip']); - for ($i = 0, $cnt = count($onlinerow_reg); $i < $cnt; $i++) - { - if (!in_array($onlinerow_reg[$i]['user_id'], $reg_userid_ary)) - { - $reg_userid_ary[] = $onlinerow_reg[$i]['user_id']; + $template->assign_block_vars('reg_user_row', [ + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($onlinerow_reg[$i], true), + 'STARTED' => bb_date($onlinerow_reg[$i]['session_start'], 'd-M-Y H:i', false), + 'LASTUPDATE' => bb_date($onlinerow_reg[$i]['user_session_time'], 'd-M-Y H:i', false), + 'IP_ADDRESS' => $reg_ip, + 'U_WHOIS_IP' => config()->get('whois_info') . $reg_ip, + ]); + } + } - $username = $onlinerow_reg[$i]['username']; + // Guest users + if (count($onlinerow_guest)) { + $guest_users = 0; - if (bf($onlinerow_reg[$i]['user_opt'], 'user_opt', 'user_viewonline')) - { - $hidden_users++; - $hidden = TRUE; - } - else - { - $registered_users++; - $hidden = FALSE; - } + for ($i = 0, $iMax = count($onlinerow_guest); $i < $iMax; $i++) { + $guest_users++; + $row_class = 'row2'; + $guest_ip = \TorrentPier\Helpers\IPHelper::long2ip_extended($onlinerow_guest[$i]['session_ip']); - $row_class = 'row1'; - - $reg_ip = decode_ip($onlinerow_reg[$i]['session_ip']); - - $template->assign_block_vars('reg_user_row', array( - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($onlinerow_reg[$i]), - 'STARTED' => bb_date($onlinerow_reg[$i]['session_start'], 'H:i', false), - 'LASTUPDATE' => bb_date($onlinerow_reg[$i]['user_session_time'], 'H:i', false), - 'IP_ADDRESS' => $reg_ip, - 'U_WHOIS_IP' => $bb_cfg['whois_info'] . $reg_ip, - )); - } - } - } - - // Guest users - if (count($onlinerow_guest)) - { - $guest_users = 0; - - for ($i = 0; $i < count($onlinerow_guest); $i++) - { - $guest_userip_ary[] = $onlinerow_guest[$i]['session_ip']; - $guest_users++; - - $row_class = 'row2'; - - $guest_ip = decode_ip($onlinerow_guest[$i]['session_ip']); - - $template->assign_block_vars('guest_user_row', array( - 'ROW_CLASS' => $row_class, - 'STARTED' => bb_date($onlinerow_guest[$i]['session_start'], 'H:i', false), - 'LASTUPDATE' => bb_date($onlinerow_guest[$i]['session_time'], 'H:i' , false), - 'IP_ADDRESS' => $guest_ip, - 'U_WHOIS_IP' => $bb_cfg['whois_info'] . $guest_ip, - )); - } - } - } - else - { - $template->assign_vars(array( - 'USERS_ONLINE_HREF' => 'index.php?pane=right&users_online=1', - )); - } -} -else -{ - // Generate frameset - $template->assign_vars(array( - 'TPL_ADMIN_FRAMESET' => true, - )); - send_no_cache_headers(); - print_page('index.tpl', 'admin', 'no_header'); + $template->assign_block_vars('guest_user_row', [ + 'ROW_CLASS' => $row_class, + 'STARTED' => bb_date($onlinerow_guest[$i]['session_start'], 'd-M-Y H:i', false), + 'LASTUPDATE' => bb_date($onlinerow_guest[$i]['session_time'], 'd-M-Y H:i', false), + 'IP_ADDRESS' => $guest_ip, + 'U_WHOIS_IP' => config()->get('whois_info') . $guest_ip, + ]); + } + } + } else { + $template->assign_vars([ + 'USERS_ONLINE_HREF' => 'index.php?pane=right&users_online=1', + ]); + } +} else { + // Generate frameset + $template->assign_vars([ + 'CONTENT_ENCODING' => DEFAULT_CHARSET, + 'TPL_ADMIN_FRAMESET' => true, + ]); + send_no_cache_headers(); + print_page('index.tpl', 'admin', 'no_header'); } print_page('index.tpl', 'admin'); - -// Functions -function inarray ($needle, $haystack) -{ - for ($i = 0; $i < sizeof($haystack); $i++) - { - if ($haystack[$i] == $needle) - { - return true; - } - } - return false; -} \ No newline at end of file diff --git a/admin/pagestart.php b/admin/pagestart.php index 40449b461..e9f0378fd 100644 --- a/admin/pagestart.php +++ b/admin/pagestart.php @@ -1,28 +1,30 @@ session_start(); -if (IS_GUEST) -{ - redirect(LOGIN_URL . "?redirect=admin/index.php"); +if (IS_GUEST) { + redirect(LOGIN_URL . '?redirect=admin/index.php'); } -if (!IS_ADMIN) -{ - bb_die($lang['NOT_ADMIN']); +if (!IS_ADMIN) { + bb_die($lang['NOT_ADMIN']); } -if (!$userdata['session_admin']) -{ - $redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1); - redirect("login.php?redirect=$redirect"); -} \ No newline at end of file +if (!$userdata['session_admin']) { + $redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1); + redirect(LOGIN_URL . "?redirect=$redirect"); +} diff --git a/admin/stats/tr_stats.php b/admin/stats/tr_stats.php index 4655acff6..db1fc444d 100644 --- a/admin/stats/tr_stats.php +++ b/admin/stats/tr_stats.php @@ -1,48 +1,46 @@ session_start(); -if (!IS_ADMIN) bb_die($lang['NOT_AUTHORISED']); +if (!IS_ADMIN) { + bb_die($lang['NOT_AUTHORISED']); +} -$sql[] = 'SELECT count(*) FROM `'.BB_USERS.'` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-2592000'; -$sql[] = 'SELECT count(*) FROM `'.BB_USERS.'` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-7776000'; -$sql[] = 'SELECT round(avg(size)/1048576) FROM `'.BB_BT_TORRENTS.'`'; -$sql[] = 'SELECT count(*) FROM `'.BB_BT_TORRENTS.'`'; -$sql[] = 'SELECT count(distinct(topic_id)) FROM `'.BB_BT_TRACKER_SNAP.'` WHERE seeders > 0'; -$sql[] = 'SELECT count(distinct(topic_id)) FROM `'.BB_BT_TRACKER_SNAP.'` WHERE seeders > 5'; -$sql[] = 'SELECT count(distinct(poster_id)) FROM `'.BB_BT_TORRENTS.'`'; -$sql[] = 'SELECT count(distinct(poster_id)) FROM `'.BB_BT_TORRENTS.'` WHERE reg_time >= UNIX_TIMESTAMP()-2592000'; +$sql[] = 'SELECT count(*) FROM `' . BB_USERS . '` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-2592000 AND user_id NOT IN (' . EXCLUDED_USERS . ')'; +$sql[] = 'SELECT count(*) FROM `' . BB_USERS . '` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-7776000 AND user_id NOT IN (' . EXCLUDED_USERS . ')'; +$sql[] = 'SELECT round(avg(size)) FROM `' . BB_BT_TORRENTS . '`'; +$sql[] = 'SELECT count(*) FROM `' . BB_BT_TORRENTS . '`'; +$sql[] = 'SELECT count(distinct(topic_id)) FROM `' . BB_BT_TRACKER_SNAP . '` WHERE seeders > 0'; +$sql[] = 'SELECT count(distinct(topic_id)) FROM `' . BB_BT_TRACKER_SNAP . '` WHERE seeders > 5'; +$sql[] = 'SELECT count(distinct(poster_id)) FROM `' . BB_BT_TORRENTS . '`'; +$sql[] = 'SELECT count(distinct(poster_id)) FROM `' . BB_BT_TORRENTS . '` WHERE reg_time >= UNIX_TIMESTAMP()-2592000'; echo ''; -echo ' -

-'; +echo '

'; -foreach ($sql as $i => $query) -{ - $row = mysql_fetch_row(DB()->query($query)); - echo ""; +foreach ($sql as $i => $query) { + $result = DB()->fetch_row($query); + $row = array_values($result)[0]; // Get first column value + $row = ($i == 2) ? humn_size($row) : $row; + echo ""; } echo '
{$lang['TR_STATS'][$i]}{$row[0]}
{$lang['TR_STATS'][$i]}$row
'; - echo '
';
 
-if ($l = sys('la'))
-{
-	$l = explode(' ', $l);
-	for ($i=0; $i < 3; $i++)
-	{
-		$l[$i] = round($l[$i], 1);
-	}
-	echo "\n\nloadavg: $l[0] $l[1] $l[2]\n\n";
-}
-
-echo 'gen time: '. sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) ." sec\n";
+echo 'gen time: ' . sprintf('%.3f', array_sum(explode(' ', microtime())) - TIMESTART) . " sec\n";
 
 echo '
'; -echo ''; \ No newline at end of file +echo ''; diff --git a/admin/stats/tracker.php b/admin/stats/tracker.php index 69d9922d8..677373d78 100644 --- a/admin/stats/tracker.php +++ b/admin/stats/tracker.php @@ -1,90 +1,139 @@ session_start(); -if (!IS_ADMIN) bb_die($lang['NOT_AUTHORISED']); +if (!IS_ADMIN) { + bb_die($lang['NOT_AUTHORISED']); +} -$peers_in_last_minutes = array(30, 15, 5, 1); +$peers_in_last_minutes = [30, 15, 5, 1]; $peers_in_last_sec_limit = 300; -$announce_interval = intval($bb_cfg['announce_interval']); -$stat = array(); +$announce_interval = (int)config()->get('announce_interval'); +$stat = []; define('TMP_TRACKER_TABLE', 'tmp_tracker'); -DB()->query(" - CREATE TEMPORARY TABLE ". TMP_TRACKER_TABLE ." ( +DB()->query(' + CREATE TEMPORARY TABLE ' . TMP_TRACKER_TABLE . " ( `topic_id` mediumint(8) unsigned NOT NULL default '0', `user_id` mediumint(9) NOT NULL default '0', - `ip` char(8) binary NOT NULL default '0', + `ip` char(42) binary default '0', + `ipv6` char(42) binary default '0', + `peer_id` char(20) binary default '0', `seeder` tinyint(1) NOT NULL default '0', `speed_up` mediumint(8) unsigned NOT NULL default '0', `speed_down` mediumint(8) unsigned NOT NULL default '0', `update_time` int(11) NOT NULL default '0' ) SELECT - topic_id, user_id, ip, seeder, speed_up, speed_down, update_time - FROM ". BB_BT_TRACKER ." -"); + topic_id, user_id, ip, ipv6, peer_id, seeder, speed_up, speed_down, update_time + FROM " . BB_BT_TRACKER . ' +'); // Peers within announce interval -$stat += DB()->fetch_row("SELECT COUNT(*) AS p_within_ann FROM ". TMP_TRACKER_TABLE ." WHERE update_time >= ". (TIMENOW - $announce_interval)); +$stat += DB()->fetch_row('SELECT COUNT(*) AS p_within_ann FROM ' . TMP_TRACKER_TABLE . ' WHERE update_time >= ' . (TIMENOW - $announce_interval)); // All peers, "max_peer_time" -$stat += DB()->fetch_row("SELECT COUNT(*) AS p_all, SUM(speed_up) as speed_up, SUM(speed_down) as speed_down, UNIX_TIMESTAMP() - MIN(update_time) AS max_peer_time, UNIX_TIMESTAMP() - MAX(update_time) AS last_peer_time FROM ". TMP_TRACKER_TABLE); - +$stat += DB()->fetch_row('SELECT COUNT(*) AS p_all, SUM(speed_up) as speed_up, SUM(speed_down) as speed_down, UNIX_TIMESTAMP() - MIN(update_time) AS max_peer_time, UNIX_TIMESTAMP() - MAX(update_time) AS last_peer_time FROM ' . TMP_TRACKER_TABLE); // Active users -$stat += DB()->fetch_row("SELECT COUNT(DISTINCT user_id) AS u_bt_active FROM ". TMP_TRACKER_TABLE); +$stat += DB()->fetch_row('SELECT COUNT(DISTINCT user_id) AS u_bt_active FROM ' . TMP_TRACKER_TABLE); // All bt-users -$stat += DB()->fetch_row("SELECT COUNT(*) AS u_bt_all FROM ". BB_BT_USERS); +$stat += DB()->fetch_row('SELECT COUNT(*) AS u_bt_all FROM ' . BB_BT_USERS); // All bb-users -$stat += DB()->fetch_row("SELECT COUNT(*) AS u_bb_all FROM ". BB_USERS); - +$stat += DB()->fetch_row('SELECT COUNT(*) AS u_bb_all FROM ' . BB_USERS . ' WHERE user_id != ' . BOT_UID); // Active torrents -$stat += DB()->fetch_row("SELECT COUNT(DISTINCT topic_id) AS tor_active FROM ". TMP_TRACKER_TABLE); +$stat += DB()->fetch_row('SELECT COUNT(DISTINCT topic_id) AS tor_active FROM ' . TMP_TRACKER_TABLE); // With seeder -$stat += DB()->fetch_row("SELECT COUNT(DISTINCT topic_id) AS tor_with_seeder FROM ". TMP_TRACKER_TABLE ." WHERE seeder = 1"); +$stat += DB()->fetch_row('SELECT COUNT(DISTINCT topic_id) AS tor_with_seeder FROM ' . TMP_TRACKER_TABLE . ' WHERE seeder = 1'); // All torrents -$stat += DB()->fetch_row("SELECT COUNT(*) AS tor_all, SUM(size) AS torrents_size FROM ". BB_BT_TORRENTS); +$stat += DB()->fetch_row('SELECT COUNT(*) AS tor_all, SUM(size) AS torrents_size FROM ' . BB_BT_TORRENTS); // Last xx minutes -$peers_in_last_min = array(); -foreach ($peers_in_last_minutes as $t) -{ - $row = DB()->fetch_row(" - SELECT COUNT(*) AS peers FROM ". TMP_TRACKER_TABLE ." WHERE update_time >= ". (TIMENOW - 60*$t) ." - "); - $peers_in_last_min[$t] = (int) $row['peers']; +$peers_in_last_min = []; +foreach ($peers_in_last_minutes as $t) { + $row = DB()->fetch_row(' + SELECT COUNT(*) AS peers FROM ' . TMP_TRACKER_TABLE . ' WHERE update_time >= ' . (TIMENOW - 60 * $t) . ' + '); + $peers_in_last_min[$t] = (int)$row['peers']; } // Last xx seconds -$peers_in_last_sec = array(); -$rowset = DB()->fetch_rowset("SELECT COUNT(*) AS peers FROM ". TMP_TRACKER_TABLE ." GROUP BY update_time DESC LIMIT $peers_in_last_sec_limit"); -foreach ($rowset as $cnt => $row) -{ - $peers_in_last_sec[] = sprintf('%3s', $row['peers']) . (($cnt && !(++$cnt%15)) ? " \n" : ''); +$peers_in_last_sec = []; +$rowset = DB()->fetch_rowset('SELECT COUNT(*) AS peers FROM ' . TMP_TRACKER_TABLE . ' ORDER BY update_time DESC LIMIT ' . $peers_in_last_sec_limit); +foreach ($rowset as $cnt => $row) { + $peers_in_last_sec[] = sprintf('%3s', $row['peers']) . (($cnt && !(++$cnt % 15)) ? " \n" : ''); } -function commify_callback ($matches) -{ - return commify($matches[0]); +// Detailed statistics for peer clients + +$client_list = ''; +$clients_percentage = []; +$numwant = !empty($_GET['client_numwant']) ? (int)$_GET['client_numwant'] : 100; +$client_full = !empty($_GET['client_length']) ? (int)$_GET['client_length'] : false; + +if ($client_full || !$stats_cache = CACHE('tr_cache')->get('tracker_clients_stats')) { + + $rowset = DB()->fetch_rowset('SELECT peer_id AS client FROM ' . TMP_TRACKER_TABLE); + + if (!empty($rowset)) { + + $client_count = 0; + + foreach ($rowset as $cnt => $row) { + $clientString = $client_full ? substr($row['client'], 0, $client_full) : substr($row['client'], 0, 3); + if (!isset($clients[$clientString])) { + $clients[$clientString] = 1; + } else { + $clients[$clientString]++; + } + $client_count++; + } + + arsort($clients, SORT_NUMERIC); + foreach ($clients as $client => $count) { + $percentage = number_format(($count / $client_count) * 100, 2); + $clients_percentage[$client] = "[$count] => $percentage%"; + } + + if (!$client_full) { + CACHE('tr_cache')->set('tracker_clients_stats', $clients_percentage, 3600); + } + } +} else { + $clients_percentage = $stats_cache; } -function commify_ob ($contents) -{ - return preg_replace_callback("#\b\d+\b#", 'commify_callback', $contents); + +$n = 1; +foreach (array_slice($clients_percentage, 0, $numwant) as $client => $value) { + $client_list .= ($client_full) ? ("$client => $value
") : "$n. " . get_user_torrent_client($client) . " $value
"; + $n++; } + +function commify_callback($matches) +{ + return commify($matches[0]); +} + +function commify_ob($contents) +{ + return preg_replace_callback("#\b\d+\b#", 'commify_callback', $contents); +} + ob_start('commify_ob'); echo ''; -echo ' -

- ---'; - +echo '

'; echo "\n\n"; echo "\n @@ -92,7 +141,7 @@ echo "\n \n"; @@ -101,36 +150,33 @@ echo "\n \n"; -echo "\n\n"; -echo "\n\n"; - -echo "\n\n"; -echo '\n"; +echo "\n\n"; +echo "\n\n"; +echo "\n\n"; +echo '\n"; +echo "\n + + '; echo '
users: bb-all / bt-all / bt-active $stat[u_bb_all] / $stat[u_bt_all] / $stat[u_bt_active]
$stat[tor_all] / $stat[tor_active] / $stat[tor_with_seeder]   - [ ". humn_size($stat['torrents_size']) ." ] + [ " . humn_size($stat['torrents_size']) . " ]
$stat[p_all] / $stat[p_within_ann]   - [ up: ". humn_size($stat['speed_up']) ."/s, - down: ". humn_size($stat['speed_down']) ."/s ] + [ up: " . humn_size($stat['speed_up']) . '/s, + down: ' . humn_size($stat['speed_down']) . "/s ]
peers: in last ". join(' / ', $peers_in_last_minutes) ." min". join(' / ', $peers_in_last_min) ."
peers in last $peers_in_last_sec_limit sec
[ per second, DESC order --> ]
last peer: $stat[last_peer_time] seconds ago
". date("j M H:i:s [T O]") ."
 '. join(' ', $peers_in_last_sec) ."
peers: in last " . implode(' / ', $peers_in_last_minutes) . " min" . implode(' / ', $peers_in_last_min) . "
peers in last $peers_in_last_sec_limit sec
[ per second, DESC order --> ]
last peer: $stat[last_peer_time] seconds ago
" . date('j M H:i:s [T O]') . "
 ' . implode(' ', $peers_in_last_sec) . "
clients: + $client_list +
+\n"; +echo (count($clients_percentage) > $numwant) ? ('' . 'Show more' . '
') : ''; +echo $client_full ? '
Get more length and numbers via modifying the parameters in the url' : (!empty($client_list) ? 'Peer_ids with more length (version debugging)' : ''); +echo '
'; - +echo !$client_full ? '

Simple stats for clients are being cached for one hour.

' : ''; echo '
';
 
-if ($l = sys('la'))
-{
-	$l = explode(' ', $l);
-	for ($i=0; $i < 3; $i++)
-	{
-		$l[$i] = round($l[$i], 1);
-	}
-	echo "\n\nloadavg: $l[0] $l[1] $l[2]\n\n";
-}
-
-echo 'gen time: '. sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) ." sec\n";
-
+echo 'gen time: ' . sprintf('%.3f', array_sum(explode(' ', microtime())) - TIMESTART) . " sec\n";
 echo '
'; echo ''; -DB()->query("DROP TEMPORARY TABLE ". TMP_TRACKER_TABLE); +DB()->query('DROP TEMPORARY TABLE ' . TMP_TRACKER_TABLE); -bb_exit(); \ No newline at end of file +exit(); diff --git a/ajax.php b/ajax.php index 0f40f474d..abe638c8e 100644 --- a/ajax.php +++ b/ajax.php @@ -1,428 +1,45 @@ init(); // Init userdata $user->session_start(); -// Exit if board is disabled via ON/OFF trigger or by admin -if ($ajax->action != 'manage_admin') -{ - if ($bb_cfg['board_disable']) - { - $ajax->ajax_die($lang['BOARD_DISABLE']); - } - else if (file_exists(BB_DISABLED)) - { - $ajax->ajax_die($lang['BOARD_DISABLE_CRON']); - } -} - // Load actions required modules -switch ($ajax->action) -{ - case 'view_post': - require(INC_DIR . 'bbcode.php'); - break; +switch ($ajax->action) { + case 'view_post': + case 'posts': + case 'post_mod_comment': + require INC_DIR . '/bbcode.php'; + break; - case 'posts': - case 'post_mod_comment': - require(INC_DIR . 'bbcode.php'); - require(INC_DIR . 'functions_post.php'); - require(INC_DIR . 'functions_admin.php'); - break; - - case 'view_torrent': - case 'mod_action': - case 'change_tor_status': - case 'gen_passkey': - require(ATTACH_DIR . 'attachment_mod.php'); - require(INC_DIR . 'functions_torrent.php'); - break; - - case 'change_torrent': - require(ATTACH_DIR . 'attachment_mod.php'); - require(INC_DIR . 'functions_torrent.php'); - break; - - case 'user_register': - require(INC_DIR . 'functions_validate.php'); - break; - - case 'manage_user': - case 'manage_admin': - require(INC_DIR . 'functions_admin.php'); - break; - - case 'group_membership': - case 'manage_group': - require(INC_DIR . 'functions_group.php'); - break; - - case 'sitemap'; - require(CLASS_DIR .'sitemap.php'); - break; + case 'view_torrent': + case 'mod_action': + case 'change_tor_status': + case 'change_torrent': + case 'passkey': + require ATTACH_DIR . '/attachment_mod.php'; + break; } -// Position in $ajax->valid_actions['xxx'] -define('AJAX_AUTH', 0); // 'guest', 'user', 'mod', 'admin', 'super_admin' - $ajax->exec(); -// -// Ajax -// -class ajax_common -{ - var $request = array(); - var $response = array(); - - var $valid_actions = array( - // ACTION NAME AJAX_AUTH - 'edit_user_profile' => array('admin'), - 'change_user_rank' => array('admin'), - 'change_user_opt' => array('admin'), - 'manage_user' => array('admin'), - 'manage_admin' => array('admin'), - 'sitemap' => array('admin'), - - 'mod_action' => array('mod'), - 'topic_tpl' => array('mod'), - 'group_membership' => array('mod'), - 'post_mod_comment' => array('mod'), - - 'avatar' => array('user'), - 'gen_passkey' => array('user'), - 'change_torrent' => array('user'), - 'change_tor_status' => array('user'), - 'manage_group' => array('user'), - - 'view_post' => array('guest'), - 'view_torrent' => array('guest'), - 'user_register' => array('guest'), - 'posts' => array('guest'), - 'index_data' => array('guest'), - ); - - var $action = null; - - /** - * Constructor - */ - function ajax_common() - { - ob_start(array(&$this, 'ob_handler')); - header('Content-Type: text/plain'); - } - - /** - * Perform action - */ - function exec() - { - global $lang; - - // Exit if we already have errors - if (!empty($this->response['error_code'])) - { - $this->send(); - } - - // Check that requested action is valid - $action = $this->action; - - if (!$action || !is_string($action)) - { - $this->ajax_die('no action specified'); - } - elseif (!$action_params =& $this->valid_actions[$action]) - { - $this->ajax_die('invalid action: ' . $action); - } - - // Auth check - switch ($action_params[AJAX_AUTH]) - { - // GUEST - case 'guest': - break; - - // USER - case 'user': - if (IS_GUEST) - { - $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); - } - break; - - // MOD - case 'mod': - if (!IS_AM) - { - $this->ajax_die($lang['ONLY_FOR_MOD']); - } - $this->check_admin_session(); - break; - - // ADMIN - case 'admin': - if (!IS_ADMIN) - { - $this->ajax_die($lang['ONLY_FOR_ADMIN']); - } - $this->check_admin_session(); - break; - - // SUPER_ADMIN - case 'super_admin': - if (!IS_SUPER_ADMIN) - { - $this->ajax_die($lang['ONLY_FOR_SUPER_ADMIN']); - } - $this->check_admin_session(); - break; - - default: - trigger_error("invalid auth type for $action", E_USER_ERROR); - } - - // Run action - $this->$action(); - - // Send output - $this->send(); - } - - /** - * Exit on error - */ - function ajax_die($error_msg, $error_code = E_AJAX_GENERAL_ERROR) - { - $this->response['error_code'] = $error_code; - $this->response['error_msg'] = $error_msg; - - $this->send(); - } - - /** - * Initialization - */ - function init() - { - $this->request = $_POST; - $this->action =& $this->request['action']; - } - - /** - * Send data - */ - function send() - { - $this->response['action'] = $this->action; - - if (DBG_USER && SQL_DEBUG && !empty($_COOKIE['sql_log'])) - { - $this->response['sql_log'] = get_sql_log(); - } - - // sending output will be handled by $this->ob_handler() - exit(); - } - - /** - * OB Handler - */ - function ob_handler($contents) - { - if (DBG_USER) - { - if ($contents) - { - $this->response['raw_output'] = $contents; - } - } - - $response_js = bb_json_encode($this->response); - - if (GZIP_OUTPUT_ALLOWED && !defined('NO_GZIP')) - { - if (UA_GZIP_SUPPORTED && strlen($response_js) > 2000) - { - header('Content-Encoding: gzip'); - $response_js = gzencode($response_js, 1); - } - } - - return $response_js; - } - - /** - * Admin session - */ - function check_admin_session() - { - global $user; - - if (!$user->data['session_admin']) - { - if (empty($this->request['user_password'])) - { - $this->prompt_for_password(); - } - else - { - $login_args = array( - 'login_username' => $user->data['username'], - 'login_password' => $_POST['user_password'], - ); - if (!$user->login($login_args, true)) - { - $this->ajax_die('Wrong password'); - } - } - } - } - - /** - * Prompt for password - */ - function prompt_for_password() - { - $this->response['prompt_password'] = 1; - $this->send(); - } - - /** - * Prompt for confirmation - */ - function prompt_for_confirm($confirm_msg) - { - if (empty($confirm_msg)) $this->ajax_die('false'); - - $this->response['prompt_confirm'] = 1; - $this->response['confirm_msg'] = $confirm_msg; - $this->send(); - } - - /** - * Verify mod rights - */ - function verify_mod_rights($forum_id) - { - global $userdata, $lang; - - $is_auth = auth(AUTH_MOD, $forum_id, $userdata); - - if (!$is_auth['auth_mod']) - { - $this->ajax_die($lang['ONLY_FOR_MOD']); - } - } - - function edit_user_profile() - { - require(AJAX_DIR . 'edit_user_profile.php'); - } - - function change_user_rank() - { - require(AJAX_DIR . 'change_user_rank.php'); - } - - function change_user_opt() - { - require(AJAX_DIR . 'change_user_opt.php'); - } - - function gen_passkey() - { - require(AJAX_DIR . 'gen_passkey.php'); - } - - function group_membership() - { - require(AJAX_DIR . 'group_membership.php'); - } - - function manage_group() - { - require(AJAX_DIR . 'edit_group_profile.php'); - } - - function post_mod_comment() - { - require(AJAX_DIR . 'post_mod_comment.php'); - } - - function view_post() - { - require(AJAX_DIR . 'view_post.php'); - } - - function change_tor_status() - { - require(AJAX_DIR . 'change_tor_status.php'); - } - - function change_torrent() - { - require(AJAX_DIR . 'change_torrent.php'); - } - - function view_torrent() - { - require(AJAX_DIR . 'view_torrent.php'); - } - - function user_register() - { - require(AJAX_DIR . 'user_register.php'); - } - - function mod_action() - { - require(AJAX_DIR . 'mod_action.php'); - } - - function posts() - { - require(AJAX_DIR . 'posts.php'); - } - - function manage_user() - { - require(AJAX_DIR . 'manage_user.php'); - } - - function manage_admin() - { - require(AJAX_DIR . 'manage_admin.php'); - } - - function topic_tpl() - { - require(AJAX_DIR . 'topic_tpl.php'); - } - - function index_data() - { - require(AJAX_DIR . 'index_data.php'); - } - - function avatar() - { - require(AJAX_DIR . 'avatar.php'); - } - - function sitemap() - { - require(AJAX_DIR .'sitemap.php'); - } -} \ No newline at end of file +/** + * @deprecated ajax_common + * Dirty class removed from here since 2.2.0 + * To add new actions see at src/Ajax.php + */ diff --git a/bt/announce.php b/bt/announce.php index 70fc72331..3c74e554f 100644 --- a/bt/announce.php +++ b/bt/announce.php @@ -1,348 +1,374 @@ get('announce_interval'); +$passkey_key = config()->get('passkey_key'); // Recover info_hash -if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) -{ - $_GET['info_hash'] = $_GET['?info_hash']; +if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) { + $_GET['info_hash'] = $_GET['?info_hash']; } // Initial request verification -if (strpos($_SERVER['REQUEST_URI'], 'scrape') !== false) -{ - msg_die('Please disable SCRAPE!'); +if (str_contains($_SERVER['REQUEST_URI'], 'scrape')) { + msg_die('Please disable SCRAPE!'); } -if (!isset($_GET[$passkey_key]) || !is_string($_GET[$passkey_key]) || strlen($_GET[$passkey_key]) != BT_AUTH_KEY_LENGTH) -{ - msg_die('Please LOG IN and REDOWNLOAD this torrent (passkey not found)'); + +if (!isset($_GET[$passkey_key]) || !is_string($_GET[$passkey_key])) { + msg_die('Please LOG IN and RE-DOWNLOAD this torrent (passkey not found)'); } // Input var names // String -$input_vars_str = array( - 'info_hash', - 'peer_id', - 'event', - $passkey_key, -); +$input_vars_str = ['info_hash', 'peer_id', 'event', $passkey_key]; // Numeric -$input_vars_num = array( - 'port', - 'uploaded', - 'downloaded', - 'left', - 'numwant', - 'compact', -); +$input_vars_num = ['port', 'uploaded', 'downloaded', 'left', 'numwant', 'compact']; // Init received data // String -foreach ($input_vars_str as $var_name) -{ - $$var_name = isset($_GET[$var_name]) ? (string) $_GET[$var_name] : null; +foreach ($input_vars_str as $var_name) { + $$var_name = isset($_GET[$var_name]) ? (string)$_GET[$var_name] : null; } + // Numeric -foreach ($input_vars_num as $var_name) -{ - $$var_name = isset($_GET[$var_name]) ? (float) $_GET[$var_name] : null; +foreach ($input_vars_num as $var_name) { + $$var_name = isset($_GET[$var_name]) ? (float)$_GET[$var_name] : null; } + // Passkey -$passkey = isset($$passkey_key) ? $$passkey_key : null; +$passkey = $$passkey_key ?? null; // Verify request // Required params (info_hash, peer_id, port, uploaded, downloaded, left, passkey) -if (!isset($info_hash) || strlen($info_hash) != 20) -{ - msg_die('Invalid info_hash'); +if (!isset($peer_id)) { + msg_die('peer_id was not provided'); } -if (!isset($peer_id) || strlen($peer_id) != 20) -{ - msg_die('Invalid peer_id'); +if (strlen($peer_id) !== 20) { + msg_die('Invalid peer_id: ' . $peer_id); } -if (!isset($port) || $port < 0 || $port > 0xFFFF) -{ - msg_die('Invalid port'); + +// Check for client ban +if (config()->get('client_ban.enabled')) { + $targetClient = []; + + foreach (config()->get('client_ban.clients') as $clientId => $banReason) { + if (str_starts_with($peer_id, $clientId)) { + $targetClient = [ + 'peer_id' => $clientId, + 'ban_reason' => $banReason + ]; + break; + } + } + + if (config()->get('client_ban.only_allow_mode')) { + if (empty($targetClient['peer_id'])) { + msg_die('Your BitTorrent client has been banned!'); + } + } else { + if (!empty($targetClient['peer_id'])) { + msg_die(empty($targetClient['ban_reason']) ? 'Your BitTorrent client has been banned!' : $targetClient['ban_reason']); + } + } } -if (!isset($uploaded) || $uploaded < 0 || $uploaded > $max_up_down_val || $uploaded == 1844674407370) -{ - msg_die('Invalid uploaded value'); + +// Verify info_hash +if (!isset($info_hash)) { + msg_die('info_hash was not provided'); } -if (!isset($downloaded) || $downloaded < 0 || $downloaded > $max_up_down_val || $downloaded == 1844674407370) -{ - msg_die('Invalid downloaded value'); + +/** + * Verify event + * + * @see https://github.com/HDInnovations/UNIT3D-Community-Edition/blob/c64275f0b5dcb3c4c845d5204871adfe24f359d6/app/Http/Controllers/AnnounceController.php#L275 + */ +$event = strtolower((string)$event); +if (!in_array($event, ['started', 'completed', 'stopped', 'paused', ''])) { + msg_die('Invalid event: ' . $event); } -if (!isset($left) || $left < 0 || $left > $max_left_val) -{ - msg_die('Invalid left value'); + +// Store info hash in hex format +$info_hash_hex = bin2hex($info_hash); + +// Store peer id +$peer_id_sql = preg_replace('/[^a-zA-Z0-9\-\_]/', '', $peer_id); + +// Stopped event +$stopped = ($event === 'stopped'); + +// Check info_hash length +if (strlen($info_hash) !== 20) { + msg_die('Invalid info_hash: ' . (mb_check_encoding($info_hash, DEFAULT_CHARSET) ? $info_hash : $info_hash_hex)); } -if (!verify_id($passkey, BT_AUTH_KEY_LENGTH)) -{ - msg_die('Invalid passkey'); + +/** + * Block system-reserved ports since 99.9% of the time they're fake and thus not connectable + * Some clients will send port of 0 on 'stopped' events. Let them through as they won't receive peers anyway. + * + * @see https://github.com/HDInnovations/UNIT3D-Community-Edition/blob/c64275f0b5dcb3c4c845d5204871adfe24f359d6/app/Http/Controllers/AnnounceController.php#L284 + */ +if ( + !isset($port) + || !is_numeric($port) + || ($port < 1024 && !$stopped) + || $port > 0xFFFF + || (!empty(config()->get('disallowed_ports')) && in_array($port, config()->get('disallowed_ports'))) +) { + msg_die('Invalid port: ' . $port); +} + +if (!isset($uploaded) || !is_numeric($uploaded) || $uploaded < 0) { + msg_die('Invalid uploaded value: ' . $uploaded); +} + +if (!isset($downloaded) || !is_numeric($downloaded) || $downloaded < 0) { + msg_die('Invalid downloaded value: ' . $downloaded); +} + +if (!isset($left) || !is_numeric($left) || $left < 0) { + msg_die('Invalid left value: ' . $left); +} + +/** + * Check User-Agent length + * + * @see https://github.com/HDInnovations/UNIT3D-Community-Edition/blob/c64275f0b5dcb3c4c845d5204871adfe24f359d6/app/Http/Controllers/AnnounceController.php#L177 + */ +if (strlen($userAgent) > 64) { + msg_die('User-Agent must be less than 64 characters long'); +} + +/** + * Block Browser by checking the User-Agent + * + * @see https://github.com/HDInnovations/UNIT3D-Community-Edition/blob/c64275f0b5dcb3c4c845d5204871adfe24f359d6/app/Http/Controllers/AnnounceController.php#L182 + */ +if (preg_match('/(Mozilla|Browser|Chrome|Safari|AppleWebKit|Opera|Links|Lynx|Bot|Unknown)/i', $userAgent)) { + msg_die('Browser disallowed'); } // IP $ip = $_SERVER['REMOTE_ADDR']; -if (!$bb_cfg['ignore_reported_ip'] && isset($_GET['ip']) && $ip !== $_GET['ip']) -{ - if (!$bb_cfg['verify_reported_ip']) - { - $ip = $_GET['ip']; - } - elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) - { - foreach ($matches[0] as $x_ip) - { - if ($x_ip === $_GET['ip']) - { - if (!$bb_cfg['allow_internal_ip'] && preg_match("#^(10|172\.16|192\.168)\.#", $x_ip)) - { - break; - } - $ip = $x_ip; - break; - } - } - } +// 'ip' query handling +if (!config()->get('ignore_reported_ip') && isset($_GET['ip']) && $ip !== $_GET['ip']) { + if (!config()->get('verify_reported_ip') && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $x_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + + if ($x_ip === $_GET['ip']) { + $filteredIp = filter_var($x_ip, FILTER_VALIDATE_IP); + if ($filteredIp !== false && (config()->get('allow_internal_ip') || !filter_var($filteredIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))) { + $ip = $filteredIp; + } + } + } } + // Check that IP format is valid -if (!verify_ip($ip)) -{ - msg_die("Invalid IP: $ip"); +if (!\TorrentPier\Helpers\IPHelper::isValid($ip)) { + msg_die("Invalid IP: $ip"); +} + +// Convert IP to long format +$ip_sql = \TorrentPier\Helpers\IPHelper::ip2long($ip); + +// Detect IP version +$ipv4 = $ipv6 = null; +$ip_version = \TorrentPier\Helpers\IPHelper::isValidv6($ip) ? 'ipv6' : 'ip'; +if ($ip_version === 'ipv6') { + $ipv6 = $ip_sql; +} else { + $ipv4 = $ip_sql; } -// Convert IP to HEX format -$ip_sql = encode_ip($ip); // Peer unique id -$peer_hash = md5( - rtrim($info_hash, ' ') . $passkey . $ip . $port -); +$peer_hash = hash('xxh128', $passkey . $info_hash_hex . $port); + +// Set seeder & complete +$complete = $seeder = ($left == 0) ? 1 : 0; // Get cached peer info from previous announce (last peer info) $lp_info = CACHE('tr_cache')->get(PEER_HASH_PREFIX . $peer_hash); -if (DBG_LOG) dbg_log(' ', '$lp_info-get_from-CACHE-'. ($lp_info ? 'hit' : 'miss')); +// Stopped event, slice peer's cache life to 30 seconds +if ($stopped && $lp_info) { + CACHE('tr_cache')->set(PEER_HASH_PREFIX . $peer_hash, $lp_info, 30); +} // Drop fast announce -if ($lp_info && (!isset($event) || $event !== 'stopped')) -{ - drop_fast_announce($lp_info); -} - -// Functions -function drop_fast_announce ($lp_info) -{ - global $announce_interval; - - if ($lp_info['update_time'] < (TIMENOW - $announce_interval + 60)) - { - return; // if announce interval correct - } - - $new_ann_intrv = $lp_info['update_time'] + $announce_interval - TIMENOW; - - dummy_exit($new_ann_intrv); -} - -function msg_die ($msg) -{ - if (DBG_LOG) dbg_log(' ', '!die-'. clean_filename($msg)); - - $output = bencode(array( -# 'interval' => (int) 1800, - 'min interval' => (int) 1800, -# 'peers' => (string) DUMMY_PEER, - 'failure reason' => (string) $msg, - 'warning message' => (string) $msg, - )); - - die($output); -} - -# $agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-'; -# bb_log("$agent | ". str_compact($peer_id) ."\n", 'agent'); - -// Start announcer -define('TR_ROOT', './'); -require(TR_ROOT . 'includes/init_tr.php'); - -$seeder = ($left == 0) ? 1 : 0; -$stopped = ($event === 'stopped'); - -// Stopped event -if ($stopped) -{ - CACHE('tr_cache')->rm(PEER_HASH_PREFIX . $peer_hash); - if (DBG_LOG) dbg_log(' ', 'stopped'); +if ($lp_info && (!isset($event) || !$stopped)) { + if ($lp_info['ip_ver4'] === $ipv4 || $lp_info['ip_ver6'] === $ipv6 || isset($lp_info['ip_ver4'], $lp_info['ip_ver6'])) { + if ($lp_cached_peers = CACHE('tr_cache')->get(PEERS_LIST_PREFIX . $lp_info['topic_id'])) { + drop_fast_announce($lp_info, $lp_cached_peers); // Use cache but with new calculated interval and seed, peer count set + } + } } // Get last peer info from DB -if (!CACHE('tr_cache')->used && !$lp_info) -{ - $lp_info = DB()->fetch_row(" - SELECT * FROM ". BB_BT_TRACKER ." WHERE peer_hash = '$peer_hash' LIMIT 1 +if (!CACHE('tr_cache')->used && !$lp_info) { + $lp_info = DB()->fetch_row(" + SELECT * FROM " . BB_BT_TRACKER . " WHERE peer_hash = '$peer_hash' LIMIT 1 "); - - if (DBG_LOG) dbg_log(' ', '$lp_info-get_from-DB-'. ($lp_info ? 'hit' : 'miss')); } -if ($lp_info) -{ - if (!$stopped) - { - drop_fast_announce($lp_info); - } +if ($lp_info) { + $user_id = $lp_info['user_id']; + $topic_id = $lp_info['topic_id']; + $releaser = $lp_info['releaser']; + $tor_type = $lp_info['tor_type']; + $hybrid_unrecord = $lp_info['hybrid_unrecord'] ?? false; +} else { + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - $user_id = $lp_info['user_id']; - $topic_id = $lp_info['topic_id']; - $releaser = $lp_info['releaser']; - $tor_type = $lp_info['tor_type']; -} -else -{ - // Verify if torrent registered on tracker and user authorized - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - $passkey_sql = DB()->escape($passkey); + /** + * Currently torrent clients send truncated v2 hashes (the design raises questions). + * @see https://github.com/bittorrent/bittorrent.org/issues/145#issuecomment-1720040343 + */ + $info_hash_where = "WHERE tor.info_hash = '$info_hash_sql' OR SUBSTRING(tor.info_hash_v2, 1, 20) = '$info_hash_sql'"; - $sql = " - SELECT tor.topic_id, tor.poster_id, tor.tor_type, u.* - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_BT_USERS ." u ON u.auth_key = '$passkey_sql' - WHERE tor.info_hash = '$info_hash_sql' + $passkey_sql = DB()->escape($passkey); + + $sql = " + SELECT tor.topic_id, tor.poster_id, tor.tor_type, tor.tor_status, tor.info_hash, tor.info_hash_v2, bt.*, u.user_level + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_BT_USERS . " bt ON bt.auth_key = '$passkey_sql' + LEFT JOIN " . BB_USERS . " u ON u.user_id = bt.user_id + $info_hash_where LIMIT 1 "; + $row = DB()->fetch_row($sql); - $row = DB()->fetch_row($sql); + // Verify if torrent registered on tracker and user authorized + if (empty($row['topic_id'])) { + msg_die('Torrent not registered, info_hash = ' . (mb_check_encoding($info_hash, DEFAULT_CHARSET) ? $info_hash : $info_hash_hex)); + } + if (empty($row['user_id'])) { + msg_die('Please LOG IN and RE-DOWNLOAD this torrent (user not found)'); + } - if (empty($row['topic_id'])) - { - msg_die('Torrent not registered, info_hash = ' . bin2hex($info_hash_sql)); - } - if (empty($row['user_id'])) - { - msg_die('Please LOG IN and REDOWNLOAD this torrent (user not found)'); - } + // Assign variables + $user_id = $row['user_id']; + define('IS_GUEST', (int)$user_id === GUEST_UID); + define('IS_ADMIN', !IS_GUEST && (int)$row['user_level'] === ADMIN); + define('IS_MOD', !IS_GUEST && (int)$row['user_level'] === MOD); + define('IS_GROUP_MEMBER', !IS_GUEST && (int)$row['user_level'] === GROUP_MEMBER); + define('IS_USER', !IS_GUEST && (int)$row['user_level'] === USER); + define('IS_SUPER_ADMIN', IS_ADMIN && isset(config()->get('super_admins')[$user_id])); + define('IS_AM', IS_ADMIN || IS_MOD); + $topic_id = $row['topic_id']; + $releaser = (int)($user_id == $row['poster_id']); + $tor_type = $row['tor_type']; + $tor_status = $row['tor_status']; - $user_id = $row['user_id']; - $topic_id = $row['topic_id']; - $releaser = (int) ($user_id == $row['poster_id']); - $tor_type = $row['tor_type']; + // Check tor status + if (!IS_AM && isset(config()->get('tor_frozen')[$tor_status]) && !(isset(config()->get('tor_frozen_author_download')[$tor_status]) && $releaser)) { + msg_die('Torrent frozen and cannot be downloaded'); + } - // Ratio limits - if ((TR_RATING_LIMITS || $tr_cfg['limit_concurrent_ips']) && !$stopped) - { - $user_ratio = ($row['u_down_total'] && $row['u_down_total'] > MIN_DL_FOR_RATIO) ? ($row['u_up_total'] + $row['u_up_release'] + $row['u_up_bonus']) / $row['u_down_total'] : 1; - $rating_msg = ''; + // Check hybrid status + if (!empty($row['info_hash']) && !empty($row['info_hash_v2'])) { + $stat_protocol = match ((int)config()->get('tracker.hybrid_stat_protocol')) { + 2 => substr($row['info_hash_v2'], 0, 20), + default => $row['info_hash'] // 1 + }; + if ($info_hash !== $stat_protocol) { + $hybrid_unrecord = true; // This allows us to announce only for one info-hash + } + } - if (!$seeder) - { - foreach ($rating_limits as $ratio => $limit) - { - if ($user_ratio < $ratio) - { - $tr_cfg['limit_active_tor'] = 1; - $tr_cfg['limit_leech_count'] = $limit; - $rating_msg = " (ratio < $ratio)"; - break; - } - } - } + // Ratio limits + if ((RATIO_ENABLED || config()->get('tracker.limit_concurrent_ips')) && !$stopped) { + $user_ratio = get_bt_ratio($row); + if ($user_ratio === null) { + $user_ratio = 1; + } + $rating_msg = ''; - // Limit active torrents - if (!isset($bb_cfg['unlimited_users'][$user_id]) && $tr_cfg['limit_active_tor'] && (($tr_cfg['limit_seed_count'] && $seeder) || ($tr_cfg['limit_leech_count'] && !$seeder))) - { - $sql = "SELECT COUNT(DISTINCT topic_id) AS active_torrents - FROM ". BB_BT_TRACKER ." + if (!$seeder) { + foreach (config()->get('rating') as $ratio => $limit) { + if ($user_ratio < $ratio) { + config()->set('tracker.limit_active_tor', 1); + config()->set('tracker.limit_leech_count', $limit); + $rating_msg = " (ratio < $ratio)"; + break; + } + } + } + + // Limit active torrents + if (!isset(config()->get('unlimited_users')[$user_id]) && config()->get('tracker.limit_active_tor') && ((config()->get('tracker.limit_seed_count') && $seeder) || (config()->get('tracker.limit_leech_count') && !$seeder))) { + $sql = "SELECT COUNT(DISTINCT topic_id) AS active_torrents + FROM " . BB_BT_TRACKER . " WHERE user_id = $user_id AND seeder = $seeder AND topic_id != $topic_id"; - if (!$seeder && $tr_cfg['leech_expire_factor'] && $user_ratio < 0.5) - { - $sql .= " AND update_time > ". (TIMENOW - 60*$tr_cfg['leech_expire_factor']); - } - $sql .= " GROUP BY user_id"; + if (!$seeder && config()->get('tracker.leech_expire_factor') && $user_ratio < 0.5) { + $sql .= " AND update_time > " . (TIMENOW - 60 * config()->get('tracker.leech_expire_factor')); + } + $sql .= " GROUP BY user_id"; - if ($row = DB()->fetch_row($sql)) - { - if ($seeder && $tr_cfg['limit_seed_count'] && $row['active_torrents'] >= $tr_cfg['limit_seed_count']) - { - msg_die('Only '. $tr_cfg['limit_seed_count'] .' torrent(s) allowed for seeding'); - } - elseif (!$seeder && $tr_cfg['limit_leech_count'] && $row['active_torrents'] >= $tr_cfg['limit_leech_count']) - { - msg_die('Only '. $tr_cfg['limit_leech_count'] .' torrent(s) allowed for leeching'. $rating_msg); - } - } - } + if ($row = DB()->fetch_row($sql)) { + if ($seeder && config()->get('tracker.limit_seed_count') && $row['active_torrents'] >= config()->get('tracker.limit_seed_count')) { + msg_die('Only ' . config()->get('tracker.limit_seed_count') . ' torrent(s) allowed for seeding'); + } elseif (!$seeder && config()->get('tracker.limit_leech_count') && $row['active_torrents'] >= config()->get('tracker.limit_leech_count')) { + msg_die('Only ' . config()->get('tracker.limit_leech_count') . ' torrent(s) allowed for leeching' . $rating_msg); + } + } + } - // Limit concurrent IPs - if ($tr_cfg['limit_concurrent_ips'] && (($tr_cfg['limit_seed_ips'] && $seeder) || ($tr_cfg['limit_leech_ips'] && !$seeder))) - { - $sql = "SELECT COUNT(DISTINCT ip) AS ips - FROM ". BB_BT_TRACKER ." + // Limit concurrent IPs + if (config()->get('tracker.limit_concurrent_ips') && ((config()->get('tracker.limit_seed_ips') && $seeder) || (config()->get('tracker.limit_leech_ips') && !$seeder))) { + $sql = "SELECT COUNT(DISTINCT ip) AS ips + FROM " . BB_BT_TRACKER . " WHERE topic_id = $topic_id AND user_id = $user_id AND seeder = $seeder - AND ip != '$ip_sql'"; + AND $ip_version != '$ip_sql'"; - if (!$seeder && $tr_cfg['leech_expire_factor']) - { - $sql .= " AND update_time > ". (TIMENOW - 60*$tr_cfg['leech_expire_factor']); - } - $sql .= " GROUP BY topic_id"; + if (!$seeder && config()->get('tracker.leech_expire_factor')) { + $sql .= " AND update_time > " . (TIMENOW - 60 * config()->get('tracker.leech_expire_factor')); + } + $sql .= " GROUP BY topic_id"; - if ($row = DB()->fetch_row($sql)) - { - if ($seeder && $tr_cfg['limit_seed_ips'] && $row['ips'] >= $tr_cfg['limit_seed_ips']) - { - msg_die('You can seed only from '. $tr_cfg['limit_seed_ips'] ." IP's"); - } - elseif (!$seeder && $tr_cfg['limit_leech_ips'] && $row['ips'] >= $tr_cfg['limit_leech_ips']) - { - msg_die('You can leech only from '. $tr_cfg['limit_leech_ips'] ." IP's"); - } - } - } - } + if ($row = DB()->fetch_row($sql)) { + if ($seeder && config()->get('tracker.limit_seed_ips') && $row['ips'] >= config()->get('tracker.limit_seed_ips')) { + msg_die('You can seed only from ' . config()->get('tracker.limit_seed_ips') . " IP's"); + } elseif (!$seeder && config()->get('tracker.limit_leech_ips') && $row['ips'] >= config()->get('tracker.limit_leech_ips')) { + msg_die('You can leech only from ' . config()->get('tracker.limit_leech_ips') . " IP's"); + } + } + } + } } // Up/Down speed $speed_up = $speed_down = 0; -if ($lp_info && $lp_info['update_time'] < TIMENOW) -{ - if ($uploaded > $lp_info['uploaded']) - { - $speed_up = ceil(($uploaded - $lp_info['uploaded']) / (TIMENOW - $lp_info['update_time'])); - } - if ($downloaded > $lp_info['downloaded']) - { - $speed_down = ceil(($downloaded - $lp_info['downloaded']) / (TIMENOW - $lp_info['update_time'])); - } +if ($lp_info && $lp_info['update_time'] < TIMENOW) { + if ($uploaded > $lp_info['uploaded']) { + $speed_up = ceil(($uploaded - $lp_info['uploaded']) / (TIMENOW - $lp_info['update_time'])); + } + if ($downloaded > $lp_info['downloaded']) { + $speed_down = ceil(($downloaded - $lp_info['downloaded']) / (TIMENOW - $lp_info['update_time'])); + } } // Up/Down addition @@ -350,156 +376,174 @@ $up_add = ($lp_info && $uploaded > $lp_info['uploaded']) ? $uploaded - $lp_info[ $down_add = ($lp_info && $downloaded > $lp_info['downloaded']) ? $downloaded - $lp_info['downloaded'] : 0; // Gold/Silver releases -if ($tr_cfg['gold_silver_enabled'] && $down_add) -{ - if ($tor_type == TOR_TYPE_GOLD) - { - $down_add = 0; - } - // Silver releases - elseif ($tor_type == TOR_TYPE_SILVER) - { - $down_add = ceil($down_add/2); - } +if (config()->get('tracker.gold_silver_enabled') && $down_add) { + if ($tor_type == TOR_TYPE_GOLD) { + $down_add = 0; + } // Silver releases + elseif ($tor_type == TOR_TYPE_SILVER) { + $down_add = ceil($down_add / 2); + } } -// Insert/update peer info +// Freeleech +if (config()->get('tracker.freeleech') && $down_add) { + $down_add = 0; +} + +// Insert / update peer info $peer_info_updated = false; $update_time = ($stopped) ? 0 : TIMENOW; -if ($lp_info) -{ - $sql = "UPDATE ". BB_BT_TRACKER ." SET update_time = $update_time"; +if ($lp_info && empty($hybrid_unrecord)) { + $sql = "UPDATE " . BB_BT_TRACKER . " SET update_time = $update_time"; - $sql .= ", seeder = $seeder"; - $sql .= ($releaser != $lp_info['releaser']) ? ", releaser = $releaser" : ''; + $sql .= ", $ip_version = '$ip_sql'"; + $sql .= ", port = '$port'"; + $sql .= ", seeder = $seeder"; + $sql .= ($releaser != $lp_info['releaser']) ? ", releaser = $releaser" : ''; - $sql .= ($tor_type != $lp_info['tor_type']) ? ", tor_type = $tor_type" : ''; + $sql .= ($tor_type != $lp_info['tor_type']) ? ", tor_type = $tor_type" : ''; - $sql .= ($uploaded != $lp_info['uploaded']) ? ", uploaded = $uploaded" : ''; - $sql .= ($downloaded != $lp_info['downloaded']) ? ", downloaded = $downloaded" : ''; - $sql .= ", remain = $left"; + $sql .= ($uploaded != $lp_info['uploaded']) ? ", uploaded = $uploaded" : ''; + $sql .= ($downloaded != $lp_info['downloaded']) ? ", downloaded = $downloaded" : ''; + $sql .= ", remain = $left"; - $sql .= ($up_add) ? ", up_add = up_add + $up_add" : ''; - $sql .= ($down_add) ? ", down_add = down_add + $down_add" : ''; + $sql .= $up_add ? ", up_add = up_add + $up_add" : ''; + $sql .= $down_add ? ", down_add = down_add + $down_add" : ''; - $sql .= ", speed_up = $speed_up"; - $sql .= ", speed_down = $speed_down"; + $sql .= ", speed_up = $speed_up"; + $sql .= ", speed_down = $speed_down"; - $sql .= " WHERE peer_hash = '$peer_hash'"; - $sql .= " LIMIT 1"; + $sql .= ", complete = $complete"; + $sql .= ", peer_id = '$peer_id_sql'"; - DB()->query($sql); + $sql .= " WHERE peer_hash = '$peer_hash'"; + $sql .= " LIMIT 1"; - $peer_info_updated = DB()->affected_rows(); + DB()->query($sql); - if (DBG_LOG) dbg_log(' ', 'this_peer-update'. ($peer_info_updated ? '' : '-FAIL')); + $peer_info_updated = DB()->affected_rows(); } -if (!$lp_info || !$peer_info_updated) -{ - $columns = 'peer_hash, topic_id, user_id, ip, port, seeder, releaser, tor_type, uploaded, downloaded, remain, speed_up, speed_down, up_add, down_add, update_time'; - $values = "'$peer_hash', $topic_id, $user_id, '$ip_sql', $port, $seeder, $releaser, $tor_type, $uploaded, $downloaded, $left, $speed_up, $speed_down, $up_add, $down_add, $update_time"; +if ((!$lp_info || !$peer_info_updated) && !$stopped && empty($hybrid_unrecord)) { + $columns = "peer_hash, topic_id, user_id, $ip_version, port, seeder, releaser, tor_type, uploaded, downloaded, remain, speed_up, speed_down, up_add, down_add, update_time, complete, peer_id"; + $values = "'$peer_hash', $topic_id, $user_id, '$ip_sql', $port, $seeder, $releaser, $tor_type, $uploaded, $downloaded, $left, $speed_up, $speed_down, $up_add, $down_add, $update_time, $complete, '$peer_id_sql'"; - DB()->query("REPLACE INTO ". BB_BT_TRACKER ." ($columns) VALUES ($values)"); - - if (DBG_LOG) dbg_log(' ', 'this_peer-insert'); + DB()->query("REPLACE INTO " . BB_BT_TRACKER . " ($columns) VALUES ($values)"); } // Exit if stopped -if ($stopped) -{ - silent_exit(); +if ($stopped) { + dummy_exit(); } // Store peer info in cache -$lp_info = array( - 'downloaded' => (float) $downloaded, - 'releaser' => (int) $releaser, - 'seeder' => (int) $seeder, - 'topic_id' => (int) $topic_id, - 'update_time' => (int) TIMENOW, - 'uploaded' => (float) $uploaded, - 'user_id' => (int) $user_id, - 'tor_type' => (int) $tor_type, -); +$lp_info_new = [ + 'downloaded' => (float)$downloaded, + 'releaser' => (int)$releaser, + 'seeder' => (int)$seeder, + 'topic_id' => (int)$topic_id, + 'update_time' => (int)TIMENOW, + 'uploaded' => (float)$uploaded, + 'user_id' => (int)$user_id, + 'tor_type' => (int)$tor_type, + 'complete' => (int)$complete, + 'ip_ver4' => $lp_info['ip_ver4'] ?? $ipv4, + 'ip_ver6' => $lp_info['ip_ver6'] ?? $ipv6, +]; -$lp_info_cached = CACHE('tr_cache')->set(PEER_HASH_PREFIX . $peer_hash, $lp_info, PEER_HASH_EXPIRE); +if (!empty($hybrid_unrecord)) { + $lp_info_new['hybrid_unrecord'] = $hybrid_unrecord; +} -if (DBG_LOG && !$lp_info_cached) dbg_log(' ', '$lp_info-caching-FAIL'); +// Cache new list with peer hash +$lp_info_cached = CACHE('tr_cache')->set(PEER_HASH_PREFIX . $peer_hash, $lp_info_new, PEER_HASH_EXPIRE); // Get cached output $output = CACHE('tr_cache')->get(PEERS_LIST_PREFIX . $topic_id); -if (DBG_LOG) dbg_log(' ', '$output-get_from-CACHE-'. ($output !== false ? 'hit' : 'miss')); +if (!$output) { + // Retrieve peers + $numwant = (int)config()->get('tracker.numwant'); + $compact_mode = (config()->get('tracker.compact_mode') || !empty($compact)); -if (!$output) -{ - // Retrieve peers - $numwant = (int) $tr_cfg['numwant']; - $compact_mode = ($tr_cfg['compact_mode'] || !empty($compact)); + $rowset = DB()->fetch_rowset(" + SELECT ip, ipv6, port + FROM " . BB_BT_TRACKER . " + WHERE topic_id = $topic_id + ORDER BY seeder ASC, RAND() + LIMIT $numwant + "); - $rowset = DB()->fetch_rowset(" - SELECT ip, port - FROM ". BB_BT_TRACKER ." - WHERE topic_id = $topic_id - ORDER BY RAND() - LIMIT $numwant - "); + if (empty($rowset)) { + $rowset[] = ['ip' => $ip_sql, 'port' => (int)$port]; + } - if ($compact_mode) - { - $peers = ''; + if ($compact_mode) { + $peers = ''; + $peers6 = ''; - foreach ($rowset as $peer) - { - $peers .= pack('Nn', ip2long(decode_ip($peer['ip'])), $peer['port']); - } - } - else - { - $peers = array(); + foreach ($rowset as $peer) { + if (!empty($peer['ip'])) { + $peer_ipv4 = \TorrentPier\Helpers\IPHelper::long2ip_extended($peer['ip']); + $peers .= inet_pton($peer_ipv4) . pack('n', $peer['port']); + } + if (!empty($peer['ipv6'])) { + $peer_ipv6 = \TorrentPier\Helpers\IPHelper::long2ip_extended($peer['ipv6']); + $peers6 .= inet_pton($peer_ipv6) . pack('n', $peer['port']); + } + } + } else { + $peers = []; - foreach ($rowset as $peer) - { - $peers[] = array( - 'ip' => decode_ip($peer['ip']), - 'port' => intval($peer['port']), - ); - } - } + foreach ($rowset as $peer) { + if (!empty($peer['ip'])) { + $peer_ipv4 = \TorrentPier\Helpers\IPHelper::long2ip_extended($peer['ip']); + $peers[] = ['ip' => \TorrentPier\Helpers\IPHelper::long2ip_extended($peer['ip']), 'port' => (int)$peer['port']]; + } + if (!empty($peer['ipv6'])) { + $peer_ipv6 = \TorrentPier\Helpers\IPHelper::long2ip_extended($peer['ipv6']); + $peers[] = ['ip' => \TorrentPier\Helpers\IPHelper::long2ip_extended($peer['ipv6']), 'port' => (int)$peer['port']]; + } + } + } - $seeders = 0; - $leechers = 0; + $seeders = $leechers = $client_completed = 0; - if ($tr_cfg['scrape']) - { - $row = DB()->fetch_row(" - SELECT seeders, leechers - FROM ". BB_BT_TRACKER_SNAP ." + if (config()->get('tracker.scrape')) { + $row = DB()->fetch_row(" + SELECT seeders, leechers, completed + FROM " . BB_BT_TRACKER_SNAP . " WHERE topic_id = $topic_id LIMIT 1 "); - $seeders = $row['seeders']; - $leechers = $row['leechers']; - } + $seeders = $row['seeders'] ?? ($seeder ? 1 : 0); + $leechers = $row['leechers'] ?? (!$seeder ? 1 : 0); + $client_completed = $row['completed'] ?? 0; + } - $output = array( - 'interval' => (int) $announce_interval, - 'min interval' => (int) $announce_interval, - 'peers' => $peers, - 'complete' => (int) $seeders, - 'incomplete' => (int) $leechers, - ); + $output = [ + 'interval' => (int)$announce_interval, + 'complete' => (int)$seeders, + 'incomplete' => (int)$leechers, + 'downloaded' => (int)$client_completed, + ]; - $peers_list_cached = CACHE('tr_cache')->set(PEERS_LIST_PREFIX . $topic_id, $output, PEERS_LIST_EXPIRE); + if (!empty($peers)) { + $output['peers'] = $peers; + } - if (DBG_LOG && !$peers_list_cached) dbg_log(' ', '$output-caching-FAIL'); + if (!empty($peers6)) { + $output['peers6'] = $peers6; + } + + $peers_list_cached = CACHE('tr_cache')->set(PEERS_LIST_PREFIX . $topic_id, $output, PEERS_LIST_EXPIRE); } -// Return data to client -echo bencode($output); +$output['external ip'] = inet_pton($ip); -tracker_exit(); -exit; \ No newline at end of file +// Return data to client +echo \Arokettu\Bencode\Bencode::encode($output); + +exit; diff --git a/bt/includes/.htaccess b/bt/includes/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/bt/includes/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/bt/includes/init_tr.php b/bt/includes/init_tr.php index f3f1b8298..283c71ede 100644 --- a/bt/includes/init_tr.php +++ b/bt/includes/init_tr.php @@ -1,489 +1,84 @@ get('tracker.bt_off')) { + msg_die(config()->get('tracker.bt_off_reason')); +} // // Functions // -function tracker_exit () +function silent_exit($msg = '') { - global $DBS; + echo \Arokettu\Bencode\Bencode::encode(['warning message' => str_compact($msg)]); - if (DBG_LOG && DBG_TRACKER) - { - if ($gen_time = utime() - TIMESTART) - { - $sql_init_perc = round($DBS->sql_inittime*100/$gen_time); - $sql_total_perc = round($DBS->sql_timetotal*100/$gen_time); - - $str = array(); - $str[] = substr(TIMENOW, -4, 4); - $str[] = sprintf('%.4f', $gen_time); - $str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_inittime, $sql_init_perc); - $str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_timetotal, $sql_total_perc); - $str[] = $DBS->num_queries; - $str[] = sprintf('%.1f', sys('la')); - $str = join(LOG_SEPR, $str) . LOG_LF; - dbg_log($str, '!!gentime'); - } - } - exit; + exit; } -function silent_exit () +function error_exit($msg = '') { - while (@ob_end_clean()); + echo \Arokettu\Bencode\Bencode::encode(['failure reason' => str_compact($msg)]); - tracker_exit(); + exit; } -function error_exit ($msg = '') +function drop_fast_announce($lp_info, $lp_cached_peers = []) { - if (DBG_LOG) dbg_log(' ', '!err-'. clean_filename($msg)); + global $announce_interval; - silent_exit(); + if ($lp_info['update_time'] < (TIMENOW - $announce_interval + 60)) { + return; // if announce interval correct + } - echo bencode(array('failure reason' => str_compact($msg))); + $new_ann_intrv = $lp_info['update_time'] + $announce_interval - TIMENOW; - tracker_exit(); + dummy_exit($new_ann_intrv, $lp_cached_peers); } -// Database -class sql_db +function msg_die($msg) { - var $cfg = array(); - var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); - var $link = null; - var $result = null; - var $db_server = ''; - var $selected_db = null; - - var $locked = false; - - var $num_queries = 0; - var $sql_starttime = 0; - var $sql_inittime = 0; - var $sql_timetotal = 0; - var $sql_last_time = 0; - var $slow_time = 0; - - var $dbg = array(); - var $dbg_id = 0; - var $dbg_enabled = false; - var $cur_query = null; - - var $DBS = array(); - - /** - * Constructor - */ - function sql_db ($cfg_values) - { - global $DBS; - - $this->cfg = array_combine($this->cfg_keys, $cfg_values); - $this->dbg_enabled = sql_dbg_enabled(); - $this->slow_time = SQL_SLOW_QUERY_TIME; - - $this->DBS['num_queries'] =& $DBS->num_queries; - $this->DBS['sql_inittime'] =& $DBS->sql_inittime; - $this->DBS['sql_timetotal'] =& $DBS->sql_timetotal; - } - - /** - * Initialize connection - */ - function init () - { - // Connect to server - $this->link = $this->connect(); - - // Select database - $this->selected_db = $this->select_db(); - - // Set charset - if ($this->cfg['charset'] && !@mysql_set_charset($this->cfg['charset'], $this->link)) - { - if (!$this->sql_query("SET NAMES {$this->cfg['charset']}")) - { - error_exit("Could not set charset {$this->cfg['charset']}"); - } - } - - $this->num_queries = 0; - $this->sql_inittime = $this->sql_timetotal; - $this->DBS['sql_inittime'] += $this->sql_inittime; - } - - /** - * Open connection - */ - function connect () - { - $this->cur_query = 'connect'; - $this->debug('start'); - - $connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect'; - - if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) - { - $this->log_error(); - } - - register_shutdown_function(array(&$this, 'close')); - - $this->debug('end'); - $this->cur_query = null; - -# if (DBG_LOG) dbg_log(' ', 'DB-connect'. ($link ? '' : '-FAIL')); - - if (!$link) - { - if (function_exists('dummy_exit')) - { - dummy_exit(mt_rand(1200, 2400)); - } - else - { - die; - } - } - - return $link; - } - - /** - * Select database - */ - function select_db () - { - $this->cur_query = 'select db'; - $this->debug('start'); - - if (!mysql_select_db($this->cfg['dbname'], $this->link)) - { - $this->log_error(); - error_exit("Could not select database '{$this->cfg['dbname']}'"); - } - - $this->debug('end'); - $this->cur_query = null; - - return $this->cfg['dbname']; - } - - /** - * Base query method - */ - function sql_query ($query) - { - if (!is_resource($this->link)) - { - $this->init(); - } - $this->cur_query = $query; - $this->debug('start'); - - if (!$this->result = mysql_query($query, $this->link)) - { - $this->log_error(); - } - - $this->debug('end'); - $this->cur_query = null; - - $this->num_queries++; - $this->DBS['num_queries']++; - - return $this->result; - } - - /** - * Execute query WRAPPER (with error handling) - */ - function query ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $result; - } - - /** - * Return number of rows - */ - function num_rows ($result = false) - { - $num_rows = false; - - if ($result OR $result = $this->result) - { - $num_rows = is_resource($result) ? mysql_num_rows($result) : false; - } - - return $num_rows; - } - - /** - * Return number of affected rows - */ - function affected_rows () - { - return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; - } - - /** - * Fetch current row - */ - function sql_fetchrow ($result) - { - return is_resource($result) ? mysql_fetch_assoc($result) : false; - } - - /** - * Alias of sql_fetchrow() - */ - function fetch_next ($result) - { - return $this->sql_fetchrow($result); - } - - /** - * Fetch row WRAPPER (with error handling) - */ - function fetch_row ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $this->sql_fetchrow($result); - } - - /** - * Fetch all rows - */ - function sql_fetchrowset ($result) - { - $rowset = array(); - - while ($row = mysql_fetch_assoc($result)) - { - $rowset[] = $row; - } - - return $rowset; - } - - /** - * Fetch all rows WRAPPER (with error handling) - */ - function fetch_rowset ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $this->sql_fetchrowset($result); - } - - /** - * Escape string used in sql query - */ - function escape ($v, $check_type = false) - { - if (!is_resource($this->link)) - { - $this->init(); - } - if (!$check_type) - { - return mysql_real_escape_string($v); - } - - switch (true) - { - case is_string ($v): return "'". mysql_real_escape_string($v) ."'"; - case is_int ($v): return "$v"; - case is_bool ($v): return ($v) ? '1' : '0'; - case is_float ($v): return "'$v'"; - case is_null ($v): return 'NULL'; - } - // if $v has unsuitable type - $this->trigger_error(__FUNCTION__ .' - wrong params'); - } - - /** - * Return sql error array - */ - function sql_error () - { - $return_ary = array( - 'code' => '', - 'message' => 'not connected', - ); - - if (is_resource($this->link)) - { - $return_ary = array( - 'code' => mysql_errno($this->link), - 'message' => mysql_error($this->link), - ); - } - - return $return_ary; - } - - /** - * Close sql connection - */ - function close () - { - if (is_resource($this->link)) - { - mysql_close($this->link); - } - - $this->link = $this->selected_db = null; - - if (DBG_LOG) dbg_log(str_repeat(' ', $this->num_queries), 'DB-num_queries-'. php_sapi_name()); - } - - /** - * Get info about last query - */ - function query_info () - { - $info = array(); - - if ($num = $this->num_rows($this->result)) - { - $info[] = "$num rows"; - } - - if (is_resource($this->link) AND $ext = mysql_info($this->link)) - { - $info[] = "$ext"; - } - elseif (!$num && ($aff = $this->affected_rows($this->result) AND $aff != -1)) - { - $info[] = "$aff rows"; - } - - return join(', ', $info); - } - - /** - * Store debug info - */ - function debug ($mode) - { - if (!SQL_DEBUG) return; - - if ($mode == 'start') - { - if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) - { - $this->sql_starttime = utime(); - $this->sql_last_time = 0; - } - } - elseif ($mode == 'end') - { - if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) - { - $this->sql_last_time = utime() - $this->sql_starttime; - $this->sql_timetotal += $this->sql_last_time; - $this->DBS['sql_timetotal'] += $this->sql_last_time; - - if (SQL_LOG_SLOW_QUERIES && $this->sql_last_time > $this->slow_time) - { - $msg = date('m-d H:i:s') . LOG_SEPR; - $msg .= sprintf('%03d', round($this->sql_last_time)); - $msg .= LOG_SEPR . sprintf('%.1f', sys('la')); - $msg .= LOG_SEPR . str_compact($this->cur_query); - $msg .= LOG_SEPR .' # '. $this->query_info(); - $msg .= LOG_SEPR . $this->debug_find_source(); - bb_log($msg . LOG_LF, 'sql_slow_tr'); - } - } - } - return; - } - - /** - * Trigger error - */ - function trigger_error ($msg = '') - { - if (error_reporting()) - { - if (!$msg) $msg = 'DB Error'; - - if (DBG_TRACKER === true) - { - $err = $this->sql_error(); - $msg .= trim(sprintf(' #%06d %s', $err['code'], $err['message'])); - } - else - { - $msg .= " [". $this->debug_find_source() ."]"; - } - - error_exit($msg); - } - } - - /** - * Find caller source - */ - function debug_find_source () - { - $source = ''; - $backtrace = debug_backtrace(); - - foreach ($backtrace as $trace) - { - if ($trace['file'] !== __FILE__) - { - $source = str_replace(BB_PATH, '', $trace['file']) .'('. $trace['line'] .')'; - break; - } - } - - return $source; - } - - /** - * Log error - */ - function log_error () - { - if (!SQL_LOG_ERRORS) return; - if (!error_reporting()) return; - - $msg = array(); - $err = $this->sql_error(); - $msg[] = str_compact(sprintf('#%06d %s', $err['code'], $err['message'])); - $msg[] = ''; - $msg[] = str_compact($this->cur_query); - $msg[] = ''; - $msg[] = 'Source : '. $this->debug_find_source(); - $msg[] = 'IP : '. @$_SERVER['REMOTE_ADDR']; - $msg[] = 'Date : '. date('Y-m-d H:i:s'); - $msg[] = 'Agent : '. @$_SERVER['HTTP_USER_AGENT']; - $msg[] = 'Req_URI : '. @$_SERVER['REQUEST_URI']; - $msg[] = 'Referer : '. @$_SERVER['HTTP_REFERER']; - $msg[] = 'Method : '. @$_SERVER['REQUEST_METHOD']; - $msg[] = 'Request : '. trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF; - $msg[] = ''; - bb_log($msg, 'sql_error_tr'); - } -} \ No newline at end of file + $output = \Arokettu\Bencode\Bencode::encode([ + 'interval' => (int)1800, + 'failure reason' => (string)$msg, + ]); + + die($output); +} + +function dummy_exit($interval = 1800, $cache_dict = []) +{ + $output = [ + 'interval' => (int)$interval, + 'peers' => (string)DUMMY_PEER, + 'external ip' => inet_pton($_SERVER['REMOTE_ADDR']), + ]; + + if (!empty($cache_dict)) { + $output['complete'] = $cache_dict['complete']; + $output['incomplete'] = $cache_dict['incomplete']; + $output['downloaded'] = $cache_dict['downloaded']; + } + + if (isset($cache_dict['peers'])) { + $output['peers'] = $cache_dict['peers']; + } + + if (isset($cache_dict['peers6'])) { + $output['peers6'] = $cache_dict['peers6']; + } + + $output = \Arokettu\Bencode\Bencode::encode($output); + + die($output); +} diff --git a/bt/index.php b/bt/index.php index 7e44c5d1d..7896ca43d 100644 --- a/bt/index.php +++ b/bt/index.php @@ -1,3 +1,10 @@ get('tracker.scrape')) { + msg_die('Please disable SCRAPE!'); +} // Recover info_hash -if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) -{ - $_GET['info_hash'] = $_GET['?info_hash']; +if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) { + $_GET['info_hash'] = $_GET['?info_hash']; } -if (!isset($_GET['info_hash']) || strlen($_GET['info_hash']) != 20) -{ - msg_die('Invalid info_hash'); +$info_hash = isset($_GET['info_hash']) ? (string)$_GET['info_hash'] : null; + +// Verify info_hash +if (!isset($info_hash)) { + msg_die('info_hash was not provided'); } -$info_hash = $_GET['info_hash']; +// Store info hash in hex format +$info_hash_hex = bin2hex($info_hash); -function msg_die ($msg) -{ - if (DBG_LOG) dbg_log(' ', '!die-'. clean_filename($msg)); - - $output = bencode(array( - 'min interval' => (int) 1800, - 'failure reason' => (string) $msg, - 'warning message' => (string) $msg, - )); - - die($output); +// Check info_hash length +if (strlen($info_hash) !== 20) { + msg_die('Invalid info_hash: ' . (mb_check_encoding($info_hash, DEFAULT_CHARSET) ? $info_hash : $info_hash_hex)); } -define('TR_ROOT', './'); -require(TR_ROOT . 'includes/init_tr.php'); +// Handle multiple hashes +preg_match_all('/info_hash=([^&]*)/i', $_SERVER['QUERY_STRING'], $info_hash_array); -$info_hash_sql = rtrim(DB()->escape($info_hash), ' '); +$torrents = []; +$info_hashes = []; -$row = DB()->fetch_row(" - SELECT tor.complete_count, snap.seeders, snap.leechers - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_BT_TRACKER_SNAP ." snap ON (snap.topic_id = tor.topic_id) - WHERE tor.info_hash = '$info_hash_sql' - LIMIT 1 -"); +foreach ($info_hash_array[1] as $hash) { + $decoded_hash = urldecode($hash); -$output['files'][$info_hash] = array( - 'complete' => (int) $row['seeders'], - 'downloaded' => (int) $row['complete_count'], - 'incomplete' => (int) $row['leechers'], -); + if (strlen($decoded_hash) !== 20) { + continue; + } -echo bencode($output); + if ($scrape_cache = CACHE('tr_cache')->get(SCRAPE_LIST_PREFIX . bin2hex($decoded_hash))) { + $torrents['files'][$info_key = array_key_first($scrape_cache)] = $scrape_cache[$info_key]; + } else { + $info_hashes[] = DB()->escape(($decoded_hash)); + } +} -tracker_exit(); -exit; \ No newline at end of file +$info_hash_count = count($info_hashes); + +if (!empty($info_hash_count)) { + if ($info_hash_count > config()->get('max_scrapes')) { + $info_hashes = array_slice($info_hashes, 0, config()->get('max_scrapes')); + } + + $info_hashes_sql = implode('\', \'', $info_hashes); + + /** + * Currently torrent clients send truncated v2 hashes (the design raises questions). + * @see https://github.com/bittorrent/bittorrent.org/issues/145#issuecomment-1720040343 + */ + $info_hash_where = "tor.info_hash IN ('$info_hashes_sql') OR SUBSTRING(tor.info_hash_v2, 1, 20) IN ('$info_hashes_sql')"; + + $sql = " + SELECT tor.info_hash, tor.info_hash_v2, tor.complete_count, snap.seeders, snap.leechers + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_BT_TRACKER_SNAP . " snap ON (snap.topic_id = tor.topic_id) + WHERE $info_hash_where + "; + + $scrapes = DB()->fetch_rowset($sql); + + if (!empty($scrapes)) { + foreach ($scrapes as $scrape) { + $hash_v1 = !empty($scrape['info_hash']) ? $scrape['info_hash'] : ''; + $hash_v2 = !empty($scrape['info_hash_v2']) ? substr($scrape['info_hash_v2'], 0, 20) : ''; + $info_hash_scrape = (in_array(urlencode($hash_v1), $info_hash_array[1])) ? $hash_v1 : $hash_v2; // Replace logic to prioritize $hash_v2, in case of future prioritization of v2 + + $torrents['files'][$info_hash_scrape] = [ + 'complete' => (int)$scrape['seeders'], + 'downloaded' => (int)$scrape['complete_count'], + 'incomplete' => (int)$scrape['leechers'] + ]; + CACHE('tr_cache')->set(SCRAPE_LIST_PREFIX . bin2hex($info_hash_scrape), array_slice($torrents['files'], -1, null, true), SCRAPE_LIST_EXPIRE); + } + } +} + +// Verify if torrent registered on tracker +if (empty($torrents)) { + msg_die('Torrent not registered, info_hash = ' . (mb_check_encoding($info_hash, DEFAULT_CHARSET) ? $info_hash : $info_hash_hex)); +} + +die(\Arokettu\Bencode\Bencode::encode($torrents)); diff --git a/callseed.php b/callseed.php deleted file mode 100644 index 0db99f1cd..000000000 --- a/callseed.php +++ /dev/null @@ -1,94 +0,0 @@ -session_start(array('req_login' => true)); - -$topic_id = (int) request_var('t', 0); -$t_data = topic_info($topic_id); -$forum_id = $t_data['forum_id']; - -set_die_append_msg($forum_id, $topic_id); - -if ($t_data['seeders'] > 2) -{ - bb_die(sprintf($lang['CALLSEED_HAVE_SEED'], $t_data['seeders'])); -} -elseif ($t_data['call_seed_time'] > (TIMENOW - 86400)) -{ - $time_left = delta_time($t_data['call_seed_time'] + 86400, TIMENOW, 'days'); - bb_die(sprintf($lang['CALLSEED_MSG_SPAM'], $time_left)); -} - -$ban_user_id = array(); - -$sql = DB()->fetch_rowset("SELECT ban_userid FROM ". BB_BANLIST ." WHERE ban_userid != 0"); - -foreach ($sql as $row) -{ - $ban_user_id[] = ','. $row['ban_userid']; -} -$ban_user_id = join('', $ban_user_id); - -$user_list = DB()->fetch_rowset(" - SELECT DISTINCT dl.user_id, u.user_opt, tr.user_id as active_dl - FROM ". BB_BT_DLSTATUS ." dl - LEFT JOIN ". BB_USERS ." u ON(u.user_id = dl.user_id) - LEFT JOIN ". BB_BT_TRACKER ." tr ON(tr.user_id = dl.user_id) - WHERE dl.topic_id = $topic_id - AND dl.user_status IN (". DL_STATUS_COMPLETE.", ". DL_STATUS_DOWN.") - AND dl.user_id NOT IN ({$userdata['user_id']}, ". EXCLUDED_USERS_CSV . $ban_user_id .") - AND u.user_active = 1 - GROUP BY dl.user_id -"); - -$subject = sprintf($lang['CALLSEED_SUBJECT'], $t_data['topic_title']); -$message = sprintf($lang['CALLSEED_TEXT'], make_url(TOPIC_URL . $topic_id), $t_data['topic_title'], make_url(DOWNLOAD_URL . $t_data['attach_id'])); - -if ($user_list) -{ - foreach ($user_list as $row) - { - if (!empty($row['active_dl'])) continue; - - if (bf($row['user_opt'], 'user_opt', 'user_callseed')) - { - send_pm($row['user_id'], $subject, $message, BOT_UID); - } - } -} -else -{ - send_pm($t_data['poster_id'], $subject, $message, BOT_UID); -} - -DB()->query("UPDATE ". BB_BT_TORRENTS ." SET call_seed_time = ". TIMENOW ." WHERE topic_id = $topic_id LIMIT 1"); - -meta_refresh(TOPIC_URL . $topic_id); -bb_die($lang['CALLSEED_MSG_OK']); - -function topic_info ($topic_id) -{ - global $lang; - - $sql = " - SELECT - tor.poster_id, tor.forum_id, tor.attach_id, tor.call_seed_time, - t.topic_title, sn.seeders - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_TOPICS ." t USING(topic_id) - LEFT JOIN ". BB_BT_TRACKER_SNAP ." sn USING(topic_id) - WHERE tor.topic_id = $topic_id - "; - - if (!$torrent = DB()->fetch_row($sql)) - { - bb_die($lang['TOPIC_POST_NOT_EXIST']); - } - - return $torrent; -} diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 000000000..1798567f1 --- /dev/null +++ b/cliff.toml @@ -0,0 +1,126 @@ +# git-cliff ~ TorrentPier configuration file +# https://git-cliff.org/docs/configuration +# +# Lines starting with "#" are comments. +# Configuration options are organized into tables and keys. +# See documentation for more information on available options. + +[remote.github] +owner = "torrentpier" +repo = "torrentpier" + +[changelog] +# template for the changelog header +header = """ +[![TorrentPier](https://raw.githubusercontent.com/torrentpier/.github/refs/heads/main/versions/Cattle.png)](https://github.com/torrentpier)\n +# 📖 Change Log\n +""" +# template for the changelog body +# https://keats.github.io/tera/docs/#introduction +body = """ +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} + +{%- macro nightly_url() -%} + https://nightly.link/{{ remote.github.owner }}/{{ remote.github.repo }}/workflows/ci/master/TorrentPier-master +{%- endmacro -%} + +{% macro print_commit(commit) -%} + - {% if commit.scope %}*({{ commit.scope }})* {% endif %}\ + {% if commit.breaking %}[**breaking**] {% endif %}\ + {{ commit.message | upper_first }} - \ + ([{{ commit.id | truncate(length=7, end="") }}]({{ self::remote_url() }}/commit/{{ commit.id }}))\ +{% endmacro -%} + +{% if version %}\ + {% if previous.version %}\ + ## [{{ version }}]\ + ({{ self::remote_url() }}/compare/{{ previous.version }}..{{ version }}) ({{ timestamp | date(format="%Y-%m-%d") }}) + {% else %}\ + ## {{ version }} ({{ timestamp | date(format="%Y-%m-%d") }}) + {% endif %}\ +{% else %}\ + ## [nightly]({{ self::nightly_url() }}) +{% endif %}\ + +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | striptags | trim | upper_first }} + {% for commit in commits + | filter(attribute="scope") + | sort(attribute="scope") %} + {{ self::print_commit(commit=commit) }} + {%- endfor %} + {% for commit in commits %} + {%- if not commit.scope -%} + {{ self::print_commit(commit=commit) }} + {% endif -%} + {% endfor -%} +{% endfor -%} +{%- if github -%} +{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} + ## New Contributors ❤️ +{% endif %}\ +{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + * @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} in \ + [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} +{%- endfor -%} +{%- endif %} + + +""" +# template for the changelog footer +footer = """ +""" +# remove the leading and trailing whitespace from the templates +trim = true +# postprocessors +postprocessors = [ + { pattern = '', replace = "https://github.com/torrentpier/torrentpier" }, # replace repository URL +] + +[git] +# parse the commits based on https://www.conventionalcommits.org +conventional_commits = true +# filter out the commits that are not conventional +filter_unconventional = true +# process each line of a commit as an individual commit +split_commits = false +# regex for preprocessing the commit messages +commit_preprocessors = [ + # Replace issue numbers + { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/pull/${2}))" }, + # Check spelling of the commit with https://github.com/crate-ci/typos + # If the spelling is incorrect, it will be automatically fixed. + # { pattern = '.*', replace_command = 'typos --write-changes -' }, +] +# regex for parsing and grouping commits +commit_parsers = [ + { message = "^feat", group = "🚀 Features" }, + { message = "^fix", group = "🐛 Bug Fixes" }, + { message = "^doc", group = "📚 Documentation" }, + { message = "^perf", group = "⚡ Performance" }, + { message = "^refactor", group = "🚜 Refactor" }, + { message = "^style", group = "🎨 Styling" }, + { message = "^test", group = "🧪 Testing" }, + { message = "^ignore|^release|^changelog", skip = true }, + { message = "^chore|^ci|^misc", group = "⚙️ Miscellaneous" }, + { body = ".*security", group = "🛡️ Security" }, + { message = "^revert", group = "◀️ Revert" }, + { message = "^crowdin|^crodwin", group = "🈳 New translations" }, # crowdin pulls supporting + { message = "^Composer", group = "📦 Dependencies" }, # dependabot pulls supporting + { message = "^rem|^drop|^removed", group = "🗑️ Removed" }, + { message = ".*", group = "💼 Other" }, +] +# protect breaking changes from being skipped due to matching a skipping commit_parser +protect_breaking_commits = false +# filter out the commits that are not matched by commit parsers +filter_commits = false +# regex for matching git tags +tag_pattern = "v[0-9].*" +# sort the tags topologically +topo_order = false +# sort the commits inside sections by oldest/newest order +sort_commits = "newest" diff --git a/common.php b/common.php index 0bf328a70..de0a8cab4 100644 --- a/common.php +++ b/common.php @@ -1,507 +1,456 @@ true)); -$loader->register(); +// Get all constants +require_once BB_PATH . '/library/defines.php'; -$server_protocol = ($bb_cfg['cookie_secure']) ? 'https://' : 'http://'; -$server_port = (in_array($bb_cfg['server_port'], array(80, 443))) ? '' : ':' . $bb_cfg['server_port']; -define('FORUM_PATH', $bb_cfg['script_path']); -define('FULL_URL', $server_protocol . $bb_cfg['server_name'] . $server_port . $bb_cfg['script_path']); +// Composer +if (!is_file(BB_PATH . '/vendor/autoload.php')) { + die('🔩 Manual install: Install composer and run composer install.
☕️ Quick install: Run php install.php in CLI mode.'); +} +require_once BB_PATH . '/vendor/autoload.php'; + +/** + * Gets the value of an environment variable. + * + * @param string $key + * @param mixed|null $default + * @return mixed + */ +function env(string $key, mixed $default = null): mixed +{ + return \TorrentPier\Env::get($key, $default); +} + +// Load ENV +try { + $dotenv = Dotenv\Dotenv::createMutable(BB_PATH); + $dotenv->load(); +} catch (\Dotenv\Exception\InvalidPathException $pathException) { + die('🔩 Manual install: Rename from .env.example to .env, and configure it.
☕️ Quick install: Run php install.php in CLI mode.'); +} + +// Load config +require_once BB_PATH . '/library/config.php'; + +// Local config +if (is_file(BB_PATH . '/library/config.local.php')) { + require_once BB_PATH . '/library/config.local.php'; +} + +/** @noinspection PhpUndefinedVariableInspection */ +// Initialize Config singleton, bb_cfg from global file config +$config = \TorrentPier\Config::init($bb_cfg); + +/** + * Get the Config instance + * + * @return \TorrentPier\Config + */ +function config(): \TorrentPier\Config +{ + return \TorrentPier\Config::getInstance(); +} + +/** + * Get the Censor instance + * + * @return \TorrentPier\Censor + */ +function censor(): \TorrentPier\Censor +{ + return \TorrentPier\Censor::getInstance(); +} + +/** + * Get the Dev instance + * + * @return \TorrentPier\Dev + */ +function dev(): \TorrentPier\Dev +{ + return \TorrentPier\Dev::getInstance(); +} + +/** + * Get the Language instance + * + * @return \TorrentPier\Language + */ +function lang(): \TorrentPier\Language +{ + return \TorrentPier\Language::getInstance(); +} + +/** + * Get a language string (shorthand for lang()->get()) + * + * @param string $key Language key, supports dot notation (e.g., 'DATETIME.TODAY') + * @param mixed $default Default value if key doesn't exist + * @return mixed Language string or default value + */ +function __(string $key, mixed $default = null): mixed +{ + return \TorrentPier\Language::getInstance()->get($key, $default); +} + +/** + * Echo a language string (shorthand for echo __()) + * + * @param string $key Language key, supports dot notation + * @param mixed $default Default value if key doesn't exist + * @return void + */ +function _e(string $key, mixed $default = null): void +{ + echo \TorrentPier\Language::getInstance()->get($key, $default); +} + +/** + * Initialize debug + */ +define('APP_ENV', env('APP_ENV', 'production')); +if (APP_ENV === 'development') { + define('DBG_USER', true); // forced debug +} else { + define('DBG_USER', isset($_COOKIE[COOKIE_DBG])); +} +(\TorrentPier\Dev::init()); + +/** + * Server variables initialize + */ +$server_protocol = config()->get('cookie_secure') ? 'https://' : 'http://'; +$server_port = in_array((int)config()->get('server_port'), [80, 443], true) ? '' : ':' . config()->get('server_port'); +define('FORUM_PATH', config()->get('script_path')); +define('FULL_URL', $server_protocol . config()->get('server_name') . $server_port . config()->get('script_path')); unset($server_protocol, $server_port); -// Debug options -define('DBG_USER', (isset($_COOKIE[COOKIE_DBG]))); - -// Board/Tracker shared constants and functions -define('BB_BT_TORRENTS', 'bb_bt_torrents'); -define('BB_BT_TRACKER', 'bb_bt_tracker'); -define('BB_BT_TRACKER_SNAP', 'bb_bt_tracker_snap'); -define('BB_BT_USERS', 'bb_bt_users'); - -define('BT_AUTH_KEY_LENGTH', 10); - -define('PEER_HASH_PREFIX', 'peer_'); -define('PEERS_LIST_PREFIX', 'peers_list_'); -define('PEER_HASH_EXPIRE', round($bb_cfg['announce_interval'] * (0.85 * $tr_cfg['expire_factor']))); // sec -define('PEERS_LIST_EXPIRE', round($bb_cfg['announce_interval'] * 0.7)); // sec - -define('DL_STATUS_RELEASER', -1); -define('DL_STATUS_DOWN', 0); -define('DL_STATUS_COMPLETE', 1); -define('DL_STATUS_CANCEL', 3); -define('DL_STATUS_WILL', 4); - -define('TOR_TYPE_GOLD', 1); -define('TOR_TYPE_SILVER', 2); - -define('GUEST_UID', -1); -define('BOT_UID', -746); +// Initialize the new DB factory with database configuration +TorrentPier\Database\DatabaseFactory::init(config()->get('db'), config()->get('db_alias', [])); /** - * Database + * Get the Database instance + * + * @param string $db_alias + * @return \TorrentPier\Database\Database */ -// Core DB class -require(CORE_DIR . 'dbs.php'); -$DBS = new DBS($bb_cfg); - -function DB ($db_alias = 'db1') +function DB(string $db_alias = 'db'): \TorrentPier\Database\Database { - global $DBS; - return $DBS->get_db_obj($db_alias); + return TorrentPier\Database\DatabaseFactory::getInstance($db_alias); } +// Initialize Unified Cache System +TorrentPier\Cache\UnifiedCacheSystem::getInstance(config()->all()); + /** - * Cache + * Get cache manager instance (replaces legacy cache system) + * + * @param string $cache_name + * @return \TorrentPier\Cache\CacheManager */ -// Main cache class -require(INC_DIR . 'cache/common.php'); -// Main datastore class -require(INC_DIR . 'datastore/common.php'); - -// Core CACHE class -require(CORE_DIR . 'caches.php'); -$CACHES = new CACHES($bb_cfg); - -function CACHE ($cache_name) +function CACHE(string $cache_name): \TorrentPier\Cache\CacheManager { - global $CACHES; - return $CACHES->get_cache_obj($cache_name); + return TorrentPier\Cache\UnifiedCacheSystem::getInstance()->get_cache_obj($cache_name); } -// Common cache classes -require(INC_DIR . 'cache/memcache.php'); -require(INC_DIR . 'cache/sqlite.php'); -require(INC_DIR . 'cache/redis.php'); -require(INC_DIR . 'cache/apc.php'); -require(INC_DIR . 'cache/xcache.php'); -require(INC_DIR . 'cache/file.php'); - /** -* Datastore -*/ -// Common datastore classes -require(INC_DIR . 'datastore/memcache.php'); -require(INC_DIR . 'datastore/sqlite.php'); -require(INC_DIR . 'datastore/redis.php'); -require(INC_DIR . 'datastore/apc.php'); -require(INC_DIR . 'datastore/xcache.php'); -require(INC_DIR . 'datastore/file.php'); - -// Initialize datastore -switch ($bb_cfg['datastore_type']) + * Get datastore manager instance (replaces legacy datastore system) + * + * @return \TorrentPier\Cache\DatastoreManager + */ +function datastore(): \TorrentPier\Cache\DatastoreManager { - case 'memcache': - $datastore = new datastore_memcache($bb_cfg['cache']['memcache'], $bb_cfg['cache']['prefix']); - break; - - case 'sqlite': - $default_cfg = array( - 'db_file_path' => $bb_cfg['cache']['db_dir'] .'datastore.sqlite.db', - 'pconnect' => true, - 'con_required' => true, - ); - $datastore = new datastore_sqlite($default_cfg, $bb_cfg['cache']['prefix']); - break; - - case 'redis': - $datastore = new datastore_redis($bb_cfg['cache']['redis'], $bb_cfg['cache']['prefix']); - break; - - case 'apc': - $datastore = new datastore_apc($bb_cfg['cache']['prefix']); - break; - - case 'xcache': - $datastore = new datastore_xcache($bb_cfg['cache']['prefix']); - break; - - case 'filecache': - default: $datastore = new datastore_file($bb_cfg['cache']['db_dir'] . 'datastore/', $bb_cfg['cache']['prefix']); + return TorrentPier\Cache\UnifiedCacheSystem::getInstance()->getDatastore(config()->get('datastore_type', 'file')); } -function sql_dbg_enabled () -{ - return (SQL_DEBUG && DBG_USER && !empty($_COOKIE['sql_log'])); -} - -function short_query ($sql, $esc_html = false) -{ - $max_len = 100; - $sql = str_compact($sql); - - if (!empty($_COOKIE['sql_log_full'])) - { - if (mb_strlen($sql, 'UTF-8') > $max_len) - { - $sql = mb_substr($sql, 0, 50) .' [...cut...] '. mb_substr($sql, -50); - } - } - - return ($esc_html) ? htmlCHR($sql, true) : $sql; -} +/** + * Backward compatibility: Global datastore variable + * This allows existing code to continue using global $datastore + */ +$datastore = datastore(); // Functions -function utime () +function utime() { - return array_sum(explode(' ', microtime())); + return array_sum(explode(' ', microtime())); } -function bb_log ($msg, $file_name) +function bb_log($msg, $file_name = 'logs', $return_path = false) { - if (is_array($msg)) - { - $msg = join(LOG_LF, $msg); - } - $file_name .= (LOG_EXT) ? '.'. LOG_EXT : ''; - return file_write($msg, LOG_DIR . $file_name); + if (is_array($msg)) { + $msg = implode(LOG_LF, $msg); + } + $file_name .= (LOG_EXT) ? '.' . LOG_EXT : ''; + + $path = (LOG_DIR . '/' . $file_name); + if ($return_path) { + return $path; + } + + return file_write($msg, $path); } -function file_write ($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $replace_content = false) +function file_write($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $replace_content = false) { - $bytes_written = false; + $bytes_written = false; + clearstatcache(); - if ($max_size && @filesize($file) >= $max_size) - { - $old_name = $file; $ext = ''; - if (preg_match('#^(.+)(\.[^\\/]+)$#', $file, $matches)) - { - $old_name = $matches[1]; $ext = $matches[2]; - } - $new_name = $old_name .'_[old]_'. date('Y-m-d_H-i-s_') . getmypid() . $ext; - clearstatcache(); - if (@file_exists($file) && @filesize($file) >= $max_size && !@file_exists($new_name)) - { - @rename($file, $new_name); - } - } - if (!$fp = @fopen($file, 'ab')) - { - if ($dir_created = bb_mkdir(dirname($file))) - { - $fp = @fopen($file, 'ab'); - } - } - if ($fp) - { - if ($lock) - { - @flock($fp, LOCK_EX); - } - if ($replace_content) - { - @ftruncate($fp, 0); - @fseek($fp, 0, SEEK_SET); - } - $bytes_written = @fwrite($fp, $str); - @fclose($fp); - } + if (is_file($file) && ($max_size && (filesize($file) >= $max_size))) { + $file_parts = pathinfo($file); + $new_name = ($file_parts['dirname'] . '/' . $file_parts['filename'] . '_[old]_' . date('Y-m-d_H-i-s_') . getmypid() . '.' . $file_parts['extension']); + clearstatcache(); + if (!is_file($new_name)) { + rename($file, $new_name); + } + } - return $bytes_written; + clearstatcache(); + if (bb_mkdir(dirname($file))) { + if ($fp = fopen($file, 'ab+')) { + if ($lock) { + flock($fp, LOCK_EX); + } + if ($replace_content) { + ftruncate($fp, 0); + fseek($fp, 0, SEEK_SET); + } + $bytes_written = fwrite($fp, $str); + fclose($fp); + } + } + + return $bytes_written; } -function bb_mkdir ($path, $mode = 0777) +function bb_mkdir($path, $mode = 0777) { - $old_um = umask(0); - $dir = mkdir_rec($path, $mode); - umask($old_um); - return $dir; + $old_um = umask(0); + $dir = mkdir_rec($path, $mode); + umask($old_um); + return $dir; } -function mkdir_rec ($path, $mode) +function mkdir_rec($path, $mode): bool { - if (is_dir($path)) - { - return ($path !== '.' && $path !== '..') ? is_writable($path) : false; - } - else - { - return (mkdir_rec(dirname($path), $mode)) ? @mkdir($path, $mode) : false; - } + if (is_dir($path)) { + return ($path !== '.' && $path !== '..') && is_writable($path); + } + + return mkdir_rec(dirname($path), $mode) && mkdir($path, $mode); } -function verify_id ($id, $length) +function verify_id($id, $length): bool { - return (is_string($id) && preg_match('#^[a-zA-Z0-9]{'. $length .'}$#', $id)); + return (is_string($id) && preg_match('#^[a-zA-Z0-9]{' . $length . '}$#', $id)); } -function clean_filename ($fname) +function clean_filename($fname) { - static $s = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '); - return str_replace($s, '_', str_compact($fname)); + static $s = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', ' ']; + return str_replace($s, '_', str_compact($fname)); } -function encode_ip ($ip) +/** + * Convert special characters to HTML entities + * + * @param $txt + * @param bool $double_encode + * @param int $quote_style + * @param ?string $charset + * @return string + */ +function htmlCHR($txt, bool $double_encode = false, int $quote_style = ENT_QUOTES, ?string $charset = DEFAULT_CHARSET): string { - $d = explode('.', $ip); - return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]); + return (string)htmlspecialchars($txt ?? '', $quote_style, $charset, $double_encode); } -function decode_ip ($ip) +/** + * @param string $str + * @return string + */ +function str_compact($str) { - return long2ip("0x{$ip}"); + return preg_replace('/\s\s+/', ' ', trim($str ?? '')); } -function ip2int ($ip) +/** + * Generate a "random" alphanumeric string. + * + * Should not be considered sufficient for cryptography, etc. + * + * @param int $length + * @return string + * @throws Exception + */ +function make_rand_str(int $length = 10): string { - return (float) sprintf('%u', ip2long($ip)); // для совместимости с 32 битными системами + $pool = str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); + + $randomString = ''; + for ($i = 0; $i < $length; $i++) { + $randomString .= $pool[random_int(0, 61)]; + } + + return $randomString; } -// long2ip( mask_ip_int(ip2int('1.2.3.4'), 24) ) = '1.2.3.255' -function mask_ip_int ($ip, $mask) +/** + * Calculates user ratio + * + * @param array $btu + * @return float|null + */ +function get_bt_ratio(array $btu): ?float { - $ip_int = is_numeric($ip) ? $ip : ip2int($ip); - $ip_masked = $ip_int | ((1 << (32 - $mask)) - 1); - return (float) sprintf('%u', $ip_masked); + return + (!empty($btu['u_down_total']) && $btu['u_down_total'] > MIN_DL_FOR_RATIO) + ? round((($btu['u_up_total'] + $btu['u_up_release'] + $btu['u_up_bonus']) / $btu['u_down_total']), 2) + : null; } -function bb_crc32 ($str) +function array_deep(&$var, $fn, $one_dimensional = false, $array_only = false, $timeout = false) { - return (float) sprintf('%u', crc32($str)); + if ($timeout) { + static $recursions = 0; + if (time() > (TIMENOW + $timeout)) { + return [ + 'timeout' => true, + 'recs' => $recursions + ]; + } + $recursions++; + } + if (is_array($var)) { + foreach ($var as $k => $v) { + if (is_array($v)) { + if ($one_dimensional) { + unset($var[$k]); + } elseif ($array_only) { + $var[$k] = $fn($v); + } else { + array_deep($var[$k], $fn, timeout: $timeout); + } + } elseif (!$array_only) { + $var[$k] = $fn($v); + } + } + } elseif (!$array_only) { + $var = $fn($var); + } } -function hexhex ($value) +/** + * Hide BB_PATH + * + * @param string $path + * @return string + */ +function hide_bb_path(string $path): string { - return dechex(hexdec($value)); + return ltrim(str_replace(BB_PATH, '', $path), '/\\'); } -function verify_ip ($ip) +/** + * Returns memory usage statistic + * + * @param string $param + * @return int|void + */ +function sys(string $param) { - return preg_match('#^(\d{1,3}\.){3}\d{1,3}$#', $ip); + switch ($param) { + case 'mem': + return memory_get_usage(); + case 'mem_peak': + return memory_get_peak_usage(); + default: + trigger_error("invalid param: $param", E_USER_ERROR); + } } -function str_compact ($str) -{ - return preg_replace('#\s+#u', ' ', trim($str)); +/** + * Some shared defines + */ +// Initialize demo mode +define('IN_DEMO_MODE', env('APP_DEMO_MODE', false)); + +// Ratio status +define('RATIO_ENABLED', TR_RATING_LIMITS && MIN_DL_FOR_RATIO > 0); + +// Initialization +if (!defined('IN_TRACKER')) { + // Init board + require_once INC_DIR . '/init_bb.php'; +} else { + define('DUMMY_PEER', pack('Nn', \TorrentPier\Helpers\IPHelper::ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? (int)$_GET['port'] : random_int(1000, 65000))); + + define('PEER_HASH_EXPIRE', round(config()->get('announce_interval') * (0.85 * config()->get('tracker.expire_factor')))); + define('PEERS_LIST_EXPIRE', round(config()->get('announce_interval') * 0.7)); + define('SCRAPE_LIST_EXPIRE', round(config()->get('scrape_interval') * 0.7)); + + define('PEER_HASH_PREFIX', 'peer_'); + define('PEERS_LIST_PREFIX', 'peers_list_'); + define('SCRAPE_LIST_PREFIX', 'scrape_list_'); + + // Init tracker + require_once BB_PATH . '/bt/includes/init_tr.php'; + + header('Content-Type: text/plain'); + header('Pragma: no-cache'); + + if (!defined('IN_ADMIN')) { + // Exit if tracker is disabled via ON/OFF trigger + if (is_file(BB_DISABLED)) { + dummy_exit(random_int(60, 2400)); + } + } } - -function make_rand_str ($len = 10) -{ - $str = ''; - while (strlen($str) < $len) - { - $str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', crypt(uniqid(mt_rand(), true)))); - } - return substr($str, 0, $len); -} - -// bencode: based on OpenTracker -function bencode ($var) -{ - if (is_string($var)) - { - return strlen($var) .':'. $var; - } - else if (is_int($var)) - { - return 'i'. $var .'e'; - } - else if (is_float($var)) - { - return 'i'. sprintf('%.0f', $var) .'e'; - } - else if (is_array($var)) - { - if (count($var) == 0) - { - return 'de'; - } - else - { - $assoc = false; - - foreach ($var as $key => $val) - { - if (!is_int($key)) - { - $assoc = true; - break; - } - } - - if ($assoc) - { - ksort($var, SORT_REGULAR); - $ret = 'd'; - - foreach ($var as $key => $val) - { - $ret .= bencode($key) . bencode($val); - } - return $ret .'e'; - } - else - { - $ret = 'l'; - - foreach ($var as $val) - { - $ret .= bencode($val); - } - return $ret .'e'; - } - } - } - else - { - trigger_error('bencode error: wrong data type', E_USER_ERROR); - } -} - -function array_deep (&$var, $fn, $one_dimensional = false, $array_only = false) -{ - if (is_array($var)) - { - foreach ($var as $k => $v) - { - if (is_array($v)) - { - if ($one_dimensional) - { - unset($var[$k]); - } - else if ($array_only) - { - $var[$k] = $fn($v); - } - else - { - array_deep($var[$k], $fn); - } - } - else if (!$array_only) - { - $var[$k] = $fn($v); - } - } - } - else if (!$array_only) - { - $var = $fn($var); - } -} - -function hide_bb_path ($path) -{ - return ltrim(str_replace(BB_PATH, '', $path), '/\\'); -} - -function sys ($param) -{ - switch ($param) - { - case 'la': - return function_exists('sys_getloadavg') ? join(' ', sys_getloadavg()) : 0; - break; - case 'mem': - return function_exists('memory_get_usage') ? memory_get_usage() : 0; - break; - case 'mem_peak': - return function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : 0; - break; - default: - trigger_error("invalid param: $param", E_USER_ERROR); - } -} - -function ver_compare ($version1, $operator, $version2) -{ - return version_compare($version1, $version2, $operator); -} - -function dbg_log ($str, $file) -{ - $dir = LOG_DIR . (defined('IN_TRACKER') ? 'dbg_tr/' : 'dbg_bb/') . date('m-d_H') .'/'; - return file_write($str, $dir . $file, false, false); -} - -function log_get ($file = '', $prepend_str = false) -{ - log_request($file, $prepend_str, false); -} - -function log_post ($file = '', $prepend_str = false) -{ - log_request($file, $prepend_str, true); -} - -function log_request ($file = '', $prepend_str = false, $add_post = true) -{ - global $user; - - $file = ($file) ? $file : 'req/'. date('m-d'); - $str = array(); - $str[] = date('m-d H:i:s'); - if ($prepend_str !== false) $str[] = $prepend_str; - if (!empty($user->data)) $str[] = $user->id ."\t". html_entity_decode($user->name); - $str[] = sprintf('%-15s', $_SERVER['REMOTE_ADDR']); - - if (isset($_SERVER['REQUEST_URI'])) { - $str[] = $_SERVER['REQUEST_URI']; - } - if (isset($_SERVER['HTTP_USER_AGENT'])) { - $str[] = $_SERVER['HTTP_USER_AGENT']; - } - if (isset($_SERVER['HTTP_REFERER'])) { - $str[] = $_SERVER['HTTP_REFERER']; - } - - if (!empty($_POST) && $add_post) $str[] = "post: ". str_compact(urldecode(http_build_query($_POST))); - $str = join("\t", $str) . "\n"; - bb_log($str, $file); -} - -// Board init -if (defined('IN_FORUM')) -{ - require(INC_DIR .'init_bb.php'); -} -// Tracker init -else if (defined('IN_TRACKER')) -{ - define('DUMMY_PEER', pack('Nn', ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? intval($_GET['port']) : mt_rand(1000, 65000))); - - function dummy_exit ($interval = 1800) - { - $output = bencode(array( - 'interval' => (int) $interval, - 'min interval' => (int) $interval, - 'peers' => (string) DUMMY_PEER, - )); - - die($output); - } - - header('Content-Type: text/plain'); - header('Pragma: no-cache'); - - if (!defined('IN_ADMIN')) - { - // Exit if tracker is disabled via ON/OFF trigger - if (file_exists(BB_DISABLED)) - { - dummy_exit(mt_rand(60, 2400)); - } - } -} \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 000000000..85ef6217d --- /dev/null +++ b/composer.json @@ -0,0 +1,102 @@ +{ + "name": "torrentpier/torrentpier", + "description": "TorrentPier. Bull-powered BitTorrent tracker engine", + "type": "project", + "keywords": [ + "bittorrent", + "forum", + "torrent", + "tracker" + ], + "homepage": "https://github.com/torrentpier", + "license": "MIT", + "authors": [ + { + "name": "Exile", + "email": "admin@torrentpier.com", + "homepage": "https://github.com/Exileum", + "role": "Developer" + }, + { + "name": "Diolektor", + "homepage": "https://github.com/diolektor", + "role": "Developer" + }, + { + "name": "PheRum", + "homepage": "https://github.com/PheRum", + "role": "Developer" + }, + { + "name": "belomaxorka", + "email": "roman25052006.kelesh@gmail.com", + "homepage": "https://github.com/belomaxorka", + "role": "Developer" + }, + { + "name": "kovalensky", + "email": "kovalensky@evergarden.ru", + "homepage": "https://github.com/kovalensky", + "role": "Developer" + } + ], + "support": { + "email": "support@torrentpier.com", + "issues": "https://github.com/torrentpier/torrentpier/issues", + "forum": "https://torrentpier.com" + }, + "require": { + "php": ">=8.2", + "arokettu/bencode": "^4.1.0", + "arokettu/monsterid": "^4.1.0", + "arokettu/random-polyfill": "1.0.2", + "arokettu/torrent-file": "^5.2.1", + "belomaxorka/captcha": "1.*", + "bugsnag/bugsnag": "^v3.29.1", + "claviska/simpleimage": "^4.0", + "egulias/email-validator": "^4.0.1", + "filp/whoops": "^2.15", + "gemorroj/m3u-parser": "^6.0.1", + "gigablah/sphinxphp": "2.0.8", + "google/recaptcha": "^1.3", + "jacklul/monolog-telegram": "^3.1", + "josantonius/cookie": "^2.0", + "league/flysystem": "^3.28", + "longman/ip-tools": "1.2.1", + "monolog/monolog": "^3.4", + "nette/caching": "^3.3", + "nette/database": "^3.2", + "php-curl-class/php-curl-class": "^12.0.0", + "robmorgan/phinx": "^0.16.9", + "samdark/sitemap": "2.4.1", + "symfony/mailer": "^7.3", + "symfony/polyfill": "v1.32.0", + "vlucas/phpdotenv": "^5.5", + "z4kn4fein/php-semver": "^v3.0.0" + }, + "require-dev": { + "mockery/mockery": "^1.6", + "pestphp/pest": "^3.8", + "symfony/var-dumper": "^7.3" + }, + "autoload": { + "psr-4": { + "TorrentPier\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + } + }, + "config": { + "sort-packages": true, + "optimize-autoloader": true, + "allow-plugins": { + "pestphp/pest-plugin": true, + "php-http/discovery": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 000000000..095574af1 --- /dev/null +++ b/composer.lock @@ -0,0 +1,7646 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "7c0b87c0c30183dc306f763c724beafc", + "packages": [ + { + "name": "arokettu/bencode", + "version": "4.3.1", + "source": { + "type": "git", + "url": "https://github.com/arokettu/bencode.git", + "reference": "0955a7037670c24d5ae5fdafe5ff5894aba024e7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/arokettu/bencode/zipball/0955a7037670c24d5ae5fdafe5ff5894aba024e7", + "reference": "0955a7037670c24d5ae5fdafe5ff5894aba024e7", + "shasum": "" + }, + "require": { + "arokettu/is-resource": "^1.0", + "php": "^8.1" + }, + "require-dev": { + "brick/math": "*", + "ext-bcmath": "*", + "ext-gmp": "*", + "ext-json": "*", + "mikey179/vfsstream": "^1.6.11", + "pear/math_biginteger": "^1.0", + "phpunit/phpunit": "^10.5.28", + "psy/psysh": "*", + "sandfox.dev/code-standard": "^1.2025.05.07", + "squizlabs/php_codesniffer": "*", + "vimeo/psalm": "^6" + }, + "suggest": { + "brick/math": "In case you need integers larger than your architecture supports", + "ext-bcmath": "In case you need integers larger than your architecture supports (PHP 8.4 or later)", + "ext-gmp": "In case you need integers larger than your architecture supports", + "pear/math_biginteger": "In case you need integers larger than your architecture supports", + "php-64bit": "Running 64 bit is recommended to prevent integer overflow" + }, + "type": "library", + "autoload": { + "psr-4": { + "Arokettu\\Bencode\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anton Smirnov", + "email": "sandfox@sandfox.me", + "homepage": "https://sandfox.me", + "role": "developer" + } + ], + "description": "BitTorrent's Bencode encoder/decoder", + "homepage": "https://sandfox.dev/php/bencode.html", + "keywords": [ + "bencode", + "bittorrent", + "serialize", + "torrent" + ], + "support": { + "chat": "https://gitter.im/arokettu/community", + "docs": "https://bencode.readthedocs.io/", + "issues": "https://gitlab.com/sandfox/bencode/-/issues", + "source": "https://gitlab.com/sandfox/bencode" + }, + "time": "2025-05-20T19:25:23+00:00" + }, + { + "name": "arokettu/is-resource", + "version": "1.0.4", + "source": { + "type": "git", + "url": "https://github.com/arokettu/is-resource.git", + "reference": "6a4966bf4608c69d20b7bf01670b49901a51eb9d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/arokettu/is-resource/zipball/6a4966bf4608c69d20b7bf01670b49901a51eb9d", + "reference": "6a4966bf4608c69d20b7bf01670b49901a51eb9d", + "shasum": "" + }, + "require": { + "php": ">= 5.3 < 8.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions.php" + ], + "classmap": [ + "gen/ResourceMap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anton Smirnov", + "email": "sandfox@sandfox.me", + "homepage": "https://sandfox.me/", + "role": "developer" + } + ], + "description": "Future compatible is_resource() and get_resource_type() that can understand objects that replaced earlier resources", + "homepage": "https://sandfox.dev/php/is-resource.html", + "keywords": [ + "compatibility", + "curl", + "gd", + "get_resource_type", + "hash", + "is_resource", + "pgsql", + "php80", + "php81", + "resources", + "sockets" + ], + "support": { + "chat": "https://gitter.im/arokettu/community", + "docs": "https://is-resource.readthedocs.io/", + "issues": "https://gitlab.com/sandfox/is-resource/-/issues", + "source": "https://gitlab.com/sandfox/is-resource" + }, + "time": "2024-08-27T04:34:45+00:00" + }, + { + "name": "arokettu/monsterid", + "version": "4.1.0", + "source": { + "type": "git", + "url": "https://github.com/arokettu/monsterid.git", + "reference": "4e7484a593c42eba960ee555877dd9b26577fe8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/arokettu/monsterid/zipball/4e7484a593c42eba960ee555877dd9b26577fe8a", + "reference": "4e7484a593c42eba960ee555877dd9b26577fe8a", + "shasum": "" + }, + "require": { + "arokettu/is-resource": "^1.0", + "arokettu/random-polyfill": "^1.0.1", + "ext-gd": "*", + "php": "^8.0", + "psr/http-factory": "^1.0" + }, + "require-dev": { + "arokettu/random-polyfill": ">= 1.0.1 < 1.99", + "httpsoft/http-message": "^1.1", + "php-http/discovery": "^1.20", + "phpunit/phpunit": ">= 7.0 < 10", + "psy/psysh": "*", + "sandfox.dev/code-standard": "^1.2025.03.27", + "slim/psr7": "^1.7", + "squizlabs/php_codesniffer": "*", + "vimeo/psalm": "^5.4 || ^6.0" + }, + "type": "library", + "extra": { + "discovery": { + "psr/http-factory-implementation": "Arokettu\\MonsterID\\Tests\\Helpers\\HttpFactory" + } + }, + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Arokettu\\MonsterID\\": "src/classes" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Andreas Gohr", + "homepage": "https://www.splitbrain.org/", + "role": "developer" + }, + { + "name": "Anton Smirnov", + "email": "sandfox+composer@sandfox.me", + "homepage": "https://sandfox.me/", + "role": "maintainer" + } + ], + "description": "MonsterID is a method to generate a unique monster image based upon a certain identifier (IP address, email address, whatever). It can be used to automatically provide personal avatar images in blog comments or other community services.", + "homepage": "https://sandfox.dev/php/monsterid.html", + "keywords": [ + "avatar", + "monsterid" + ], + "support": { + "chat": "https://gitter.im/arokettu/community", + "docs": "https://monsterid.readthedocs.io/", + "issues": "https://gitlab.com/sandfox/monsterid/-/issues", + "source": "https://gitlab.com/sandfox/monsterid" + }, + "time": "2025-04-03T13:37:00+00:00" + }, + { + "name": "arokettu/random-polyfill", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/arokettu/php-random-polyfill.git", + "reference": "1c36416a2b507d5aa6c0a6d7f7b8aa2c539f8361" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/arokettu/php-random-polyfill/zipball/1c36416a2b507d5aa6c0a6d7f7b8aa2c539f8361", + "reference": "1c36416a2b507d5aa6c0a6d7f7b8aa2c539f8361", + "shasum": "" + }, + "require": { + "arokettu/unsigned": "^1.2.1", + "php": "^7.1 | ^8.0", + "symfony/polyfill-php80": "^1.22", + "symfony/polyfill-php81": "^1.22", + "symfony/polyfill-php82": "^1.27" + }, + "provide": { + "ext-random": "8.2.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.5 | ^8.5 | 9.5.*", + "psy/psysh": "*", + "sandfox.dev/code-standard": "^1", + "squizlabs/php_codesniffer": "*", + "vimeo/psalm": "^4.24" + }, + "suggest": { + "ext-gmp": "For significantly faster calculation" + }, + "type": "library", + "autoload": { + "psr-0": { + "Random\\": "src", + "Arokettu\\Random\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Anton Smirnov", + "email": "sandfox@sandfox.me", + "homepage": "https://sandfox.me/", + "role": "developer" + } + ], + "description": "Random Extension Polyfill for PHP", + "homepage": "https://sandfox.dev/php/random-polyfill.html", + "keywords": [ + "polyfill", + "random" + ], + "support": { + "chat": "https://gitter.im/arokettu/community", + "docs": "https://php-random-polyfill.readthedocs.io/", + "issues": "https://github.com/arokettu/php-random-polyfill/issues", + "source": "https://github.com/arokettu/php-random-polyfill" + }, + "time": "2023-09-07T13:01:52+00:00" + }, + { + "name": "arokettu/torrent-file", + "version": "5.3.1", + "source": { + "type": "git", + "url": "https://github.com/arokettu/torrent-file.git", + "reference": "650ed7109bcd01dd6c4f47d129f120eb1f82ca07" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/arokettu/torrent-file/zipball/650ed7109bcd01dd6c4f47d129f120eb1f82ca07", + "reference": "650ed7109bcd01dd6c4f47d129f120eb1f82ca07", + "shasum": "" + }, + "require": { + "arokettu/bencode": "^2.8 | ^3.1 | ^4.0", + "ext-hash": "*", + "nikic/iter": "^2.2", + "php": "^8.1", + "psr/event-dispatcher": "^1.0", + "symfony/filesystem": "^5.4 | ^6.0 | ^7.0", + "symfony/finder": "^5.4 | ^6.0 | ^7.0" + }, + "require-dev": { + "ext-openssl": "*", + "jetbrains/phpstorm-attributes": "^1.0", + "league/event": "^3.0", + "phpunit/phpunit": "^10.5.3", + "psy/psysh": "*", + "sandfox.dev/code-standard": "^1.2024.07.05", + "squizlabs/php_codesniffer": "*", + "vimeo/psalm": "^5.2" + }, + "suggest": { + "ext-openssl": "for signature logic" + }, + "type": "library", + "autoload": { + "psr-4": { + "Arokettu\\Torrent\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anton Smirnov", + "email": "sandfox@sandfox.me", + "homepage": "https://sandfox.me/", + "role": "developer" + } + ], + "description": "A class to work with torrent files", + "homepage": "https://sandfox.dev/php/torrent-file.html", + "keywords": [ + "bittorrent", + "torrent", + "torrent-file" + ], + "support": { + "chat": "https://gitter.im/arokettu/community", + "docs": "https://torrent-file.readthedocs.io/", + "issues": "https://gitlab.com/sandfox/torrent-file/-/issues", + "source": "https://gitlab.com/sandfox/torrent-file" + }, + "time": "2024-07-28T21:43:34+00:00" + }, + { + "name": "arokettu/unsigned", + "version": "1.3.6", + "source": { + "type": "git", + "url": "https://github.com/arokettu/unsigned.git", + "reference": "1e5b3a131d669ee31c4d941bc27e4ba4ef64ae76" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/arokettu/unsigned/zipball/1e5b3a131d669ee31c4d941bc27e4ba4ef64ae76", + "reference": "1e5b3a131d669ee31c4d941bc27e4ba4ef64ae76", + "shasum": "" + }, + "require": { + "php": "^7.0 | ^8.0" + }, + "require-dev": { + "phpunit/phpunit": ">= 6.5 <10", + "psy/psysh": "*", + "sandfox.dev/code-standard": "^1.2025.03.27", + "squizlabs/php_codesniffer": "*" + }, + "type": "library", + "autoload": { + "files": [ + "src/lib.php" + ], + "classmap": [ + "src/Unsigned.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Anton Smirnov", + "email": "sandfox@sandfox.me", + "homepage": "https://sandfox.me/", + "role": "developer" + } + ], + "description": "Fixed length unsigned arithmetic emulation", + "homepage": "https://sandfox.dev/php/unsigned.html", + "keywords": [ + "arithmetic", + "unsigned" + ], + "support": { + "chat": "https://gitter.im/arokettu/community", + "docs": "https://php-unsigned.readthedocs.io/", + "issues": "https://gitlab.com/sandfox/unsigned/-/issues", + "source": "https://gitlab.com/sandfox/unsigned" + }, + "time": "2025-03-31T23:49:37+00:00" + }, + { + "name": "belomaxorka/captcha", + "version": "v1.2.4", + "source": { + "type": "git", + "url": "https://github.com/belomaxorka/Captcha.git", + "reference": "db51723a9539b57ac3faff0211c117b4c55dbe23" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/belomaxorka/Captcha/zipball/db51723a9539b57ac3faff0211c117b4c55dbe23", + "reference": "db51723a9539b57ac3faff0211c117b4c55dbe23", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "ext-gd": "*", + "ext-mbstring": "*", + "php": ">=5.3.0", + "symfony/finder": "*" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35 || ^5.7.21 || ^6.4 || ^7.0 || ^8.0 || ^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Gregwar\\": "src/Gregwar" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Grégoire Passault", + "email": "g.passault@gmail.com", + "homepage": "https://www.gregwar.com/", + "role": "Developer" + }, + { + "name": "Jeremy Livingston", + "email": "jeremy.j.livingston@gmail.com" + }, + { + "name": "belomaxorka", + "email": "roman25052006.kelesh@gmail.com", + "homepage": "https://belomaxorka.github.io/", + "role": "Developer" + } + ], + "description": "Captcha generator", + "homepage": "https://github.com/belomaxorka/Captcha", + "keywords": [ + "anti-bot", + "anti-spam", + "bot-protection", + "captcha", + "no-bot", + "obfuscation", + "security", + "spam", + "spam-protection" + ], + "support": { + "source": "https://github.com/belomaxorka/Captcha/tree/v1.2.4" + }, + "time": "2025-03-10T13:15:53+00:00" + }, + { + "name": "bugsnag/bugsnag", + "version": "v3.29.3", + "source": { + "type": "git", + "url": "https://github.com/bugsnag/bugsnag-php.git", + "reference": "9d9aa665f5e9d24f45aad5114dbd2d861119febb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bugsnag/bugsnag-php/zipball/9d9aa665f5e9d24f45aad5114dbd2d861119febb", + "reference": "9d9aa665f5e9d24f45aad5114dbd2d861119febb", + "shasum": "" + }, + "require": { + "composer/ca-bundle": "^1.0", + "guzzlehttp/guzzle": "^5.0|^6.0|^7.0", + "php": ">=5.5" + }, + "require-dev": { + "guzzlehttp/psr7": "^1.3|^2.0", + "mtdowling/burgomaster": "dev-master#72151eddf5f0cf101502b94bf5031f9c53501a04", + "php-mock/php-mock-phpunit": "^1.1|^2.1", + "phpunit/phpunit": "^4.8.36|^7.5.15|^9.3.10", + "sebastian/version": ">=1.0.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.20-dev" + } + }, + "autoload": { + "psr-4": { + "Bugsnag\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "James Smith", + "email": "notifiers@bugsnag.com", + "homepage": "https://bugsnag.com" + } + ], + "description": "Official Bugsnag notifier for PHP applications.", + "homepage": "https://github.com/bugsnag/bugsnag-php", + "keywords": [ + "bugsnag", + "errors", + "exceptions", + "logging", + "tracking" + ], + "support": { + "issues": "https://github.com/bugsnag/bugsnag-php/issues", + "source": "https://github.com/bugsnag/bugsnag-php/tree/v3.29.3" + }, + "time": "2025-03-06T12:03:07+00:00" + }, + { + "name": "cakephp/chronos", + "version": "3.1.0", + "source": { + "type": "git", + "url": "https://github.com/cakephp/chronos.git", + "reference": "786d69e1ee4b735765cbdb5521b9603e9b98d650" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cakephp/chronos/zipball/786d69e1ee4b735765cbdb5521b9603e9b98d650", + "reference": "786d69e1ee4b735765cbdb5521b9603e9b98d650", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/clock": "^1.0" + }, + "provide": { + "psr/clock-implementation": "1.0" + }, + "require-dev": { + "cakephp/cakephp-codesniffer": "^5.0", + "phpunit/phpunit": "^10.1.0 || ^11.1.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Cake\\Chronos\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brian Nesbitt", + "email": "brian@nesbot.com", + "homepage": "http://nesbot.com" + }, + { + "name": "The CakePHP Team", + "homepage": "https://cakephp.org" + } + ], + "description": "A simple API extension for DateTime.", + "homepage": "https://cakephp.org", + "keywords": [ + "date", + "datetime", + "time" + ], + "support": { + "issues": "https://github.com/cakephp/chronos/issues", + "source": "https://github.com/cakephp/chronos" + }, + "time": "2024-07-18T03:18:04+00:00" + }, + { + "name": "cakephp/core", + "version": "5.2.5", + "source": { + "type": "git", + "url": "https://github.com/cakephp/core.git", + "reference": "a0a92ee7fbb7b7555dbf4ea7ff3fd4e779693da6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cakephp/core/zipball/a0a92ee7fbb7b7555dbf4ea7ff3fd4e779693da6", + "reference": "a0a92ee7fbb7b7555dbf4ea7ff3fd4e779693da6", + "shasum": "" + }, + "require": { + "cakephp/utility": "5.2.*@dev", + "league/container": "^4.2", + "php": ">=8.1", + "psr/container": "^1.1 || ^2.0" + }, + "provide": { + "psr/container-implementation": "^2.0" + }, + "suggest": { + "cakephp/cache": "To use Configure::store() and restore().", + "cakephp/event": "To use PluginApplicationInterface or plugin applications.", + "league/container": "To use Container and ServiceProvider classes" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-5.x": "5.2.x-dev" + } + }, + "autoload": { + "files": [ + "functions.php" + ], + "psr-4": { + "Cake\\Core\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "CakePHP Community", + "homepage": "https://github.com/cakephp/core/graphs/contributors" + } + ], + "description": "CakePHP Framework Core classes", + "homepage": "https://cakephp.org", + "keywords": [ + "cakephp", + "core", + "framework" + ], + "support": { + "forum": "https://stackoverflow.com/tags/cakephp", + "irc": "irc://irc.freenode.org/cakephp", + "issues": "https://github.com/cakephp/cakephp/issues", + "source": "https://github.com/cakephp/core" + }, + "time": "2025-04-19T12:34:03+00:00" + }, + { + "name": "cakephp/database", + "version": "5.2.5", + "source": { + "type": "git", + "url": "https://github.com/cakephp/database.git", + "reference": "a6bf606b1bab532d04ea504fef8a272a1aeba287" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cakephp/database/zipball/a6bf606b1bab532d04ea504fef8a272a1aeba287", + "reference": "a6bf606b1bab532d04ea504fef8a272a1aeba287", + "shasum": "" + }, + "require": { + "cakephp/chronos": "^3.1", + "cakephp/core": "5.2.*@dev", + "cakephp/datasource": "5.2.*@dev", + "php": ">=8.1", + "psr/log": "^3.0" + }, + "require-dev": { + "cakephp/i18n": "5.2.*@dev", + "cakephp/log": "5.2.*@dev" + }, + "suggest": { + "cakephp/i18n": "If you are using locale-aware datetime formats.", + "cakephp/log": "If you want to use query logging without providing a logger yourself." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-5.x": "5.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Cake\\Database\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "CakePHP Community", + "homepage": "https://github.com/cakephp/database/graphs/contributors" + } + ], + "description": "Flexible and powerful Database abstraction library with a familiar PDO-like API", + "homepage": "https://cakephp.org", + "keywords": [ + "abstraction", + "cakephp", + "database", + "database abstraction", + "pdo" + ], + "support": { + "forum": "https://stackoverflow.com/tags/cakephp", + "irc": "irc://irc.freenode.org/cakephp", + "issues": "https://github.com/cakephp/cakephp/issues", + "source": "https://github.com/cakephp/database" + }, + "time": "2025-06-18T02:55:13+00:00" + }, + { + "name": "cakephp/datasource", + "version": "5.2.5", + "source": { + "type": "git", + "url": "https://github.com/cakephp/datasource.git", + "reference": "f7dc4292bec0ec746db3200a5b18bb371d50dab3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cakephp/datasource/zipball/f7dc4292bec0ec746db3200a5b18bb371d50dab3", + "reference": "f7dc4292bec0ec746db3200a5b18bb371d50dab3", + "shasum": "" + }, + "require": { + "cakephp/core": "5.2.*@dev", + "php": ">=8.1", + "psr/simple-cache": "^2.0 || ^3.0" + }, + "require-dev": { + "cakephp/cache": "5.2.*@dev", + "cakephp/collection": "5.2.*@dev", + "cakephp/utility": "5.2.*@dev" + }, + "suggest": { + "cakephp/cache": "If you decide to use Query caching.", + "cakephp/collection": "If you decide to use ResultSetInterface.", + "cakephp/utility": "If you decide to use EntityTrait." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-5.x": "5.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Cake\\Datasource\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "CakePHP Community", + "homepage": "https://github.com/cakephp/datasource/graphs/contributors" + } + ], + "description": "Provides connection managing and traits for Entities and Queries that can be reused for different datastores", + "homepage": "https://cakephp.org", + "keywords": [ + "cakephp", + "connection management", + "datasource", + "entity", + "query" + ], + "support": { + "forum": "https://stackoverflow.com/tags/cakephp", + "irc": "irc://irc.freenode.org/cakephp", + "issues": "https://github.com/cakephp/cakephp/issues", + "source": "https://github.com/cakephp/datasource" + }, + "time": "2025-04-26T23:00:26+00:00" + }, + { + "name": "cakephp/utility", + "version": "5.2.5", + "source": { + "type": "git", + "url": "https://github.com/cakephp/utility.git", + "reference": "7eaef40766bf671332adfacdc2d6fb9ea8aea5de" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cakephp/utility/zipball/7eaef40766bf671332adfacdc2d6fb9ea8aea5de", + "reference": "7eaef40766bf671332adfacdc2d6fb9ea8aea5de", + "shasum": "" + }, + "require": { + "cakephp/core": "5.2.*@dev", + "php": ">=8.1" + }, + "suggest": { + "ext-intl": "To use Text::transliterate() or Text::slug()", + "lib-ICU": "To use Text::transliterate() or Text::slug()" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-5.x": "5.2.x-dev" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Cake\\Utility\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "CakePHP Community", + "homepage": "https://github.com/cakephp/utility/graphs/contributors" + } + ], + "description": "CakePHP Utility classes such as Inflector, String, Hash, and Security", + "homepage": "https://cakephp.org", + "keywords": [ + "cakephp", + "hash", + "inflector", + "security", + "string", + "utility" + ], + "support": { + "forum": "https://stackoverflow.com/tags/cakephp", + "irc": "irc://irc.freenode.org/cakephp", + "issues": "https://github.com/cakephp/cakephp/issues", + "source": "https://github.com/cakephp/utility" + }, + "time": "2025-05-21T14:35:19+00:00" + }, + { + "name": "claviska/simpleimage", + "version": "4.2.1", + "source": { + "type": "git", + "url": "https://github.com/claviska/SimpleImage.git", + "reference": "ec6d5021e5a7153a2520d64c59b86b6f3c4157c5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/claviska/SimpleImage/zipball/ec6d5021e5a7153a2520d64c59b86b6f3c4157c5", + "reference": "ec6d5021e5a7153a2520d64c59b86b6f3c4157c5", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "league/color-extractor": "0.4.*", + "php": ">=8.0" + }, + "require-dev": { + "laravel/pint": "^1.5", + "phpstan/phpstan": "^1.10" + }, + "type": "library", + "autoload": { + "psr-0": { + "claviska": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Cory LaViska", + "homepage": "http://www.abeautifulsite.net/", + "role": "Developer" + } + ], + "description": "A PHP class that makes working with images as simple as possible.", + "support": { + "issues": "https://github.com/claviska/SimpleImage/issues", + "source": "https://github.com/claviska/SimpleImage/tree/4.2.1" + }, + "funding": [ + { + "url": "https://github.com/claviska", + "type": "github" + } + ], + "time": "2024-11-22T13:25:03+00:00" + }, + { + "name": "composer/ca-bundle", + "version": "1.5.7", + "source": { + "type": "git", + "url": "https://github.com/composer/ca-bundle.git", + "reference": "d665d22c417056996c59019579f1967dfe5c1e82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/ca-bundle/zipball/d665d22c417056996c59019579f1967dfe5c1e82", + "reference": "d665d22c417056996c59019579f1967dfe5c1e82", + "shasum": "" + }, + "require": { + "ext-openssl": "*", + "ext-pcre": "*", + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^8 || ^9", + "psr/log": "^1.0 || ^2.0 || ^3.0", + "symfony/process": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\CaBundle\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.", + "keywords": [ + "cabundle", + "cacert", + "certificate", + "ssl", + "tls" + ], + "support": { + "irc": "irc://irc.freenode.org/composer", + "issues": "https://github.com/composer/ca-bundle/issues", + "source": "https://github.com/composer/ca-bundle/tree/1.5.7" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2025-05-26T15:08:54+00:00" + }, + { + "name": "doctrine/lexer", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd", + "reference": "31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "doctrine/coding-standard": "^12", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^10.5", + "psalm/plugin-phpunit": "^0.18.3", + "vimeo/psalm": "^5.21" + }, + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\Common\\Lexer\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https://www.doctrine-project.org/projects/lexer.html", + "keywords": [ + "annotations", + "docblock", + "lexer", + "parser", + "php" + ], + "support": { + "issues": "https://github.com/doctrine/lexer/issues", + "source": "https://github.com/doctrine/lexer/tree/3.0.1" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Flexer", + "type": "tidelift" + } + ], + "time": "2024-02-05T11:56:58+00:00" + }, + { + "name": "egulias/email-validator", + "version": "4.0.4", + "source": { + "type": "git", + "url": "https://github.com/egulias/EmailValidator.git", + "reference": "d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa", + "reference": "d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa", + "shasum": "" + }, + "require": { + "doctrine/lexer": "^2.0 || ^3.0", + "php": ">=8.1", + "symfony/polyfill-intl-idn": "^1.26" + }, + "require-dev": { + "phpunit/phpunit": "^10.2", + "vimeo/psalm": "^5.12" + }, + "suggest": { + "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Egulias\\EmailValidator\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eduardo Gulias Davis" + } + ], + "description": "A library for validating emails against several RFCs", + "homepage": "https://github.com/egulias/EmailValidator", + "keywords": [ + "email", + "emailvalidation", + "emailvalidator", + "validation", + "validator" + ], + "support": { + "issues": "https://github.com/egulias/EmailValidator/issues", + "source": "https://github.com/egulias/EmailValidator/tree/4.0.4" + }, + "funding": [ + { + "url": "https://github.com/egulias", + "type": "github" + } + ], + "time": "2025-03-06T22:45:56+00:00" + }, + { + "name": "filp/whoops", + "version": "2.18.3", + "source": { + "type": "git", + "url": "https://github.com/filp/whoops.git", + "reference": "59a123a3d459c5a23055802237cb317f609867e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/filp/whoops/zipball/59a123a3d459c5a23055802237cb317f609867e5", + "reference": "59a123a3d459c5a23055802237cb317f609867e5", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^7.5.20 || ^8.5.8 || ^9.3.3", + "symfony/var-dumper": "^4.0 || ^5.0" + }, + "suggest": { + "symfony/var-dumper": "Pretty print complex values better with var-dumper available", + "whoops/soap": "Formats errors as SOAP responses" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7-dev" + } + }, + "autoload": { + "psr-4": { + "Whoops\\": "src/Whoops/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Filipe Dobreira", + "homepage": "https://github.com/filp", + "role": "Developer" + } + ], + "description": "php error handling for cool kids", + "homepage": "https://filp.github.io/whoops/", + "keywords": [ + "error", + "exception", + "handling", + "library", + "throwable", + "whoops" + ], + "support": { + "issues": "https://github.com/filp/whoops/issues", + "source": "https://github.com/filp/whoops/tree/2.18.3" + }, + "funding": [ + { + "url": "https://github.com/denis-sokolov", + "type": "github" + } + ], + "time": "2025-06-16T00:02:10+00:00" + }, + { + "name": "gemorroj/m3u-parser", + "version": "6.0.1", + "source": { + "type": "git", + "url": "https://github.com/Gemorroj/M3uParser.git", + "reference": "92fc0fe236d77e1b5a26c735ffcb6fc637eb298a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Gemorroj/M3uParser/zipball/92fc0fe236d77e1b5a26c735ffcb6fc637eb298a", + "reference": "92fc0fe236d77e1b5a26c735ffcb6fc637eb298a", + "shasum": "" + }, + "require": { + "php": ">=8.0.2" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.73.1", + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^9.6.22" + }, + "type": "library", + "autoload": { + "psr-4": { + "M3uParser\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "Gemorroj" + } + ], + "description": "m3u playlist parser/generator", + "keywords": [ + "m3u", + "m3u8", + "playlist" + ], + "support": { + "issues": "https://github.com/Gemorroj/M3uParser/issues", + "source": "https://github.com/Gemorroj/M3uParser/tree/6.0.1" + }, + "time": "2025-03-25T19:21:43+00:00" + }, + { + "name": "gigablah/sphinxphp", + "version": "2.0.8", + "source": { + "type": "git", + "url": "https://github.com/gigablah/sphinxphp.git", + "reference": "6d5e97fdd33c1129ca372203d1330827c1cbc46c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/gigablah/sphinxphp/zipball/6d5e97fdd33c1129ca372203d1330827c1cbc46c", + "reference": "6d5e97fdd33c1129ca372203d1330827c1cbc46c", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*", + "satooshi/php-coveralls": "dev-master" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "Sphinx": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0" + ], + "authors": [ + { + "name": "Andrew Aksyonoff", + "homepage": "http://sphinxsearch.com/" + } + ], + "description": "Sphinx Search PHP API", + "homepage": "http://sphinxsearch.com/", + "keywords": [ + "api", + "search", + "sphinx" + ], + "support": { + "issues": "https://github.com/gigablah/sphinxphp/issues", + "source": "https://github.com/gigablah/sphinxphp/tree/2.0.x" + }, + "time": "2013-08-22T08:05:44+00:00" + }, + { + "name": "google/recaptcha", + "version": "1.3.0", + "source": { + "type": "git", + "url": "https://github.com/google/recaptcha.git", + "reference": "d59a801e98a4e9174814a6d71bbc268dff1202df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/google/recaptcha/zipball/d59a801e98a4e9174814a6d71bbc268dff1202df", + "reference": "d59a801e98a4e9174814a6d71bbc268dff1202df", + "shasum": "" + }, + "require": { + "php": ">=8" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.14", + "php-coveralls/php-coveralls": "^2.5", + "phpunit/phpunit": "^10" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "psr-4": { + "ReCaptcha\\": "src/ReCaptcha" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "Client library for reCAPTCHA, a free service that protects websites from spam and abuse.", + "homepage": "https://www.google.com/recaptcha/", + "keywords": [ + "Abuse", + "captcha", + "recaptcha", + "spam" + ], + "support": { + "forum": "https://groups.google.com/forum/#!forum/recaptcha", + "issues": "https://github.com/google/recaptcha/issues", + "source": "https://github.com/google/recaptcha" + }, + "time": "2023-02-18T17:41:46+00:00" + }, + { + "name": "graham-campbell/result-type", + "version": "v1.1.3", + "source": { + "type": "git", + "url": "https://github.com/GrahamCampbell/Result-Type.git", + "reference": "3ba905c11371512af9d9bdd27d99b782216b6945" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/3ba905c11371512af9d9bdd27d99b782216b6945", + "reference": "3ba905c11371512af9d9bdd27d99b782216b6945", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.3" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.39 || ^9.6.20 || ^10.5.28" + }, + "type": "library", + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "An Implementation Of The Result Type", + "keywords": [ + "Graham Campbell", + "GrahamCampbell", + "Result Type", + "Result-Type", + "result" + ], + "support": { + "issues": "https://github.com/GrahamCampbell/Result-Type/issues", + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", + "type": "tidelift" + } + ], + "time": "2024-07-20T21:45:45+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.9.3", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "7b2f29fe81dc4da0ca0ea7d42107a0845946ea77" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/7b2f29fe81dc4da0ca0ea7d42107a0845946ea77", + "reference": "7b2f29fe81dc4da0ca0ea7d42107a0845946ea77", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.3", + "guzzlehttp/psr7": "^2.7.0", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "guzzle/client-integration-tests": "3.0.2", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.39 || ^9.6.20", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.9.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2025-03-27T13:37:11+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "2.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "7c69f28996b0a6920945dd20b3857e499d9ca96c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/7c69f28996b0a6920945dd20b3857e499d9ca96c", + "reference": "7c69f28996b0a6920945dd20b3857e499d9ca96c", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.39 || ^9.6.20" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/2.2.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2025-03-27T13:27:01+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.7.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "c2270caaabe631b3b44c85f99e5a04bbb8060d16" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/c2270caaabe631b3b44c85f99e5a04bbb8060d16", + "reference": "c2270caaabe631b3b44c85f99e5a04bbb8060d16", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "0.9.0", + "phpunit/phpunit": "^8.5.39 || ^9.6.20" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.7.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2025-03-27T12:30:47+00:00" + }, + { + "name": "jacklul/monolog-telegram", + "version": "3.2.0", + "source": { + "type": "git", + "url": "https://github.com/jacklul/monolog-telegram.git", + "reference": "1f2069f5556b1c8d6eb2d8b8ac29ff376675cf46" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/jacklul/monolog-telegram/zipball/1f2069f5556b1c8d6eb2d8b8ac29ff376675cf46", + "reference": "1f2069f5556b1c8d6eb2d8b8ac29ff376675cf46", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-mbstring": "*", + "monolog/monolog": "^3.0", + "php": "^8.1" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^9.0", + "squizlabs/php_codesniffer": "^3.2", + "vlucas/phpdotenv": "^5.0" + }, + "suggest": { + "ext-curl": "cURL generally works better and is recommended" + }, + "type": "library", + "autoload": { + "psr-4": { + "jacklul\\MonologTelegramHandler\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jack'lul", + "email": "jacklulcat@gmail.com", + "homepage": "https://jacklul.github.io", + "role": "Developer" + } + ], + "description": "Monolog handler that sends logs through Telegram bot to any chat in HTML format", + "keywords": [ + "bot", + "log", + "logging", + "monolog", + "telegram" + ], + "support": { + "issues": "https://github.com/jacklul/monolog-telegram/issues", + "source": "https://github.com/jacklul/monolog-telegram" + }, + "time": "2025-01-24T18:07:58+00:00" + }, + { + "name": "josantonius/cookie", + "version": "v2.0.7", + "source": { + "type": "git", + "url": "https://github.com/josantonius/php-cookie.git", + "reference": "f6751dcfdd47a8ed54a77c77760eded24676b8cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/josantonius/php-cookie/zipball/f6751dcfdd47a8ed54a77c77760eded24676b8cf", + "reference": "f6751dcfdd47a8ed54a77c77760eded24676b8cf", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "guzzlehttp/guzzle": "^7.4", + "phpmd/phpmd": "^2.6", + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "^3.7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-4": { + "Josantonius\\Cookie\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josantonius", + "email": "hello@josantonius.dev", + "homepage": "https://josantonius.dev", + "role": "Developer" + } + ], + "description": "PHP library for handling cookies.", + "keywords": [ + "cookies", + "php" + ], + "support": { + "discussions": "https://github.com/josantonius/php-cookie/discussions", + "issues": "https://github.com/josantonius/php-cookie/issues", + "source": "https://github.com/josantonius/php-cookie" + }, + "funding": [ + { + "url": "https://github.com/Josantonius", + "type": "github" + } + ], + "time": "2024-09-11T14:15:04+00:00" + }, + { + "name": "league/color-extractor", + "version": "0.4.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/color-extractor.git", + "reference": "21fcac6249c5ef7d00eb83e128743ee6678fe505" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/color-extractor/zipball/21fcac6249c5ef7d00eb83e128743ee6678fe505", + "reference": "21fcac6249c5ef7d00eb83e128743ee6678fe505", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "php": "^7.3 || ^8.0" + }, + "replace": { + "matthecat/colorextractor": "*" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "~2", + "phpunit/phpunit": "^9.5" + }, + "suggest": { + "ext-curl": "To download images from remote URLs if allow_url_fopen is disabled for security reasons" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\ColorExtractor\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mathieu Lechat", + "email": "math.lechat@gmail.com", + "homepage": "http://matthecat.com", + "role": "Developer" + } + ], + "description": "Extract colors from an image as a human would do.", + "homepage": "https://github.com/thephpleague/color-extractor", + "keywords": [ + "color", + "extract", + "human", + "image", + "palette" + ], + "support": { + "issues": "https://github.com/thephpleague/color-extractor/issues", + "source": "https://github.com/thephpleague/color-extractor/tree/0.4.0" + }, + "time": "2022-09-24T15:57:16+00:00" + }, + { + "name": "league/container", + "version": "4.2.5", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/container.git", + "reference": "d3cebb0ff4685ff61c749e54b27db49319e2ec00" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/container/zipball/d3cebb0ff4685ff61c749e54b27db49319e2ec00", + "reference": "d3cebb0ff4685ff61c749e54b27db49319e2ec00", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0", + "psr/container": "^1.1 || ^2.0" + }, + "provide": { + "psr/container-implementation": "^1.0" + }, + "replace": { + "orno/di": "~2.0" + }, + "require-dev": { + "nette/php-generator": "^3.4", + "nikic/php-parser": "^4.10", + "phpstan/phpstan": "^0.12.47", + "phpunit/phpunit": "^8.5.17", + "roave/security-advisories": "dev-latest", + "scrutinizer/ocular": "^1.8", + "squizlabs/php_codesniffer": "^3.6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-1.x": "1.x-dev", + "dev-2.x": "2.x-dev", + "dev-3.x": "3.x-dev", + "dev-4.x": "4.x-dev", + "dev-master": "4.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\Container\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Phil Bennett", + "email": "mail@philbennett.co.uk", + "role": "Developer" + } + ], + "description": "A fast and intuitive dependency injection container.", + "homepage": "https://github.com/thephpleague/container", + "keywords": [ + "container", + "dependency", + "di", + "injection", + "league", + "provider", + "service" + ], + "support": { + "issues": "https://github.com/thephpleague/container/issues", + "source": "https://github.com/thephpleague/container/tree/4.2.5" + }, + "funding": [ + { + "url": "https://github.com/philipobenito", + "type": "github" + } + ], + "time": "2025-05-20T12:55:37+00:00" + }, + { + "name": "league/flysystem", + "version": "3.29.1", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/flysystem.git", + "reference": "edc1bb7c86fab0776c3287dbd19b5fa278347319" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/edc1bb7c86fab0776c3287dbd19b5fa278347319", + "reference": "edc1bb7c86fab0776c3287dbd19b5fa278347319", + "shasum": "" + }, + "require": { + "league/flysystem-local": "^3.0.0", + "league/mime-type-detection": "^1.0.0", + "php": "^8.0.2" + }, + "conflict": { + "async-aws/core": "<1.19.0", + "async-aws/s3": "<1.14.0", + "aws/aws-sdk-php": "3.209.31 || 3.210.0", + "guzzlehttp/guzzle": "<7.0", + "guzzlehttp/ringphp": "<1.1.1", + "phpseclib/phpseclib": "3.0.15", + "symfony/http-client": "<5.2" + }, + "require-dev": { + "async-aws/s3": "^1.5 || ^2.0", + "async-aws/simple-s3": "^1.1 || ^2.0", + "aws/aws-sdk-php": "^3.295.10", + "composer/semver": "^3.0", + "ext-fileinfo": "*", + "ext-ftp": "*", + "ext-mongodb": "^1.3", + "ext-zip": "*", + "friendsofphp/php-cs-fixer": "^3.5", + "google/cloud-storage": "^1.23", + "guzzlehttp/psr7": "^2.6", + "microsoft/azure-storage-blob": "^1.1", + "mongodb/mongodb": "^1.2", + "phpseclib/phpseclib": "^3.0.36", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^9.5.11|^10.0", + "sabre/dav": "^4.6.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\Flysystem\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "File storage abstraction for PHP", + "keywords": [ + "WebDAV", + "aws", + "cloud", + "file", + "files", + "filesystem", + "filesystems", + "ftp", + "s3", + "sftp", + "storage" + ], + "support": { + "issues": "https://github.com/thephpleague/flysystem/issues", + "source": "https://github.com/thephpleague/flysystem/tree/3.29.1" + }, + "time": "2024-10-08T08:58:34+00:00" + }, + { + "name": "league/flysystem-local", + "version": "3.29.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/flysystem-local.git", + "reference": "e0e8d52ce4b2ed154148453d321e97c8e931bd27" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/flysystem-local/zipball/e0e8d52ce4b2ed154148453d321e97c8e931bd27", + "reference": "e0e8d52ce4b2ed154148453d321e97c8e931bd27", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "league/flysystem": "^3.0.0", + "league/mime-type-detection": "^1.0.0", + "php": "^8.0.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\Flysystem\\Local\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "Local filesystem adapter for Flysystem.", + "keywords": [ + "Flysystem", + "file", + "files", + "filesystem", + "local" + ], + "support": { + "source": "https://github.com/thephpleague/flysystem-local/tree/3.29.0" + }, + "time": "2024-08-09T21:24:39+00:00" + }, + { + "name": "league/mime-type-detection", + "version": "1.16.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/mime-type-detection.git", + "reference": "2d6702ff215bf922936ccc1ad31007edc76451b9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/mime-type-detection/zipball/2d6702ff215bf922936ccc1ad31007edc76451b9", + "reference": "2d6702ff215bf922936ccc1ad31007edc76451b9", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.2", + "phpstan/phpstan": "^0.12.68", + "phpunit/phpunit": "^8.5.8 || ^9.3 || ^10.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\MimeTypeDetection\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "Mime-type detection for Flysystem", + "support": { + "issues": "https://github.com/thephpleague/mime-type-detection/issues", + "source": "https://github.com/thephpleague/mime-type-detection/tree/1.16.0" + }, + "funding": [ + { + "url": "https://github.com/frankdejonge", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/flysystem", + "type": "tidelift" + } + ], + "time": "2024-09-21T08:32:55+00:00" + }, + { + "name": "longman/ip-tools", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/akalongman/php-ip-tools.git", + "reference": "6c050dfbf91811d14b9b3aa31fb7116eac0f0a18" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/akalongman/php-ip-tools/zipball/6c050dfbf91811d14b9b3aa31fb7116eac0f0a18", + "reference": "6c050dfbf91811d14b9b3aa31fb7116eac0f0a18", + "shasum": "" + }, + "require": { + "ext-bcmath": "*", + "php": ">=5.5" + }, + "require-dev": { + "phpspec/phpspec": "~2.1", + "phpunit/phpunit": "~4.1", + "squizlabs/php_codesniffer": "~2.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Longman\\IPTools\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Avtandil Kikabidze aka LONGMAN", + "email": "akalongman@gmail.com", + "homepage": "https://longman.me", + "role": "Developer" + } + ], + "description": "PHP IP Tools for manipulation with IPv4 and IPv6", + "homepage": "https://github.com/akalongman/php-ip-tools", + "keywords": [ + "IP", + "Match", + "compare", + "ipv4", + "ipv6", + "mask", + "subnet", + "tools", + "utilities" + ], + "support": { + "issues": "https://github.com/akalongman/php-ip-tools/issues", + "source": "https://github.com/akalongman/php-ip-tools" + }, + "time": "2016-10-23T20:08:46+00:00" + }, + { + "name": "monolog/monolog", + "version": "3.9.0", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "10d85740180ecba7896c87e06a166e0c95a0e3b6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/10d85740180ecba7896c87e06a166e0c95a0e3b6", + "reference": "10d85740180ecba7896c87e06a166e0c95a0e3b6", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" + }, + "provide": { + "psr/log-implementation": "3.0.0" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.0", + "doctrine/couchdb": "~1.0@dev", + "elasticsearch/elasticsearch": "^7 || ^8", + "ext-json": "*", + "graylog2/gelf-php": "^1.4.2 || ^2.0", + "guzzlehttp/guzzle": "^7.4.5", + "guzzlehttp/psr7": "^2.2", + "mongodb/mongodb": "^1.8", + "php-amqplib/php-amqplib": "~2.4 || ^3", + "php-console/php-console": "^3.1.8", + "phpstan/phpstan": "^2", + "phpstan/phpstan-deprecation-rules": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpunit/phpunit": "^10.5.17 || ^11.0.7", + "predis/predis": "^1.1 || ^2", + "rollbar/rollbar": "^4.0", + "ruflin/elastica": "^7 || ^8", + "symfony/mailer": "^5.4 || ^6", + "symfony/mime": "^5.4 || ^6" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler", + "ext-mbstring": "Allow to work properly with unicode symbols", + "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)", + "ext-openssl": "Required to send log messages using SSL", + "ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "https://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "support": { + "issues": "https://github.com/Seldaek/monolog/issues", + "source": "https://github.com/Seldaek/monolog/tree/3.9.0" + }, + "funding": [ + { + "url": "https://github.com/Seldaek", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/monolog/monolog", + "type": "tidelift" + } + ], + "time": "2025-03-24T10:02:05+00:00" + }, + { + "name": "nette/caching", + "version": "v3.3.1", + "source": { + "type": "git", + "url": "https://github.com/nette/caching.git", + "reference": "b37d2c9647b41a9d04f099f10300dc5496c4eb77" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/caching/zipball/b37d2c9647b41a9d04f099f10300dc5496c4eb77", + "reference": "b37d2c9647b41a9d04f099f10300dc5496c4eb77", + "shasum": "" + }, + "require": { + "nette/utils": "^4.0", + "php": "8.0 - 8.4" + }, + "conflict": { + "latte/latte": ">=3.0.0 <3.0.12" + }, + "require-dev": { + "latte/latte": "^2.11 || ^3.0.12", + "nette/di": "^3.1 || ^4.0", + "nette/tester": "^2.4", + "phpstan/phpstan": "^1.0", + "psr/simple-cache": "^2.0 || ^3.0", + "tracy/tracy": "^2.9" + }, + "suggest": { + "ext-pdo_sqlite": "to use SQLiteStorage or SQLiteJournal" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "⏱ Nette Caching: library with easy-to-use API and many cache backends.", + "homepage": "https://nette.org", + "keywords": [ + "cache", + "journal", + "memcached", + "nette", + "sqlite" + ], + "support": { + "issues": "https://github.com/nette/caching/issues", + "source": "https://github.com/nette/caching/tree/v3.3.1" + }, + "time": "2024-08-07T00:01:58+00:00" + }, + { + "name": "nette/database", + "version": "v3.2.7", + "source": { + "type": "git", + "url": "https://github.com/nette/database.git", + "reference": "10a7c76e314a06bb5f92d447d82170b5dde7392f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/database/zipball/10a7c76e314a06bb5f92d447d82170b5dde7392f", + "reference": "10a7c76e314a06bb5f92d447d82170b5dde7392f", + "shasum": "" + }, + "require": { + "ext-pdo": "*", + "nette/caching": "^3.2", + "nette/utils": "^4.0", + "php": "8.1 - 8.4" + }, + "require-dev": { + "jetbrains/phpstorm-attributes": "^1.0", + "mockery/mockery": "^1.6", + "nette/di": "^3.1", + "nette/tester": "^2.5", + "phpstan/phpstan-nette": "^1.0", + "tracy/tracy": "^2.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "💾 Nette Database: layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.", + "homepage": "https://nette.org", + "keywords": [ + "database", + "mssql", + "mysql", + "nette", + "notorm", + "oracle", + "pdo", + "postgresql", + "queries", + "sqlite" + ], + "support": { + "issues": "https://github.com/nette/database/issues", + "source": "https://github.com/nette/database/tree/v3.2.7" + }, + "time": "2025-06-03T05:00:20+00:00" + }, + { + "name": "nette/utils", + "version": "v4.0.7", + "source": { + "type": "git", + "url": "https://github.com/nette/utils.git", + "reference": "e67c4061eb40b9c113b218214e42cb5a0dda28f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/utils/zipball/e67c4061eb40b9c113b218214e42cb5a0dda28f2", + "reference": "e67c4061eb40b9c113b218214e42cb5a0dda28f2", + "shasum": "" + }, + "require": { + "php": "8.0 - 8.4" + }, + "conflict": { + "nette/finder": "<3", + "nette/schema": "<1.2.2" + }, + "require-dev": { + "jetbrains/phpstorm-attributes": "dev-master", + "nette/tester": "^2.5", + "phpstan/phpstan": "^1.0", + "tracy/tracy": "^2.9" + }, + "suggest": { + "ext-gd": "to use Image", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "homepage": "https://nette.org", + "keywords": [ + "array", + "core", + "datetime", + "images", + "json", + "nette", + "paginator", + "password", + "slugify", + "string", + "unicode", + "utf-8", + "utility", + "validation" + ], + "support": { + "issues": "https://github.com/nette/utils/issues", + "source": "https://github.com/nette/utils/tree/v4.0.7" + }, + "time": "2025-06-03T04:55:08+00:00" + }, + { + "name": "nikic/iter", + "version": "v2.4.1", + "source": { + "type": "git", + "url": "https://github.com/nikic/iter.git", + "reference": "3f031ae08d82c4394410e76b88b441331a6fa15f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/iter/zipball/3f031ae08d82c4394410e76b88b441331a6fa15f", + "reference": "3f031ae08d82c4394410e76b88b441331a6fa15f", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "require-dev": { + "phpstan/phpstan": "^1.4", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", + "vimeo/psalm": "^4.18 || ^5.13" + }, + "type": "library", + "autoload": { + "files": [ + "src/iter.func.php", + "src/iter.php", + "src/iter.rewindable.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Iteration primitives using generators", + "keywords": [ + "functional", + "generator", + "iterator" + ], + "support": { + "issues": "https://github.com/nikic/iter/issues", + "source": "https://github.com/nikic/iter/tree/v2.4.1" + }, + "time": "2024-03-19T20:45:05+00:00" + }, + { + "name": "php-curl-class/php-curl-class", + "version": "12.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-curl-class/php-curl-class.git", + "reference": "7a8f05efb18bb865dbce864b8fd34d4f5d920c74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-curl-class/php-curl-class/zipball/7a8f05efb18bb865dbce864b8fd34d4f5d920c74", + "reference": "7a8f05efb18bb865dbce864b8fd34d4f5d920c74", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "php": ">=8.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "*", + "ext-gd": "*", + "friendsofphp/php-cs-fixer": "*", + "phpcompatibility/php-compatibility": "dev-develop", + "phpcsstandards/phpcsutils": "@alpha", + "phpstan/phpstan": "*", + "phpunit/phpunit": "*", + "squizlabs/php_codesniffer": "*" + }, + "suggest": { + "ext-mbstring": "*" + }, + "type": "library", + "autoload": { + "psr-4": { + "Curl\\": "src/Curl/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Unlicense" + ], + "authors": [ + { + "name": "Zach Borboa" + }, + { + "name": "Contributors", + "homepage": "https://github.com/php-curl-class/php-curl-class/graphs/contributors" + } + ], + "description": "PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs.", + "homepage": "https://github.com/php-curl-class/php-curl-class", + "keywords": [ + "API-Client", + "api", + "class", + "client", + "curl", + "framework", + "http", + "http-client", + "http-proxy", + "json", + "php", + "php-curl", + "php-curl-library", + "proxy", + "requests", + "restful", + "web-scraper", + "web-scraping ", + "web-service", + "xml" + ], + "support": { + "issues": "https://github.com/php-curl-class/php-curl-class/issues", + "source": "https://github.com/php-curl-class/php-curl-class/tree/12.0.0" + }, + "time": "2025-03-25T18:04:16+00:00" + }, + { + "name": "phpoption/phpoption", + "version": "1.9.3", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "e3fac8b24f56113f7cb96af14958c0dd16330f54" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/e3fac8b24f56113f7cb96af14958c0dd16330f54", + "reference": "e3fac8b24f56113f7cb96af14958c0dd16330f54", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.39 || ^9.6.20 || ^10.5.28" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + }, + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "support": { + "issues": "https://github.com/schmittjoh/php-option/issues", + "source": "https://github.com/schmittjoh/php-option/tree/1.9.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", + "type": "tidelift" + } + ], + "time": "2024-07-20T21:41:07+00:00" + }, + { + "name": "psr/clock", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/clock.git", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/clock/zipball/e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for reading the clock.", + "homepage": "https://github.com/php-fig/clock", + "keywords": [ + "clock", + "now", + "psr", + "psr-20", + "time" + ], + "support": { + "issues": "https://github.com/php-fig/clock/issues", + "source": "https://github.com/php-fig/clock/tree/1.0.0" + }, + "time": "2022-11-25T14:36:26+00:00" + }, + { + "name": "psr/container", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "time": "2021-11-05T16:47:00+00:00" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "time": "2019-01-08T18:20:26+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "psr/simple-cache", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/simple-cache.git", + "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/764e0b3939f5ca87cb904f570ef9be2d78a07865", + "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\SimpleCache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interfaces for simple caching", + "keywords": [ + "cache", + "caching", + "psr", + "psr-16", + "simple-cache" + ], + "support": { + "source": "https://github.com/php-fig/simple-cache/tree/3.0.0" + }, + "time": "2021-10-29T13:26:27+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "robmorgan/phinx", + "version": "0.16.9", + "source": { + "type": "git", + "url": "https://github.com/cakephp/phinx.git", + "reference": "524ebdeb0e1838a845d752a3418726b38cd1e654" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cakephp/phinx/zipball/524ebdeb0e1838a845d752a3418726b38cd1e654", + "reference": "524ebdeb0e1838a845d752a3418726b38cd1e654", + "shasum": "" + }, + "require": { + "cakephp/database": "^5.0.2", + "composer-runtime-api": "^2.0", + "php-64bit": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/config": "^4.0|^5.0|^6.0|^7.0", + "symfony/console": "^6.0|^7.0" + }, + "require-dev": { + "cakephp/cakephp-codesniffer": "^5.0", + "cakephp/i18n": "^5.0", + "ext-json": "*", + "ext-pdo": "*", + "phpunit/phpunit": "^9.5.19", + "symfony/yaml": "^4.0|^5.0|^6.0|^7.0" + }, + "suggest": { + "ext-json": "Install if using JSON configuration format", + "ext-pdo": "PDO extension is needed", + "symfony/yaml": "Install if using YAML configuration format" + }, + "bin": [ + "bin/phinx" + ], + "type": "library", + "autoload": { + "psr-4": { + "Phinx\\": "src/Phinx/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Rob Morgan", + "email": "robbym@gmail.com", + "homepage": "https://robmorgan.id.au", + "role": "Lead Developer" + }, + { + "name": "Woody Gilk", + "email": "woody.gilk@gmail.com", + "homepage": "https://shadowhand.me", + "role": "Developer" + }, + { + "name": "Richard Quadling", + "email": "rquadling@gmail.com", + "role": "Developer" + }, + { + "name": "CakePHP Community", + "homepage": "https://github.com/cakephp/phinx/graphs/contributors", + "role": "Developer" + } + ], + "description": "Phinx makes it ridiculously easy to manage the database migrations for your PHP app.", + "homepage": "https://phinx.org", + "keywords": [ + "database", + "database migrations", + "db", + "migrations", + "phinx" + ], + "support": { + "issues": "https://github.com/cakephp/phinx/issues", + "source": "https://github.com/cakephp/phinx/tree/0.16.9" + }, + "time": "2025-05-25T16:07:44+00:00" + }, + { + "name": "samdark/sitemap", + "version": "2.4.1", + "source": { + "type": "git", + "url": "https://github.com/samdark/sitemap.git", + "reference": "cf514750781275ad90fc9a828b4330c9c5ccba98" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/samdark/sitemap/zipball/cf514750781275ad90fc9a828b4330c9c5ccba98", + "reference": "cf514750781275ad90fc9a828b4330c9c5ccba98", + "shasum": "" + }, + "require": { + "ext-xmlwriter": "*", + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "samdark\\sitemap\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Alexander Makarov", + "email": "sam@rmcreative.ru", + "homepage": "http://rmcreative.ru/" + } + ], + "description": "Sitemap and sitemap index builder", + "homepage": "https://github.com/samdark/sitemap", + "keywords": [ + "Sitemap" + ], + "support": { + "issues": "https://github.com/samdark/sitemap/issues", + "source": "https://github.com/samdark/sitemap" + }, + "funding": [ + { + "url": "https://github.com/samdark", + "type": "github" + }, + { + "url": "https://www.patreon.com/samdark", + "type": "patreon" + } + ], + "time": "2023-11-01T08:41:34+00:00" + }, + { + "name": "symfony/config", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/config.git", + "reference": "ba62ae565f1327c2f6366726312ed828c85853bc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/config/zipball/ba62ae565f1327c2f6366726312ed828c85853bc", + "reference": "ba62ae565f1327c2f6366726312ed828c85853bc", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/filesystem": "^7.1", + "symfony/polyfill-ctype": "~1.8" + }, + "conflict": { + "symfony/finder": "<6.4", + "symfony/service-contracts": "<2.5" + }, + "require-dev": { + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/finder": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Config\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Helps you find, load, combine, autofill and validate configuration values of any kind", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/config/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-05-15T09:04:05+00:00" + }, + { + "name": "symfony/console", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "66c1440edf6f339fd82ed6c7caa76cb006211b44" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/66c1440edf6f339fd82ed6c7caa76cb006211b44", + "reference": "66c1440edf6f339fd82ed6c7caa76cb006211b44", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^7.2" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/dotenv": "<6.4", + "symfony/event-dispatcher": "<6.4", + "symfony/lock": "<6.4", + "symfony/process": "<6.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/lock": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/stopwatch": "^6.4|^7.0", + "symfony/var-dumper": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-05-24T10:34:04+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.6.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/63afe740e99a13ba87ec199bb07bbdee937a5b62", + "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.6-dev" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.6.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:21:43+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "497f73ac996a598c92409b44ac43b6690c4f666d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/497f73ac996a598c92409b44ac43b6690c4f666d", + "reference": "497f73ac996a598c92409b44ac43b6690c4f666d", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/error-handler": "^6.4|^7.0", + "symfony/expression-language": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-04-22T09:11:45+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.6.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "59eb412e93815df44f05f342958efa9f46b1e586" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/59eb412e93815df44f05f342958efa9f46b1e586", + "reference": "59eb412e93815df44f05f342958efa9f46b1e586", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.6-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.6.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:21:43+00:00" + }, + { + "name": "symfony/filesystem", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "b8dce482de9d7c9fe2891155035a7248ab5c7fdb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/b8dce482de9d7c9fe2891155035a7248ab5c7fdb", + "reference": "b8dce482de9d7c9fe2891155035a7248ab5c7fdb", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "require-dev": { + "symfony/process": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-10-25T15:15:23+00:00" + }, + { + "name": "symfony/finder", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "ec2344cf77a48253bbca6939aa3d2477773ea63d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/ec2344cf77a48253bbca6939aa3d2477773ea63d", + "reference": "ec2344cf77a48253bbca6939aa3d2477773ea63d", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "symfony/filesystem": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-12-30T19:00:26+00:00" + }, + { + "name": "symfony/mailer", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/mailer.git", + "reference": "0f375bbbde96ae8c78e4aa3e63aabd486e33364c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mailer/zipball/0f375bbbde96ae8c78e4aa3e63aabd486e33364c", + "reference": "0f375bbbde96ae8c78e4aa3e63aabd486e33364c", + "shasum": "" + }, + "require": { + "egulias/email-validator": "^2.1.10|^3|^4", + "php": ">=8.2", + "psr/event-dispatcher": "^1", + "psr/log": "^1|^2|^3", + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/mime": "^7.2", + "symfony/service-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/http-client-contracts": "<2.5", + "symfony/http-kernel": "<6.4", + "symfony/messenger": "<6.4", + "symfony/mime": "<6.4", + "symfony/twig-bridge": "<6.4" + }, + "require-dev": { + "symfony/console": "^6.4|^7.0", + "symfony/http-client": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/twig-bridge": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mailer\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Helps sending emails", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/mailer/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-04-04T09:51:09+00:00" + }, + { + "name": "symfony/mime", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/mime.git", + "reference": "0e7b19b2f399c31df0cdbe5d8cbf53f02f6cfcd9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mime/zipball/0e7b19b2f399c31df0cdbe5d8cbf53f02f6cfcd9", + "reference": "0e7b19b2f399c31df0cdbe5d8cbf53f02f6cfcd9", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0" + }, + "conflict": { + "egulias/email-validator": "~3.0.0", + "phpdocumentor/reflection-docblock": "<3.2.2", + "phpdocumentor/type-resolver": "<1.4.0", + "symfony/mailer": "<6.4", + "symfony/serializer": "<6.4.3|>7.0,<7.0.3" + }, + "require-dev": { + "egulias/email-validator": "^2.1.10|^3.1|^4", + "league/html-to-markdown": "^5.0", + "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/property-access": "^6.4|^7.0", + "symfony/property-info": "^6.4|^7.0", + "symfony/serializer": "^6.4.3|^7.0.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mime\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Allows manipulating MIME messages", + "homepage": "https://symfony.com", + "keywords": [ + "mime", + "mime-type" + ], + "support": { + "source": "https://github.com/symfony/mime/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-02-19T08:51:26+00:00" + }, + { + "name": "symfony/polyfill", + "version": "v1.32.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill.git", + "reference": "c4ee386e95ccdbea59cea802ea776d806319d506" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill/zipball/c4ee386e95ccdbea59cea802ea776d806319d506", + "reference": "c4ee386e95ccdbea59cea802ea776d806319d506", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "replace": { + "symfony/polyfill-apcu": "self.version", + "symfony/polyfill-ctype": "self.version", + "symfony/polyfill-iconv": "self.version", + "symfony/polyfill-intl-grapheme": "self.version", + "symfony/polyfill-intl-icu": "self.version", + "symfony/polyfill-intl-idn": "self.version", + "symfony/polyfill-intl-messageformatter": "self.version", + "symfony/polyfill-intl-normalizer": "self.version", + "symfony/polyfill-mbstring": "self.version", + "symfony/polyfill-php73": "self.version", + "symfony/polyfill-php74": "self.version", + "symfony/polyfill-php80": "self.version", + "symfony/polyfill-php81": "self.version", + "symfony/polyfill-php82": "self.version", + "symfony/polyfill-php83": "self.version", + "symfony/polyfill-php84": "self.version", + "symfony/polyfill-php85": "self.version", + "symfony/polyfill-util": "self.version", + "symfony/polyfill-uuid": "self.version" + }, + "require-dev": { + "symfony/intl": "^5.4|^6.4", + "symfony/phpunit-bridge": "^6.4", + "symfony/var-dumper": "^5.4|^6.4" + }, + "type": "library", + "autoload": { + "files": [ + "src/bootstrap.php", + "src/Apcu/bootstrap.php", + "src/Ctype/bootstrap.php", + "src/Uuid/bootstrap.php", + "src/Iconv/bootstrap.php", + "src/Intl/Grapheme/bootstrap.php", + "src/Intl/Idn/bootstrap.php", + "src/Intl/Icu/bootstrap.php", + "src/Intl/MessageFormatter/bootstrap.php", + "src/Intl/Normalizer/bootstrap.php", + "src/Mbstring/bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\": "src/" + }, + "classmap": [ + "src/Intl/Icu/Resources/stubs", + "src/Intl/MessageFormatter/Resources/stubs", + "src/Intl/Normalizer/Resources/stubs", + "src/Php85/Resources/stubs", + "src/Php84/Resources/stubs", + "src/Php83/Resources/stubs", + "src/Php82/Resources/stubs", + "src/Php81/Resources/stubs", + "src/Php80/Resources/stubs", + "src/Php73/Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfills backporting features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compat", + "compatibility", + "dev", + "polyfill", + "shim" + ], + "support": { + "issues": "https://github.com/symfony/polyfill/issues", + "source": "https://github.com/symfony/polyfill/tree/v1.32.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-05-02T09:40:28+00:00" + }, + { + "name": "symfony/service-contracts", + "version": "v3.6.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "f021b05a130d35510bd6b25fe9053c2a8a15d5d4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/f021b05a130d35510bd6b25fe9053c2a8a15d5d4", + "reference": "f021b05a130d35510bd6b25fe9053c2a8a15d5d4", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.6-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.6.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-04-25T09:37:31+00:00" + }, + { + "name": "symfony/string", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "f3570b8c61ca887a9e2938e85cb6458515d2b125" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/f3570b8c61ca887a9e2938e85cb6458515d2b125", + "reference": "f3570b8c61ca887a9e2938e85cb6458515d2b125", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/emoji": "^7.1", + "symfony/error-handler": "^6.4|^7.0", + "symfony/http-client": "^6.4|^7.0", + "symfony/intl": "^6.4|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-04-20T20:19:01+00:00" + }, + { + "name": "vlucas/phpdotenv", + "version": "v5.6.2", + "source": { + "type": "git", + "url": "https://github.com/vlucas/phpdotenv.git", + "reference": "24ac4c74f91ee2c193fa1aaa5c249cb0822809af" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/24ac4c74f91ee2c193fa1aaa5c249cb0822809af", + "reference": "24ac4c74f91ee2c193fa1aaa5c249cb0822809af", + "shasum": "" + }, + "require": { + "ext-pcre": "*", + "graham-campbell/result-type": "^1.1.3", + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.3", + "symfony/polyfill-ctype": "^1.24", + "symfony/polyfill-mbstring": "^1.24", + "symfony/polyfill-php80": "^1.24" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-filter": "*", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "suggest": { + "ext-filter": "Required to use the boolean validator." + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "5.6-dev" + } + }, + "autoload": { + "psr-4": { + "Dotenv\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Vance Lucas", + "email": "vance@vancelucas.com", + "homepage": "https://github.com/vlucas" + } + ], + "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", + "keywords": [ + "dotenv", + "env", + "environment" + ], + "support": { + "issues": "https://github.com/vlucas/phpdotenv/issues", + "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv", + "type": "tidelift" + } + ], + "time": "2025-04-30T23:37:27+00:00" + }, + { + "name": "z4kn4fein/php-semver", + "version": "v3.0.0", + "source": { + "type": "git", + "url": "https://github.com/z4kn4fein/php-semver.git", + "reference": "049a1d81e92235c8b3c9ab30a96fcbaa929a266d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/z4kn4fein/php-semver/zipball/049a1d81e92235c8b3c9ab30a96fcbaa929a266d", + "reference": "049a1d81e92235c8b3c9ab30a96fcbaa929a266d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0", + "phpstan/phpstan": "^1.0", + "phpunit/phpunit": "^10" + }, + "type": "library", + "autoload": { + "psr-4": { + "z4kn4fein\\SemVer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Peter Csajtai", + "email": "peter.csajtai@outlook.com" + } + ], + "description": "Semantic Versioning library for PHP. It implements the full semantic version 2.0.0 specification and provides ability to parse, compare, and increment semantic versions along with validation against constraints.", + "homepage": "https://github.com/z4kn4fein/php-semver", + "keywords": [ + "comparison", + "semantic", + "semver", + "validation", + "version", + "versioning" + ], + "support": { + "issues": "https://github.com/z4kn4fein/php-semver/issues", + "source": "https://github.com/z4kn4fein/php-semver/tree/v3.0.0" + }, + "time": "2024-04-01T16:17:27+00:00" + } + ], + "packages-dev": [ + { + "name": "brianium/paratest", + "version": "v7.8.3", + "source": { + "type": "git", + "url": "https://github.com/paratestphp/paratest.git", + "reference": "a585c346ddf1bec22e51e20b5387607905604a71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paratestphp/paratest/zipball/a585c346ddf1bec22e51e20b5387607905604a71", + "reference": "a585c346ddf1bec22e51e20b5387607905604a71", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-pcre": "*", + "ext-reflection": "*", + "ext-simplexml": "*", + "fidry/cpu-core-counter": "^1.2.0", + "jean85/pretty-package-versions": "^2.1.0", + "php": "~8.2.0 || ~8.3.0 || ~8.4.0", + "phpunit/php-code-coverage": "^11.0.9 || ^12.0.4", + "phpunit/php-file-iterator": "^5.1.0 || ^6", + "phpunit/php-timer": "^7.0.1 || ^8", + "phpunit/phpunit": "^11.5.11 || ^12.0.6", + "sebastian/environment": "^7.2.0 || ^8", + "symfony/console": "^6.4.17 || ^7.2.1", + "symfony/process": "^6.4.19 || ^7.2.4" + }, + "require-dev": { + "doctrine/coding-standard": "^12.0.0", + "ext-pcov": "*", + "ext-posix": "*", + "phpstan/phpstan": "^2.1.6", + "phpstan/phpstan-deprecation-rules": "^2.0.1", + "phpstan/phpstan-phpunit": "^2.0.4", + "phpstan/phpstan-strict-rules": "^2.0.3", + "squizlabs/php_codesniffer": "^3.11.3", + "symfony/filesystem": "^6.4.13 || ^7.2.0" + }, + "bin": [ + "bin/paratest", + "bin/paratest_for_phpstorm" + ], + "type": "library", + "autoload": { + "psr-4": { + "ParaTest\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brian Scaturro", + "email": "scaturrob@gmail.com", + "role": "Developer" + }, + { + "name": "Filippo Tessarotto", + "email": "zoeslam@gmail.com", + "role": "Developer" + } + ], + "description": "Parallel testing for PHP", + "homepage": "https://github.com/paratestphp/paratest", + "keywords": [ + "concurrent", + "parallel", + "phpunit", + "testing" + ], + "support": { + "issues": "https://github.com/paratestphp/paratest/issues", + "source": "https://github.com/paratestphp/paratest/tree/v7.8.3" + }, + "funding": [ + { + "url": "https://github.com/sponsors/Slamdunk", + "type": "github" + }, + { + "url": "https://paypal.me/filippotessarotto", + "type": "paypal" + } + ], + "time": "2025-03-05T08:29:11+00:00" + }, + { + "name": "doctrine/deprecations", + "version": "1.1.5", + "source": { + "type": "git", + "url": "https://github.com/doctrine/deprecations.git", + "reference": "459c2f5dd3d6a4633d3b5f46ee2b1c40f57d3f38" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/deprecations/zipball/459c2f5dd3d6a4633d3b5f46ee2b1c40f57d3f38", + "reference": "459c2f5dd3d6a4633d3b5f46ee2b1c40f57d3f38", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "conflict": { + "phpunit/phpunit": "<=7.5 || >=13" + }, + "require-dev": { + "doctrine/coding-standard": "^9 || ^12 || ^13", + "phpstan/phpstan": "1.4.10 || 2.1.11", + "phpstan/phpstan-phpunit": "^1.0 || ^2", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.6 || ^10.5 || ^11.5 || ^12", + "psr/log": "^1 || ^2 || ^3" + }, + "suggest": { + "psr/log": "Allows logging deprecations via PSR-3 logger implementation" + }, + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\Deprecations\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.", + "homepage": "https://www.doctrine-project.org/", + "support": { + "issues": "https://github.com/doctrine/deprecations/issues", + "source": "https://github.com/doctrine/deprecations/tree/1.1.5" + }, + "time": "2025-04-07T20:06:18+00:00" + }, + { + "name": "fidry/cpu-core-counter", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/theofidry/cpu-core-counter.git", + "reference": "8520451a140d3f46ac33042715115e290cf5785f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/8520451a140d3f46ac33042715115e290cf5785f", + "reference": "8520451a140d3f46ac33042715115e290cf5785f", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry/makefile": "^0.2.0", + "fidry/php-cs-fixer-config": "^1.1.2", + "phpstan/extension-installer": "^1.2.0", + "phpstan/phpstan": "^1.9.2", + "phpstan/phpstan-deprecation-rules": "^1.0.0", + "phpstan/phpstan-phpunit": "^1.2.2", + "phpstan/phpstan-strict-rules": "^1.4.4", + "phpunit/phpunit": "^8.5.31 || ^9.5.26", + "webmozarts/strict-phpunit": "^7.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Fidry\\CpuCoreCounter\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "description": "Tiny utility to get the number of CPU cores.", + "keywords": [ + "CPU", + "core" + ], + "support": { + "issues": "https://github.com/theofidry/cpu-core-counter/issues", + "source": "https://github.com/theofidry/cpu-core-counter/tree/1.2.0" + }, + "funding": [ + { + "url": "https://github.com/theofidry", + "type": "github" + } + ], + "time": "2024-08-06T10:04:20+00:00" + }, + { + "name": "hamcrest/hamcrest-php", + "version": "v2.1.1", + "source": { + "type": "git", + "url": "https://github.com/hamcrest/hamcrest-php.git", + "reference": "f8b1c0173b22fa6ec77a81fe63e5b01eba7e6487" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/hamcrest/hamcrest-php/zipball/f8b1c0173b22fa6ec77a81fe63e5b01eba7e6487", + "reference": "f8b1c0173b22fa6ec77a81fe63e5b01eba7e6487", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0" + }, + "replace": { + "cordoval/hamcrest-php": "*", + "davedevelopment/hamcrest-php": "*", + "kodova/hamcrest-php": "*" + }, + "require-dev": { + "phpunit/php-file-iterator": "^1.4 || ^2.0 || ^3.0", + "phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0 || ^8.0 || ^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + } + }, + "autoload": { + "classmap": [ + "hamcrest" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "This is the PHP port of Hamcrest Matchers", + "keywords": [ + "test" + ], + "support": { + "issues": "https://github.com/hamcrest/hamcrest-php/issues", + "source": "https://github.com/hamcrest/hamcrest-php/tree/v2.1.1" + }, + "time": "2025-04-30T06:54:44+00:00" + }, + { + "name": "jean85/pretty-package-versions", + "version": "2.1.1", + "source": { + "type": "git", + "url": "https://github.com/Jean85/pretty-package-versions.git", + "reference": "4d7aa5dab42e2a76d99559706022885de0e18e1a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/4d7aa5dab42e2a76d99559706022885de0e18e1a", + "reference": "4d7aa5dab42e2a76d99559706022885de0e18e1a", + "shasum": "" + }, + "require": { + "composer-runtime-api": "^2.1.0", + "php": "^7.4|^8.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.2", + "jean85/composer-provided-replaced-stub-package": "^1.0", + "phpstan/phpstan": "^2.0", + "phpunit/phpunit": "^7.5|^8.5|^9.6", + "rector/rector": "^2.0", + "vimeo/psalm": "^4.3 || ^5.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Jean85\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alessandro Lai", + "email": "alessandro.lai85@gmail.com" + } + ], + "description": "A library to get pretty versions strings of installed dependencies", + "keywords": [ + "composer", + "package", + "release", + "versions" + ], + "support": { + "issues": "https://github.com/Jean85/pretty-package-versions/issues", + "source": "https://github.com/Jean85/pretty-package-versions/tree/2.1.1" + }, + "time": "2025-03-19T14:43:43+00:00" + }, + { + "name": "mockery/mockery", + "version": "1.6.12", + "source": { + "type": "git", + "url": "https://github.com/mockery/mockery.git", + "reference": "1f4efdd7d3beafe9807b08156dfcb176d18f1699" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mockery/mockery/zipball/1f4efdd7d3beafe9807b08156dfcb176d18f1699", + "reference": "1f4efdd7d3beafe9807b08156dfcb176d18f1699", + "shasum": "" + }, + "require": { + "hamcrest/hamcrest-php": "^2.0.1", + "lib-pcre": ">=7.0", + "php": ">=7.3" + }, + "conflict": { + "phpunit/phpunit": "<8.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.5 || ^9.6.17", + "symplify/easy-coding-standard": "^12.1.14" + }, + "type": "library", + "autoload": { + "files": [ + "library/helpers.php", + "library/Mockery.php" + ], + "psr-4": { + "Mockery\\": "library/Mockery" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Pádraic Brady", + "email": "padraic.brady@gmail.com", + "homepage": "https://github.com/padraic", + "role": "Author" + }, + { + "name": "Dave Marshall", + "email": "dave.marshall@atstsolutions.co.uk", + "homepage": "https://davedevelopment.co.uk", + "role": "Developer" + }, + { + "name": "Nathanael Esayeas", + "email": "nathanael.esayeas@protonmail.com", + "homepage": "https://github.com/ghostwriter", + "role": "Lead Developer" + } + ], + "description": "Mockery is a simple yet flexible PHP mock object framework", + "homepage": "https://github.com/mockery/mockery", + "keywords": [ + "BDD", + "TDD", + "library", + "mock", + "mock objects", + "mockery", + "stub", + "test", + "test double", + "testing" + ], + "support": { + "docs": "https://docs.mockery.io/", + "issues": "https://github.com/mockery/mockery/issues", + "rss": "https://github.com/mockery/mockery/releases.atom", + "security": "https://github.com/mockery/mockery/security/advisories", + "source": "https://github.com/mockery/mockery" + }, + "time": "2024-05-16T03:13:13+00:00" + }, + { + "name": "myclabs/deep-copy", + "version": "1.13.1", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "1720ddd719e16cf0db4eb1c6eca108031636d46c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/1720ddd719e16cf0db4eb1c6eca108031636d46c", + "reference": "1720ddd719e16cf0db4eb1c6eca108031636d46c", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "conflict": { + "doctrine/collections": "<1.6.8", + "doctrine/common": "<2.13.3 || >=3 <3.2.2" + }, + "require-dev": { + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpspec/prophecy": "^1.10", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" + }, + "type": "library", + "autoload": { + "files": [ + "src/DeepCopy/deep_copy.php" + ], + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.13.1" + }, + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", + "type": "tidelift" + } + ], + "time": "2025-04-29T12:36:36+00:00" + }, + { + "name": "nikic/php-parser", + "version": "v5.5.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "ae59794362fe85e051a58ad36b289443f57be7a9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/ae59794362fe85e051a58ad36b289443f57be7a9", + "reference": "ae59794362fe85e051a58ad36b289443f57be7a9", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^9.0" + }, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v5.5.0" + }, + "time": "2025-05-31T08:24:38+00:00" + }, + { + "name": "nunomaduro/collision", + "version": "v8.8.1", + "source": { + "type": "git", + "url": "https://github.com/nunomaduro/collision.git", + "reference": "44ccb82e3e21efb5446748d2a3c81a030ac22bd5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nunomaduro/collision/zipball/44ccb82e3e21efb5446748d2a3c81a030ac22bd5", + "reference": "44ccb82e3e21efb5446748d2a3c81a030ac22bd5", + "shasum": "" + }, + "require": { + "filp/whoops": "^2.18.1", + "nunomaduro/termwind": "^2.3.1", + "php": "^8.2.0", + "symfony/console": "^7.3.0" + }, + "conflict": { + "laravel/framework": "<11.44.2 || >=13.0.0", + "phpunit/phpunit": "<11.5.15 || >=13.0.0" + }, + "require-dev": { + "brianium/paratest": "^7.8.3", + "larastan/larastan": "^3.4.2", + "laravel/framework": "^11.44.2 || ^12.18", + "laravel/pint": "^1.22.1", + "laravel/sail": "^1.43.1", + "laravel/sanctum": "^4.1.1", + "laravel/tinker": "^2.10.1", + "orchestra/testbench-core": "^9.12.0 || ^10.4", + "pestphp/pest": "^3.8.2", + "sebastian/environment": "^7.2.1 || ^8.0" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider" + ] + }, + "branch-alias": { + "dev-8.x": "8.x-dev" + } + }, + "autoload": { + "files": [ + "./src/Adapters/Phpunit/Autoload.php" + ], + "psr-4": { + "NunoMaduro\\Collision\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "Cli error handling for console/command-line PHP applications.", + "keywords": [ + "artisan", + "cli", + "command-line", + "console", + "dev", + "error", + "handling", + "laravel", + "laravel-zero", + "php", + "symfony" + ], + "support": { + "issues": "https://github.com/nunomaduro/collision/issues", + "source": "https://github.com/nunomaduro/collision" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + }, + { + "url": "https://www.patreon.com/nunomaduro", + "type": "patreon" + } + ], + "time": "2025-06-11T01:04:21+00:00" + }, + { + "name": "nunomaduro/termwind", + "version": "v2.3.1", + "source": { + "type": "git", + "url": "https://github.com/nunomaduro/termwind.git", + "reference": "dfa08f390e509967a15c22493dc0bac5733d9123" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nunomaduro/termwind/zipball/dfa08f390e509967a15c22493dc0bac5733d9123", + "reference": "dfa08f390e509967a15c22493dc0bac5733d9123", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": "^8.2", + "symfony/console": "^7.2.6" + }, + "require-dev": { + "illuminate/console": "^11.44.7", + "laravel/pint": "^1.22.0", + "mockery/mockery": "^1.6.12", + "pestphp/pest": "^2.36.0 || ^3.8.2", + "phpstan/phpstan": "^1.12.25", + "phpstan/phpstan-strict-rules": "^1.6.2", + "symfony/var-dumper": "^7.2.6", + "thecodingmachine/phpstan-strict-rules": "^1.0.0" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Termwind\\Laravel\\TermwindServiceProvider" + ] + }, + "branch-alias": { + "dev-2.x": "2.x-dev" + } + }, + "autoload": { + "files": [ + "src/Functions.php" + ], + "psr-4": { + "Termwind\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "Its like Tailwind CSS, but for the console.", + "keywords": [ + "cli", + "console", + "css", + "package", + "php", + "style" + ], + "support": { + "issues": "https://github.com/nunomaduro/termwind/issues", + "source": "https://github.com/nunomaduro/termwind/tree/v2.3.1" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + }, + { + "url": "https://github.com/xiCO2k", + "type": "github" + } + ], + "time": "2025-05-08T08:14:37+00:00" + }, + { + "name": "pestphp/pest", + "version": "v3.8.2", + "source": { + "type": "git", + "url": "https://github.com/pestphp/pest.git", + "reference": "c6244a8712968dbac88eb998e7ff3b5caa556b0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pestphp/pest/zipball/c6244a8712968dbac88eb998e7ff3b5caa556b0d", + "reference": "c6244a8712968dbac88eb998e7ff3b5caa556b0d", + "shasum": "" + }, + "require": { + "brianium/paratest": "^7.8.3", + "nunomaduro/collision": "^8.8.0", + "nunomaduro/termwind": "^2.3.0", + "pestphp/pest-plugin": "^3.0.0", + "pestphp/pest-plugin-arch": "^3.1.0", + "pestphp/pest-plugin-mutate": "^3.0.5", + "php": "^8.2.0", + "phpunit/phpunit": "^11.5.15" + }, + "conflict": { + "filp/whoops": "<2.16.0", + "phpunit/phpunit": ">11.5.15", + "sebastian/exporter": "<6.0.0", + "webmozart/assert": "<1.11.0" + }, + "require-dev": { + "pestphp/pest-dev-tools": "^3.4.0", + "pestphp/pest-plugin-type-coverage": "^3.5.0", + "symfony/process": "^7.2.5" + }, + "bin": [ + "bin/pest" + ], + "type": "library", + "extra": { + "pest": { + "plugins": [ + "Pest\\Mutate\\Plugins\\Mutate", + "Pest\\Plugins\\Configuration", + "Pest\\Plugins\\Bail", + "Pest\\Plugins\\Cache", + "Pest\\Plugins\\Coverage", + "Pest\\Plugins\\Init", + "Pest\\Plugins\\Environment", + "Pest\\Plugins\\Help", + "Pest\\Plugins\\Memory", + "Pest\\Plugins\\Only", + "Pest\\Plugins\\Printer", + "Pest\\Plugins\\ProcessIsolation", + "Pest\\Plugins\\Profile", + "Pest\\Plugins\\Retry", + "Pest\\Plugins\\Snapshot", + "Pest\\Plugins\\Verbose", + "Pest\\Plugins\\Version", + "Pest\\Plugins\\Parallel" + ] + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "autoload": { + "files": [ + "src/Functions.php", + "src/Pest.php" + ], + "psr-4": { + "Pest\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "The elegant PHP Testing Framework.", + "keywords": [ + "framework", + "pest", + "php", + "test", + "testing", + "unit" + ], + "support": { + "issues": "https://github.com/pestphp/pest/issues", + "source": "https://github.com/pestphp/pest/tree/v3.8.2" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + } + ], + "time": "2025-04-17T10:53:02+00:00" + }, + { + "name": "pestphp/pest-plugin", + "version": "v3.0.0", + "source": { + "type": "git", + "url": "https://github.com/pestphp/pest-plugin.git", + "reference": "e79b26c65bc11c41093b10150c1341cc5cdbea83" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pestphp/pest-plugin/zipball/e79b26c65bc11c41093b10150c1341cc5cdbea83", + "reference": "e79b26c65bc11c41093b10150c1341cc5cdbea83", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.0.0", + "composer-runtime-api": "^2.2.2", + "php": "^8.2" + }, + "conflict": { + "pestphp/pest": "<3.0.0" + }, + "require-dev": { + "composer/composer": "^2.7.9", + "pestphp/pest": "^3.0.0", + "pestphp/pest-dev-tools": "^3.0.0" + }, + "type": "composer-plugin", + "extra": { + "class": "Pest\\Plugin\\Manager" + }, + "autoload": { + "psr-4": { + "Pest\\Plugin\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The Pest plugin manager", + "keywords": [ + "framework", + "manager", + "pest", + "php", + "plugin", + "test", + "testing", + "unit" + ], + "support": { + "source": "https://github.com/pestphp/pest-plugin/tree/v3.0.0" + }, + "funding": [ + { + "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=66BYDWAT92N6L", + "type": "custom" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + }, + { + "url": "https://www.patreon.com/nunomaduro", + "type": "patreon" + } + ], + "time": "2024-09-08T23:21:41+00:00" + }, + { + "name": "pestphp/pest-plugin-arch", + "version": "v3.1.1", + "source": { + "type": "git", + "url": "https://github.com/pestphp/pest-plugin-arch.git", + "reference": "db7bd9cb1612b223e16618d85475c6f63b9c8daa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pestphp/pest-plugin-arch/zipball/db7bd9cb1612b223e16618d85475c6f63b9c8daa", + "reference": "db7bd9cb1612b223e16618d85475c6f63b9c8daa", + "shasum": "" + }, + "require": { + "pestphp/pest-plugin": "^3.0.0", + "php": "^8.2", + "ta-tikoma/phpunit-architecture-test": "^0.8.4" + }, + "require-dev": { + "pestphp/pest": "^3.8.1", + "pestphp/pest-dev-tools": "^3.4.0" + }, + "type": "library", + "extra": { + "pest": { + "plugins": [ + "Pest\\Arch\\Plugin" + ] + } + }, + "autoload": { + "files": [ + "src/Autoload.php" + ], + "psr-4": { + "Pest\\Arch\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The Arch plugin for Pest PHP.", + "keywords": [ + "arch", + "architecture", + "framework", + "pest", + "php", + "plugin", + "test", + "testing", + "unit" + ], + "support": { + "source": "https://github.com/pestphp/pest-plugin-arch/tree/v3.1.1" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + } + ], + "time": "2025-04-16T22:59:48+00:00" + }, + { + "name": "pestphp/pest-plugin-mutate", + "version": "v3.0.5", + "source": { + "type": "git", + "url": "https://github.com/pestphp/pest-plugin-mutate.git", + "reference": "e10dbdc98c9e2f3890095b4fe2144f63a5717e08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pestphp/pest-plugin-mutate/zipball/e10dbdc98c9e2f3890095b4fe2144f63a5717e08", + "reference": "e10dbdc98c9e2f3890095b4fe2144f63a5717e08", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.2.0", + "pestphp/pest-plugin": "^3.0.0", + "php": "^8.2", + "psr/simple-cache": "^3.0.0" + }, + "require-dev": { + "pestphp/pest": "^3.0.8", + "pestphp/pest-dev-tools": "^3.0.0", + "pestphp/pest-plugin-type-coverage": "^3.0.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Pest\\Mutate\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sandro Gehri", + "email": "sandrogehri@gmail.com" + } + ], + "description": "Mutates your code to find untested cases", + "keywords": [ + "framework", + "mutate", + "mutation", + "pest", + "php", + "plugin", + "test", + "testing", + "unit" + ], + "support": { + "source": "https://github.com/pestphp/pest-plugin-mutate/tree/v3.0.5" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/gehrisandro", + "type": "github" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + } + ], + "time": "2024-09-22T07:54:40+00:00" + }, + { + "name": "phar-io/manifest", + "version": "2.0.4", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "54750ef60c58e43759730615a392c31c80e23176" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176", + "reference": "54750ef60c58e43759730615a392c31c80e23176", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-phar": "*", + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:33:53+00:00" + }, + { + "name": "phar-io/version", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.2.1" + }, + "time": "2022-02-21T01:04:05+00:00" + }, + { + "name": "phpdocumentor/reflection-common", + "version": "2.2.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionCommon.git", + "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/1d01c49d4ed62f25aa84a747ad35d5a16924662b", + "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-2.x": "2.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jaap van Otterdijk", + "email": "opensource@ijaap.nl" + } + ], + "description": "Common reflection classes used by phpdocumentor to reflect the code structure", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "FQSEN", + "phpDocumentor", + "phpdoc", + "reflection", + "static analysis" + ], + "support": { + "issues": "https://github.com/phpDocumentor/ReflectionCommon/issues", + "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x" + }, + "time": "2020-06-27T09:03:43+00:00" + }, + { + "name": "phpdocumentor/reflection-docblock", + "version": "5.6.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", + "reference": "92dde6a5919e34835c506ac8c523ef095a95ed62" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/92dde6a5919e34835c506ac8c523ef095a95ed62", + "reference": "92dde6a5919e34835c506ac8c523ef095a95ed62", + "shasum": "" + }, + "require": { + "doctrine/deprecations": "^1.1", + "ext-filter": "*", + "php": "^7.4 || ^8.0", + "phpdocumentor/reflection-common": "^2.2", + "phpdocumentor/type-resolver": "^1.7", + "phpstan/phpdoc-parser": "^1.7|^2.0", + "webmozart/assert": "^1.9.1" + }, + "require-dev": { + "mockery/mockery": "~1.3.5 || ~1.6.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-webmozart-assert": "^1.2", + "phpunit/phpunit": "^9.5", + "psalm/phar": "^5.26" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + }, + { + "name": "Jaap van Otterdijk", + "email": "opensource@ijaap.nl" + } + ], + "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", + "support": { + "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues", + "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.6.2" + }, + "time": "2025-04-13T19:20:35+00:00" + }, + { + "name": "phpdocumentor/type-resolver", + "version": "1.10.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/TypeResolver.git", + "reference": "679e3ce485b99e84c775d28e2e96fade9a7fb50a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/679e3ce485b99e84c775d28e2e96fade9a7fb50a", + "reference": "679e3ce485b99e84c775d28e2e96fade9a7fb50a", + "shasum": "" + }, + "require": { + "doctrine/deprecations": "^1.0", + "php": "^7.3 || ^8.0", + "phpdocumentor/reflection-common": "^2.0", + "phpstan/phpdoc-parser": "^1.18|^2.0" + }, + "require-dev": { + "ext-tokenizer": "*", + "phpbench/phpbench": "^1.2", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-phpunit": "^1.1", + "phpunit/phpunit": "^9.5", + "rector/rector": "^0.13.9", + "vimeo/psalm": "^4.25" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-1.x": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", + "support": { + "issues": "https://github.com/phpDocumentor/TypeResolver/issues", + "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.10.0" + }, + "time": "2024-11-09T15:12:26+00:00" + }, + { + "name": "phpstan/phpdoc-parser", + "version": "2.1.0", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpdoc-parser.git", + "reference": "9b30d6fd026b2c132b3985ce6b23bec09ab3aa68" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/9b30d6fd026b2c132b3985ce6b23bec09ab3aa68", + "reference": "9b30d6fd026b2c132b3985ce6b23bec09ab3aa68", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "doctrine/annotations": "^2.0", + "nikic/php-parser": "^5.3.0", + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^9.6", + "symfony/process": "^5.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPStan\\PhpDocParser\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPDoc parser with support for nullable, intersection and generic types", + "support": { + "issues": "https://github.com/phpstan/phpdoc-parser/issues", + "source": "https://github.com/phpstan/phpdoc-parser/tree/2.1.0" + }, + "time": "2025-02-19T13:28:12+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "11.0.10", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "1a800a7446add2d79cc6b3c01c45381810367d76" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/1a800a7446add2d79cc6b3c01c45381810367d76", + "reference": "1a800a7446add2d79cc6b3c01c45381810367d76", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-xmlwriter": "*", + "nikic/php-parser": "^5.4.0", + "php": ">=8.2", + "phpunit/php-file-iterator": "^5.1.0", + "phpunit/php-text-template": "^4.0.1", + "sebastian/code-unit-reverse-lookup": "^4.0.1", + "sebastian/complexity": "^4.0.1", + "sebastian/environment": "^7.2.0", + "sebastian/lines-of-code": "^3.0.1", + "sebastian/version": "^5.0.2", + "theseer/tokenizer": "^1.2.3" + }, + "require-dev": { + "phpunit/phpunit": "^11.5.2" + }, + "suggest": { + "ext-pcov": "PHP extension that provides line coverage", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/show" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-code-coverage", + "type": "tidelift" + } + ], + "time": "2025-06-18T08:56:18+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "5.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "118cfaaa8bc5aef3287bf315b6060b1174754af6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/118cfaaa8bc5aef3287bf315b6060b1174754af6", + "reference": "118cfaaa8bc5aef3287bf315b6060b1174754af6", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/5.1.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-08-27T05:02:59+00:00" + }, + { + "name": "phpunit/php-invoker", + "version": "5.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/c1ca3814734c07492b3d4c5f794f4b0995333da2", + "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^11.0" + }, + "suggest": { + "ext-pcntl": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", + "keywords": [ + "process" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-invoker/issues", + "security": "https://github.com/sebastianbergmann/php-invoker/security/policy", + "source": "https://github.com/sebastianbergmann/php-invoker/tree/5.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:07:44+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/3e0404dc6b300e6bf56415467ebcb3fe4f33e964", + "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "security": "https://github.com/sebastianbergmann/php-text-template/security/policy", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:08:43+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "7.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3b415def83fbcb41f991d9ebf16ae4ad8b7837b3", + "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "security": "https://github.com/sebastianbergmann/php-timer/security/policy", + "source": "https://github.com/sebastianbergmann/php-timer/tree/7.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:09:35+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "11.5.15", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "4b6a4ee654e5e0c5e1f17e2f83c0f4c91dee1f9c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/4b6a4ee654e5e0c5e1f17e2f83c0f4c91dee1f9c", + "reference": "4b6a4ee654e5e0c5e1f17e2f83c0f4c91dee1f9c", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.13.0", + "phar-io/manifest": "^2.0.4", + "phar-io/version": "^3.2.1", + "php": ">=8.2", + "phpunit/php-code-coverage": "^11.0.9", + "phpunit/php-file-iterator": "^5.1.0", + "phpunit/php-invoker": "^5.0.1", + "phpunit/php-text-template": "^4.0.1", + "phpunit/php-timer": "^7.0.1", + "sebastian/cli-parser": "^3.0.2", + "sebastian/code-unit": "^3.0.3", + "sebastian/comparator": "^6.3.1", + "sebastian/diff": "^6.0.2", + "sebastian/environment": "^7.2.0", + "sebastian/exporter": "^6.3.0", + "sebastian/global-state": "^7.0.2", + "sebastian/object-enumerator": "^6.0.1", + "sebastian/type": "^5.1.2", + "sebastian/version": "^5.0.2", + "staabm/side-effects-detector": "^1.0.5" + }, + "suggest": { + "ext-soap": "To be able to generate mocks based on WSDL files" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.5-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.15" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsors.html", + "type": "custom" + }, + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit", + "type": "tidelift" + } + ], + "time": "2025-03-23T16:02:11+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/15c5dd40dc4f38794d383bb95465193f5e0ae180", + "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "support": { + "issues": "https://github.com/sebastianbergmann/cli-parser/issues", + "security": "https://github.com/sebastianbergmann/cli-parser/security/policy", + "source": "https://github.com/sebastianbergmann/cli-parser/tree/3.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:41:36+00:00" + }, + { + "name": "sebastian/code-unit", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/54391c61e4af8078e5b276ab082b6d3c54c9ad64", + "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit/issues", + "security": "https://github.com/sebastianbergmann/code-unit/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit/tree/3.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-03-19T07:56:08+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "183a9b2632194febd219bb9246eee421dad8d45e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/183a9b2632194febd219bb9246eee421dad8d45e", + "reference": "183a9b2632194febd219bb9246eee421dad8d45e", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:45:54+00:00" + }, + { + "name": "sebastian/comparator", + "version": "6.3.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "24b8fbc2c8e201bb1308e7b05148d6ab393b6959" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/24b8fbc2c8e201bb1308e7b05148d6ab393b6959", + "reference": "24b8fbc2c8e201bb1308e7b05148d6ab393b6959", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/diff": "^6.0", + "sebastian/exporter": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.4" + }, + "suggest": { + "ext-bcmath": "For comparing BcMath\\Number objects" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "security": "https://github.com/sebastianbergmann/comparator/security/policy", + "source": "https://github.com/sebastianbergmann/comparator/tree/6.3.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-03-07T06:57:01+00:00" + }, + { + "name": "sebastian/complexity", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/complexity.git", + "reference": "ee41d384ab1906c68852636b6de493846e13e5a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/ee41d384ab1906c68852636b6de493846e13e5a0", + "reference": "ee41d384ab1906c68852636b6de493846e13e5a0", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for calculating the complexity of PHP code units", + "homepage": "https://github.com/sebastianbergmann/complexity", + "support": { + "issues": "https://github.com/sebastianbergmann/complexity/issues", + "security": "https://github.com/sebastianbergmann/complexity/security/policy", + "source": "https://github.com/sebastianbergmann/complexity/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:49:50+00:00" + }, + { + "name": "sebastian/diff", + "version": "6.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/b4ccd857127db5d41a5b676f24b51371d76d8544", + "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0", + "symfony/process": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/6.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:53:05+00:00" + }, + { + "name": "sebastian/environment", + "version": "7.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/a5c75038693ad2e8d4b6c15ba2403532647830c4", + "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "https://github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "security": "https://github.com/sebastianbergmann/environment/security/policy", + "source": "https://github.com/sebastianbergmann/environment/tree/7.2.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/environment", + "type": "tidelift" + } + ], + "time": "2025-05-21T11:55:47+00:00" + }, + { + "name": "sebastian/exporter", + "version": "6.3.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "3473f61172093b2da7de1fb5782e1f24cc036dc3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/3473f61172093b2da7de1fb5782e1f24cc036dc3", + "reference": "3473f61172093b2da7de1fb5782e1f24cc036dc3", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "https://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "security": "https://github.com/sebastianbergmann/exporter/security/policy", + "source": "https://github.com/sebastianbergmann/exporter/tree/6.3.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-12-05T09:17:50+00:00" + }, + { + "name": "sebastian/global-state", + "version": "7.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "3be331570a721f9a4b5917f4209773de17f747d7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/3be331570a721f9a4b5917f4209773de17f747d7", + "reference": "3be331570a721f9a4b5917f4209773de17f747d7", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "https://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "security": "https://github.com/sebastianbergmann/global-state/security/policy", + "source": "https://github.com/sebastianbergmann/global-state/tree/7.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:57:36+00:00" + }, + { + "name": "sebastian/lines-of-code", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/lines-of-code.git", + "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d36ad0d782e5756913e42ad87cb2890f4ffe467a", + "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for counting the lines of code in PHP source code", + "homepage": "https://github.com/sebastianbergmann/lines-of-code", + "support": { + "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", + "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy", + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:58:38+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "6.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "f5b498e631a74204185071eb41f33f38d64608aa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/f5b498e631a74204185071eb41f33f38d64608aa", + "reference": "f5b498e631a74204185071eb41f33f38d64608aa", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/6.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:00:13+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/6e1a43b411b2ad34146dee7524cb13a068bb35f9", + "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "security": "https://github.com/sebastianbergmann/object-reflector/security/policy", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:01:32+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "6.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "694d156164372abbd149a4b85ccda2e4670c0e16" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/694d156164372abbd149a4b85ccda2e4670c0e16", + "reference": "694d156164372abbd149a4b85ccda2e4670c0e16", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "https://github.com/sebastianbergmann/recursion-context", + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "security": "https://github.com/sebastianbergmann/recursion-context/security/policy", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:10:34+00:00" + }, + { + "name": "sebastian/type", + "version": "5.1.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "a8a7e30534b0eb0c77cd9d07e82de1a114389f5e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/a8a7e30534b0eb0c77cd9d07e82de1a114389f5e", + "reference": "a8a7e30534b0eb0c77cd9d07e82de1a114389f5e", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "security": "https://github.com/sebastianbergmann/type/security/policy", + "source": "https://github.com/sebastianbergmann/type/tree/5.1.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-03-18T13:35:50+00:00" + }, + { + "name": "sebastian/version", + "version": "5.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c687e3387b99f5b03b6caa64c74b63e2936ff874", + "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "security": "https://github.com/sebastianbergmann/version/security/policy", + "source": "https://github.com/sebastianbergmann/version/tree/5.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-10-09T05:16:32+00:00" + }, + { + "name": "staabm/side-effects-detector", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/staabm/side-effects-detector.git", + "reference": "d8334211a140ce329c13726d4a715adbddd0a163" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/staabm/side-effects-detector/zipball/d8334211a140ce329c13726d4a715adbddd0a163", + "reference": "d8334211a140ce329c13726d4a715adbddd0a163", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^1.12.6", + "phpunit/phpunit": "^9.6.21", + "symfony/var-dumper": "^5.4.43", + "tomasvotruba/type-coverage": "1.0.0", + "tomasvotruba/unused-public": "1.0.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "lib/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A static analysis tool to detect side effects in PHP code", + "keywords": [ + "static analysis" + ], + "support": { + "issues": "https://github.com/staabm/side-effects-detector/issues", + "source": "https://github.com/staabm/side-effects-detector/tree/1.0.5" + }, + "funding": [ + { + "url": "https://github.com/staabm", + "type": "github" + } + ], + "time": "2024-10-20T05:08:20+00:00" + }, + { + "name": "symfony/process", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "40c295f2deb408d5e9d2d32b8ba1dd61e36f05af" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/40c295f2deb408d5e9d2d32b8ba1dd61e36f05af", + "reference": "40c295f2deb408d5e9d2d32b8ba1dd61e36f05af", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-04-17T09:11:12+00:00" + }, + { + "name": "symfony/var-dumper", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "548f6760c54197b1084e1e5c71f6d9d523f2f78e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/548f6760c54197b1084e1e5c71f6d9d523f2f78e", + "reference": "548f6760c54197b1084e1e5c71f6d9d523f2f78e", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/console": "<6.4" + }, + "require-dev": { + "ext-iconv": "*", + "symfony/console": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/uid": "^6.4|^7.0", + "twig/twig": "^3.12" + }, + "bin": [ + "Resources/bin/var-dump-server" + ], + "type": "library", + "autoload": { + "files": [ + "Resources/functions/dump.php" + ], + "psr-4": { + "Symfony\\Component\\VarDumper\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides mechanisms for walking through any arbitrary PHP variable", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "support": { + "source": "https://github.com/symfony/var-dumper/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-04-27T18:39:23+00:00" + }, + { + "name": "ta-tikoma/phpunit-architecture-test", + "version": "0.8.5", + "source": { + "type": "git", + "url": "https://github.com/ta-tikoma/phpunit-architecture-test.git", + "reference": "cf6fb197b676ba716837c886baca842e4db29005" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ta-tikoma/phpunit-architecture-test/zipball/cf6fb197b676ba716837c886baca842e4db29005", + "reference": "cf6fb197b676ba716837c886baca842e4db29005", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^4.18.0 || ^5.0.0", + "php": "^8.1.0", + "phpdocumentor/reflection-docblock": "^5.3.0", + "phpunit/phpunit": "^10.5.5 || ^11.0.0 || ^12.0.0", + "symfony/finder": "^6.4.0 || ^7.0.0" + }, + "require-dev": { + "laravel/pint": "^1.13.7", + "phpstan/phpstan": "^1.10.52" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPUnit\\Architecture\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ni Shi", + "email": "futik0ma011@gmail.com" + }, + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "Methods for testing application architecture", + "keywords": [ + "architecture", + "phpunit", + "stucture", + "test", + "testing" + ], + "support": { + "issues": "https://github.com/ta-tikoma/phpunit-architecture-test/issues", + "source": "https://github.com/ta-tikoma/phpunit-architecture-test/tree/0.8.5" + }, + "time": "2025-04-20T20:23:40+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2", + "reference": "737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.2.3" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:36:25+00:00" + }, + { + "name": "webmozart/assert", + "version": "1.11.0", + "source": { + "type": "git", + "url": "https://github.com/webmozarts/assert.git", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/11cb2199493b2f8a3b53e7f19068fc6aac760991", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "php": "^7.2 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<0.12.20", + "vimeo/psalm": "<4.6.1 || 4.6.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.13" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/1.11.0" + }, + "time": "2022-06-03T18:03:27+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": true, + "prefer-lowest": false, + "platform": { + "php": ">=8.2" + }, + "platform-dev": {}, + "plugin-api-version": "2.6.0" +} diff --git a/cron.php b/cron.php index d500aeb14..d5c7a5823 100644 --- a/cron.php +++ b/cron.php @@ -1,6 +1,13 @@ - - - - \ No newline at end of file diff --git a/crowdin.yml b/crowdin.yml new file mode 100644 index 000000000..e3ecb4cd5 --- /dev/null +++ b/crowdin.yml @@ -0,0 +1,9 @@ +files: + - source: /styles/templates/default/images/lang/source/*.* + translation: /styles/templates/default/images/lang/%two_letters_code%/%original_file_name% + - source: /library/language/source/*.* + translation: /library/language/%two_letters_code%/%original_file_name% + - source: /library/language/source/email/*.* + translation: /library/language/%two_letters_code%/email/%original_file_name% + - source: /library/language/source/html/*.* + translation: /library/language/%two_letters_code%/html/%original_file_name% diff --git a/data/avatars/gallery/noavatar.png b/data/avatars/gallery/noavatar.png index d6da48389..acbe7c294 100644 Binary files a/data/avatars/gallery/noavatar.png and b/data/avatars/gallery/noavatar.png differ diff --git a/data/old_files/.htaccess b/data/old_files/.htaccess deleted file mode 100644 index 6c4686a91..000000000 --- a/data/old_files/.htaccess +++ /dev/null @@ -1,3 +0,0 @@ -php_flag engine off -RemoveHandler .php .php5 .php4 .php3 .phtml .pl .asp -AddType text/plain .php .php .htm .html .phtml .pl .asp \ No newline at end of file diff --git a/data/torrent_files/.htaccess b/data/torrent_files/.htaccess deleted file mode 100644 index 6c4686a91..000000000 --- a/data/torrent_files/.htaccess +++ /dev/null @@ -1,3 +0,0 @@ -php_flag engine off -RemoveHandler .php .php5 .php4 .php3 .phtml .pl .asp -AddType text/plain .php .php .htm .html .phtml .pl .asp \ No newline at end of file diff --git a/internal_data/ajax_html/.keep b/data/uploads/thumbs/.keep similarity index 100% rename from internal_data/ajax_html/.keep rename to data/uploads/thumbs/.keep diff --git a/dl.php b/dl.php index 845e7353f..bfc0ef678 100644 --- a/dl.php +++ b/dl.php @@ -1,78 +1,77 @@ enqueue(array( - 'attach_extensions', -)); +require __DIR__ . '/common.php'; +require ATTACH_DIR . '/attachment_mod.php'; + +$datastore->enqueue([ + 'attach_extensions', + 'cat_forums' +]); $download_id = request_var('id', 0); $thumbnail = request_var('thumb', 0); +$m3u = isset($_GET['m3u']) && $_GET['m3u']; // Send file to browser function send_file_to_browser($attachment, $upload_dir) { - global $lang, $attach_config; + global $lang; - $filename = ($upload_dir == '') ? $attachment['physical_filename'] : $upload_dir . '/' . $attachment['physical_filename']; + $filename = $upload_dir . '/' . $attachment['physical_filename']; + $gotit = false; - $gotit = false; + if (is_file(realpath($filename))) { + $gotit = true; + } else { + bb_die($lang['ERROR_NO_ATTACHMENT'] . '

' . htmlCHR($filename)); + } - if (@!file_exists(@amod_realpath($filename))) - { - bb_die($lang['ERROR_NO_ATTACHMENT'] . "

" . $filename. "

" .$lang['TOR_NOT_FOUND']); - } - else - { - $gotit = true; - } + // Correct the mime type - we force application/octet-stream for all files, except images + // Please do not change this, it is a security precaution + if (!str_contains($attachment['mimetype'], 'image')) { + $attachment['mimetype'] = 'application/octet-stream'; + } else { + header('Cache-Control: public, max-age=3600'); + } - // Correct the mime type - we force application/octet-stream for all files, except images - // Please do not change this, it is a security precaution - if (!strstr($attachment['mimetype'], 'image')) - { - $attachment['mimetype'] = 'application/octet-stream'; - } + //bt + if (!(isset($_GET['original']) && !IS_USER)) { + \TorrentPier\Legacy\Torrent::send_torrent_with_passkey($filename); + } - //bt - if (!(isset($_GET['original']) && !IS_USER)) - { - include(INC_DIR .'functions_torrent.php'); - send_torrent_with_passkey($filename); - } + // Now the tricky part... let's dance + header('Pragma: public'); + $real_filename = clean_filename(basename($attachment['real_filename'])); + $mimetype = $attachment['mimetype'] . ';'; + $charset = 'charset=' . DEFAULT_CHARSET . ';'; - // Now the tricky part... let's dance - header('Pragma: public'); - $real_filename = clean_filename(basename($attachment['real_filename'])); - $mimetype = $attachment['mimetype'].';'; - $charset = (isset($lang['CONTENT_ENCODING'])) ? "charset={$lang['CONTENT_ENCODING']};" : ''; + // Send out the Headers + header("Content-Type: $mimetype $charset name=\"$real_filename\""); + header("Content-Disposition: inline; filename=\"$real_filename\""); + unset($real_filename); - // Send out the Headers - header("Content-Type: $mimetype $charset name=\"$real_filename\""); - header("Content-Disposition: inline; filename=\"$real_filename\""); - unset($real_filename); + // Now send the File Contents to the Browser + if ($gotit) { + $size = filesize($filename); + if ($size) { + header("Content-length: $size"); + } + readfile($filename); + } else { + bb_die($lang['ERROR_NO_ATTACHMENT'] . '

' . htmlCHR($filename)); + } - // Now send the File Contents to the Browser - if ($gotit) - { - $size = @filesize($filename); - if ($size) - { - header("Content-length: $size"); - } - readfile($filename); - } - else - { - bb_die($lang['ERROR_NO_ATTACHMENT'] . "

" . $filename. "

" .$lang['TOR_NOT_FOUND']); - } - - exit; + exit; } // @@ -82,148 +81,164 @@ $user->session_start(); set_die_append_msg(); -if (!$download_id) -{ - bb_die($lang['NO_ATTACHMENT_SELECTED']); +if (!$download_id) { + bb_die($lang['NO_ATTACHMENT_SELECTED']); } -if ($attach_config['disable_mod'] && !IS_ADMIN) -{ - bb_die($lang['ATTACHMENT_FEATURE_DISABLED']); +if ($attach_config['disable_mod'] && !IS_ADMIN) { + bb_die($lang['ATTACHMENT_FEATURE_DISABLED']); } -$sql = 'SELECT * FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int) $download_id; +$sql = 'SELECT * FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int)$download_id; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not query attachment information #1'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information #1'); } -if (!($attachment = DB()->sql_fetchrow($result))) -{ - bb_die($lang['ERROR_NO_ATTACHMENT']); +if (!($attachment = DB()->sql_fetchrow($result))) { + bb_die($lang['ERROR_NO_ATTACHMENT']); } $attachment['physical_filename'] = basename($attachment['physical_filename']); +if ($thumbnail) { + // Re-define $attachment['physical_filename'] for thumbnails + $attachment['physical_filename'] = THUMB_DIR . '/t_' . $attachment['physical_filename']; +} elseif ($m3u) { + // Check m3u file exist + if (!$m3uFile = (new \TorrentPier\TorrServerAPI())->getM3UPath($download_id)) { + bb_die($lang['ERROR_NO_ATTACHMENT']); + } + + $attachment['physical_filename'] = $attachment['real_filename'] = basename($m3uFile); + $attachment['mimetype'] = mime_content_type($m3uFile); + $attachment['extension'] = str_replace('.', '', \TorrentPier\TorrServerAPI::M3U['extension']); +} + DB()->sql_freeresult($result); // get forum_id for attachment authorization or private message authorization $authorised = false; -$sql = 'SELECT * FROM ' . BB_ATTACHMENTS . ' WHERE attach_id = ' . (int) $attachment['attach_id']; +$sql = 'SELECT * FROM ' . BB_ATTACHMENTS . ' WHERE attach_id = ' . (int)$attachment['attach_id']; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not query attachment information #2'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information #2'); } $auth_pages = DB()->sql_fetchrowset($result); $num_auth_pages = DB()->num_rows($result); -for ($i = 0; $i < $num_auth_pages && $authorised == false; $i++) -{ - $auth_pages[$i]['post_id'] = intval($auth_pages[$i]['post_id']); +for ($i = 0; $i < $num_auth_pages && $authorised == false; $i++) { + $auth_pages[$i]['post_id'] = (int)$auth_pages[$i]['post_id']; - if ($auth_pages[$i]['post_id'] != 0) - { - $sql = 'SELECT forum_id, topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int) $auth_pages[$i]['post_id']; + if ($auth_pages[$i]['post_id'] != 0) { + $sql = 'SELECT forum_id, topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int)$auth_pages[$i]['post_id']; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query post information'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query post information'); + } - $row = DB()->sql_fetchrow($result); + $row = DB()->sql_fetchrow($result); - $topic_id = $row['topic_id']; - $forum_id = $row['forum_id']; + $topic_id = $row['topic_id']; + $forum_id = $row['forum_id']; - $is_auth = array(); - $is_auth = auth(AUTH_ALL, $forum_id, $userdata); - set_die_append_msg($forum_id, $topic_id); + $is_auth = auth(AUTH_ALL, $forum_id, $userdata); + set_die_append_msg($forum_id, $topic_id); - if ($is_auth['auth_download']) - { - $authorised = TRUE; - } - } + if ($is_auth['auth_download']) { + $authorised = true; + } + } } -if (!$authorised) -{ - bb_die($lang['SORRY_AUTH_VIEW_ATTACH']); +// Check the auth rights +if (!$authorised) { + bb_die($lang['SORRY_AUTH_VIEW_ATTACH'], 403); } $datastore->rm('cat_forums'); -// +// Check tor status +if (!IS_AM && ($attachment['mimetype'] === TORRENT_MIMETYPE)) { + $sql = 'SELECT tor_status, poster_id FROM ' . BB_BT_TORRENTS . ' WHERE attach_id = ' . (int)$attachment['attach_id']; + + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query tor_status information'); + } + + $row = DB()->sql_fetchrow($result); + + if (isset(config()->get('tor_frozen')[$row['tor_status']]) && !(isset(config()->get('tor_frozen_author_download')[$row['tor_status']]) && $userdata['user_id'] === $row['poster_id'])) { + bb_die($lang['TOR_STATUS_FORBIDDEN'] . $lang['TOR_STATUS_NAME'][$row['tor_status']]); + } + + DB()->sql_freeresult($result); +} + // Get Information on currently allowed Extensions -// $rows = get_extension_informations(); $num_rows = count($rows); -for ($i = 0; $i < $num_rows; $i++) -{ - $extension = strtolower(trim($rows[$i]['extension'])); - $allowed_extensions[] = $extension; - $download_mode[$extension] = $rows[$i]['download_mode']; +$allowed_extensions = $download_mode = []; +for ($i = 0; $i < $num_rows; $i++) { + $extension = strtolower(trim($rows[$i]['extension'])); + // Get allowed extensions + if ((int)$rows[$i]['allow_group'] === 1) { + $allowed_extensions[] = $extension; + } + $download_mode[$extension] = $rows[$i]['download_mode']; } // Disallowed -if (!in_array($attachment['extension'], $allowed_extensions) && !IS_ADMIN) -{ - bb_die(sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])); +if (!in_array($attachment['extension'], $allowed_extensions) && !IS_ADMIN) { + bb_die(sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension']) . '

' . $lang['FILENAME'] . ": " . $attachment['physical_filename']); } -$download_mode = intval($download_mode[$attachment['extension']]); - -if ($thumbnail) -{ - $attachment['physical_filename'] = THUMB_DIR . '/t_' . $attachment['physical_filename']; +// Getting download mode by extension +if (isset($download_mode[$attachment['extension']])) { + $download_mode = (int)$download_mode[$attachment['extension']]; +} else { + bb_die(sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension']) . '

' . $lang['FILENAME'] . ": " . $attachment['physical_filename']); } // Update download count -if (!$thumbnail) -{ - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET download_count = download_count + 1 WHERE attach_id = ' . (int) $attachment['attach_id']; +if (!$m3u && !$thumbnail && is_file(realpath($upload_dir . '/' . $attachment['physical_filename']))) { + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET download_count = download_count + 1 WHERE attach_id = ' . (int)$attachment['attach_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update attachment download count'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update attachment download count'); + } } // Determine the 'presenting'-method -if ($download_mode == PHYSICAL_LINK) -{ - $url = make_url($upload_dir . '/' . $attachment['physical_filename']); - header('Location: ' . $url); - exit; +switch ($download_mode) { + case PHYSICAL_LINK: + $url = make_url($upload_dir . '/' . $attachment['physical_filename']); + header('Location: ' . $url); + exit; + case INLINE_LINK: + if (IS_GUEST && !config()->get('captcha.disabled') && !bb_captcha('check')) { + global $template; + + $redirect_url = $_POST['redirect_url'] ?? $_SERVER['HTTP_REFERER'] ?? '/'; + $message = '
'; + $message .= $lang['CAPTCHA'] . ':'; + $message .= '
' . bb_captcha('get') . '
'; + $message .= ''; + $message .= '  '; + $message .= ''; + $message .= '
'; + + $template->assign_vars(['ERROR_MESSAGE' => $message]); + + require(PAGE_HEADER); + require(PAGE_FOOTER); + } + + send_file_to_browser($attachment, $upload_dir); + exit; + default: + bb_die('Incorrect download mode: ' . $download_mode); } -else -{ - if (IS_GUEST && !CAPTCHA()->verify_code()) - { - global $template; - - $redirect_url = isset($_POST['redirect_url']) ? $_POST['redirect_url'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/'); - $message = '
'; - $message .= $lang['CONFIRM_CODE']; - $message .= '
'. CAPTCHA()->get_html() .'
'; - $message .= ''; - $message .= '  '; - $message .= ''; - $message .= '
'; - - $template->assign_vars(array( - 'ERROR_MESSAGE' => $message, - )); - - require(PAGE_HEADER); - require(PAGE_FOOTER); - } - - send_file_to_browser($attachment, $upload_dir); - exit; -} \ No newline at end of file diff --git a/dl_list.php b/dl_list.php index d4db8fd9c..d31bb701b 100644 --- a/dl_list.php +++ b/dl_list.php @@ -1,56 +1,49 @@ session_start(); set_die_append_msg(); // Check if user logged in -if (!$userdata['session_logged_in']) -{ - redirect(LOGIN_URL . "?redirect=$redirect_type&$redirect"); +if (IS_GUEST) { + redirect(LOGIN_URL . "?redirect=$redirect_type&$redirect"); } // Check if user did not confirm -if (isset($_POST['cancel']) && $_POST['cancel']) -{ - redirect("$redirect_type?$redirect"); +if (isset($_POST['cancel']) && $_POST['cancel']) { + redirect("$redirect_type?$redirect"); } // Delete DL-list -if ($mode == 'dl_delete' && $topic_id) -{ - if (!IS_ADMIN) - { - $sql = "SELECT forum_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id LIMIT 1"; +if ($mode == 'dl_delete' && $topic_id) { + if (!IS_ADMIN) { + $sql = "SELECT forum_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id LIMIT 1"; - if (!$row = DB()->sql_fetchrow(DB()->sql_query($sql))) - { - bb_die('Could not obtain forum_id for this topic'); - } + if (!$row = DB()->sql_fetchrow(DB()->sql_query($sql))) { + bb_die('Could not obtain forum_id for this topic'); + } - $is_auth = auth(AUTH_ALL, $row['forum_id'], $userdata); + $is_auth = auth(AUTH_ALL, $row['forum_id'], $userdata); - if (!$is_auth['auth_mod']) - { - bb_die($lang['NOT_MODERATOR']); - } - } + if (!$is_auth['auth_mod']) { + bb_die($lang['NOT_MODERATOR']); + } + } - if (!$confirmed) - { - $hidden_fields = array( - 't' => $topic_id, - 'mode' => 'dl_delete', - ); + if (!$confirmed) { + $hidden_fields = [ + POST_TOPIC_URL => $topic_id, + 'mode' => 'dl_delete', + ]; - print_confirmation(array( - 'QUESTION' => $lang['DL_LIST_DEL_CONFIRM'], - 'FORM_ACTION' => 'dl_list.php', - 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - )); - } + print_confirmation([ + 'QUESTION' => $lang['DL_LIST_DEL_CONFIRM'], + 'FORM_ACTION' => 'dl_list.php', + 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + ]); + } - clear_dl_list($topic_id); - redirect("$redirect_type?$redirect"); + clear_dl_list($topic_id); + redirect("$redirect_type?$redirect"); } // Update DL status -$req_topics_ary = $topics_ary = array(); +$req_topics_ary = $topics_ary = []; // Get topics selected by user -if ($mode == 'set_topics_dl_status') -{ - if (!isset($_POST['dl_topics_id_list']) || !is_array($_POST['dl_topics_id_list'])) - { - bb_die($lang['NONE_SELECTED']); - } +if ($mode == 'set_topics_dl_status') { + if (!isset($_POST['dl_topics_id_list']) || !is_array($_POST['dl_topics_id_list'])) { + bb_die($lang['NONE_SELECTED']); + } - foreach ($_POST['dl_topics_id_list'] as $topic_id) - { - $req_topics_ary[] = (int) $topic_id; - } -} -elseif ($mode == 'set_dl_status') -{ - $req_topics_ary[] = (int) $topic_id; + foreach ($_POST['dl_topics_id_list'] as $topic_id) { + $req_topics_ary[] = (int)$topic_id; + } +} elseif ($mode == 'set_dl_status') { + $req_topics_ary[] = (int)$topic_id; } // Get existing topics -if ($req_topics_sql = join(',', $req_topics_ary)) -{ - $sql = "SELECT topic_id FROM ". BB_TOPICS ." WHERE topic_id IN($req_topics_sql)"; +if ($req_topics_sql = implode(',', $req_topics_ary)) { + $sql = "SELECT topic_id FROM " . BB_TOPICS . " WHERE topic_id IN($req_topics_sql)"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $topics_ary[] = $row['topic_id']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topics_ary[] = $row['topic_id']; + } } -if ($topics_ary && ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')) -{ - $new_dlstatus_ary = array(); +if ($topics_ary && ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')) { + $new_dlstatus_ary = []; - foreach ($topics_ary as $topic_id) - { - $new_dlstatus_ary[] = array( - 'user_id' => (int) $user->id, - 'topic_id' => (int) $topic_id, - 'user_status' => (int) $new_dl_status, - ); - } - $new_dlstatus_sql = DB()->build_array('MULTI_INSERT', $new_dlstatus_ary); + foreach ($topics_ary as $topic_id) { + $new_dlstatus_ary[] = [ + 'user_id' => (int)$user->id, + 'topic_id' => (int)$topic_id, + 'user_status' => (int)$new_dl_status, + ]; + } + $new_dlstatus_sql = DB()->build_array('MULTI_INSERT', $new_dlstatus_ary); - DB()->query("REPLACE INTO ". BB_BT_DLSTATUS ." $new_dlstatus_sql"); + DB()->query("REPLACE INTO " . BB_BT_DLSTATUS . " $new_dlstatus_sql"); - redirect("$redirect_type?$redirect"); + redirect("$redirect_type?$redirect"); } -redirect("index.php"); \ No newline at end of file +redirect('index.php'); diff --git a/favicon.ico b/favicon.ico deleted file mode 100644 index 6685e930e..000000000 Binary files a/favicon.ico and /dev/null differ diff --git a/favicon.png b/favicon.png new file mode 100644 index 000000000..3c6b8feed Binary files /dev/null and b/favicon.png differ diff --git a/feed.php b/feed.php index 454c6dd56..bbd9eb3e0 100644 --- a/feed.php +++ b/feed.php @@ -1,68 +1,67 @@ session_start(array('req_login' => true)); +require __DIR__ . '/common.php'; -$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : ''; -$type = isset($_POST['type']) ? $_POST['type'] : ''; -$id = isset($_POST['id']) ? $_POST['id'] : 0; +// Init userdata +$user->session_start(['req_login' => true]); + +$mode = $_REQUEST['mode'] ?? ''; +$type = $_POST['type'] ?? ''; +$id = isset($_POST['id']) ? (int)$_POST['id'] : 0; $timecheck = TIMENOW - 600; -if (!$mode) bb_simple_die($lang['ATOM_NO_MODE']); - -if ($mode == 'get_feed_url' && ($type == 'f' || $type == 'u') && $id >= 0) -{ - if ($type == 'f') - { - // Check if the user has actually sent a forum ID - $sql = "SELECT allow_reg_tracker, forum_name FROM ". BB_FORUMS ." WHERE forum_id = $id LIMIT 1"; - if (!$forum_data = DB()->fetch_row($sql)) - { - if ($id == 0) - { - $forum_data = array(); - } - else bb_simple_die($lang['ATOM_ERROR'].' #1'); - } - if (file_exists($bb_cfg['atom']['path'] .'/f/'. $id .'.atom') && filemtime($bb_cfg['atom']['path'] .'/f/'. $id .'.atom') > $timecheck) - { - redirect($bb_cfg['atom']['url'] .'/f/'. $id .'.atom'); - } - else - { - require_once(INC_DIR .'functions_atom.php'); - if (update_forum_feed($id, $forum_data)) redirect($bb_cfg['atom']['url'] .'/f/'. $id .'.atom'); - else bb_simple_die($lang['ATOM_NO_FORUM']); - } - } - if ($type == 'u') - { - // Check if the user has actually sent a user ID - if ($id < 1) - { - bb_simple_die($lang['ATOM_ERROR'].' #2'); - } - if (!$username = get_username($id)) - { - bb_simple_die($lang['ATOM_ERROR'].' #3'); - } - if (file_exists($bb_cfg['atom']['path'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom') && filemtime($bb_cfg['atom']['path'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom') > $timecheck) - { - redirect($bb_cfg['atom']['url'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom'); - } - else - { - require_once(INC_DIR .'functions_atom.php'); - if (update_user_feed($id, $username)) redirect($bb_cfg['atom']['url'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom'); - else bb_simple_die($lang['ATOM_NO_USER']); - } - } +if (!$mode) { + bb_simple_die($lang['ATOM_NO_MODE']); +} + +if ($mode === 'get_feed_url' && ($type === 'f' || $type === 'u') && $id >= 0) { + if ($type == 'f') { + // Check if the user has actually sent a forum ID + $sql = "SELECT allow_reg_tracker, forum_name FROM " . BB_FORUMS . " WHERE forum_id = $id LIMIT 1"; + if (!$forum_data = DB()->fetch_row($sql)) { + if ($id == 0) { + $forum_data = []; + } else { + bb_simple_die($lang['ATOM_ERROR'] . ' #1'); + } + } + if (is_file(config()->get('atom.path') . '/f/' . $id . '.atom') && filemtime(config()->get('atom.path') . '/f/' . $id . '.atom') > $timecheck) { + redirect(config()->get('atom.url') . '/f/' . $id . '.atom'); + } else { + if (\TorrentPier\Legacy\Atom::update_forum_feed($id, $forum_data)) { + redirect(config()->get('atom.url') . '/f/' . $id . '.atom'); + } else { + bb_simple_die($lang['ATOM_NO_FORUM']); + } + } + } + if ($type === 'u') { + // Check if the user has actually sent a user ID + if ($id < 1) { + bb_simple_die($lang['ATOM_ERROR'] . ' #2'); + } + if (!$username = get_username($id)) { + bb_simple_die($lang['ATOM_ERROR'] . ' #3'); + } + if (is_file(config()->get('atom.path') . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom') && filemtime(config()->get('atom.path') . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom') > $timecheck) { + redirect(config()->get('atom.url') . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom'); + } else { + if (\TorrentPier\Legacy\Atom::update_user_feed($id, $username)) { + redirect(config()->get('atom.url') . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom'); + } else { + bb_simple_die($lang['ATOM_NO_USER']); + } + } + } +} else { + bb_simple_die($lang['ATOM_ERROR'] . ' #4'); } -else -{ - bb_simple_die($lang['ATOM_ERROR'].' #4'); -} \ No newline at end of file diff --git a/filelist.php b/filelist.php new file mode 100644 index 000000000..b07e319c6 --- /dev/null +++ b/filelist.php @@ -0,0 +1,117 @@ +session_start(); + +if (config()->get('bt_disable_dht') && IS_GUEST) { + bb_die($lang['BT_PRIVATE_TRACKER'], 403); +} + +$topic_id = isset($_GET[POST_TOPIC_URL]) ? (int)$_GET[POST_TOPIC_URL] : 0; +if (!$topic_id) { + bb_die($lang['INVALID_TOPIC_ID'], 404); +} + +$sql = 'SELECT t.forum_id, t.attach_id, t.info_hash, t.info_hash_v2, t.size, ad.physical_filename + FROM ' . BB_BT_TORRENTS . ' t + LEFT JOIN ' . BB_ATTACHMENTS_DESC . ' ad + ON t.attach_id = ad.attach_id + WHERE t.topic_id = ' . $topic_id . ' + LIMIT 1'; + +if (!$row = DB()->fetch_row($sql)) { + bb_die($lang['INVALID_TOPIC_ID_DB'], 404); +} + +// Check rights +$is_auth = auth(AUTH_ALL, $row['forum_id'], $userdata); +if (!$is_auth['auth_view']) { + bb_die($lang['SORRY_AUTH_VIEW_ATTACH'], 403); +} + +// Protocol meta +$meta_v1 = !empty($row['info_hash']); +$meta_v2 = !empty($row['info_hash_v2']); + +// Method fields +$t_version_field = $meta_v2 ? 'v2' : 'v1'; +$t_files_field = $meta_v2 ? 'getFileTree' : 'getFiles'; +$t_hash_field = $meta_v2 ? 'piecesRoot' : 'sha1'; + +$file_path = get_attachments_dir() . '/' . $row['physical_filename']; +if (!is_file($file_path)) { + bb_die($lang['TOR_NOT_FOUND'], 410); +} + +$file_contents = file_get_contents($file_path); +if (config()->get('flist_max_files')) { + $filetree_pos = $meta_v2 ? strpos($file_contents, '9:file tree') : false; + $files_pos = $meta_v1 ? strpos($file_contents, '5:files', $filetree_pos) : false; + + if ($filetree_pos) { + $file_count = substr_count($file_contents, '6:length', $filetree_pos, ($files_pos ? ($files_pos - $filetree_pos) : null)); + } else { + $file_count = substr_count($file_contents, '6:length', $files_pos); + } + + if ($file_count > config()->get('flist_max_files')) { + bb_die(sprintf($lang['BT_FLIST_LIMIT'], config()->get('flist_max_files'), $file_count), 410); + } +} + +try { + $torrent = \Arokettu\Torrent\TorrentFile::loadFromString($file_contents); +} catch (\Exception $e) { + bb_die(htmlCHR("{$lang['TORFILE_INVALID']}: {$e->getMessage()}"), 410); +} + +if (IS_GUEST && $torrent->isPrivate()) { + bb_die($lang['BT_PRIVATE_TORRENT'], 403); +} + +// Get torrent files +$files = $torrent->$t_version_field()->$t_files_field(); +if ($meta_v2) { + $files = new \RecursiveIteratorIterator($files); // Flatten the list +} + +$files_count = 0; +foreach ($files as $file) { + $files_count++; + $row_class = ($files_count % 2) ? 'row1' : 'row2'; + $template->assign_block_vars('filelist', [ + 'ROW_NUMBER' => $files_count, + 'ROW_CLASS' => $row_class, + 'FILE_PATH' => clean_tor_dirname(implode('/', $file->path)), + 'FILE_LENGTH' => humn_size($file->length, 2), + 'FILE_HASH' => $file->$t_hash_field ?? '-' + ]); +} + +$torrent_name = !empty($t_name = $torrent->getName()) ? str_short(htmlCHR($t_name), 200) : $lang['UNKNOWN']; +$torrent_size = humn_size($row['size'], 2); + +// Output page +$template->assign_vars([ + 'PAGE_TITLE' => "$torrent_name (" . $torrent_size . ")", + 'FILES_COUNT' => sprintf($lang['BT_FLIST_FILE_PATH'], declension(iterator_count($files), 'files')), + 'TORRENT_CREATION_DATE' => (!empty($dt = $torrent->getCreationDate()) && is_numeric($creation_date = $dt->getTimestamp())) ? date('d-M-Y H:i (e)', $creation_date) : $lang['UNKNOWN'], + 'TORRENT_CLIENT' => !empty($creator = $torrent->getCreatedBy()) ? htmlCHR($creator) : $lang['UNKNOWN'], + 'TORRENT_PRIVATE' => $torrent->isPrivate() ? $lang['YES'] : $lang['NO'], + + 'BTMR_NOTICE' => sprintf($lang['BT_FLIST_BTMR_NOTICE'], 'https://github.com/kovalensky/tmrr'), + 'U_TOPIC' => TOPIC_URL . $topic_id, +]); + +print_page('filelist.tpl'); diff --git a/group.php b/group.php index 38778d453..e88bb6de7 100644 --- a/group.php +++ b/group.php @@ -1,78 +1,53 @@ '. $lang['SEND_PM_TXTB'] .'' : '' . $lang['SEND_PRIVATE_MESSAGE'] . ''; - $avatar = get_avatar($row['user_id'], $row['avatar_ext_id'], !bf($row['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50); - - if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || $group_mod) - { - $email_uri = ($bb_cfg['board_email_form']) ? ("profile.php?mode=email&". POST_USERS_URL ."=".$row['user_id']) : 'mailto:'. $row['user_email']; - $email = ''. $row['user_email'] .''; - } - else $email = ''; - - if ($row['user_website']) - { - $www = ($bb_cfg['text_buttons']) ? ''. $lang['VISIT_WEBSITE_TXTB'] .'' : '' . $lang['VISIT_WEBSITE'] . ''; - } - else $www = ''; - - return; -} - -$user->session_start(array('req_login' => true)); +// Init userdata +$user->session_start(['req_login' => true]); set_die_append_msg(); -$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : null; -$start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; -$per_page = $bb_cfg['group_members_per_page']; -$view_mode = isset($_REQUEST['view']) ? (string) $_REQUEST['view'] : null; +$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? (int)$_REQUEST[POST_GROUPS_URL] : null; +$start = isset($_REQUEST['start']) ? abs((int)$_REQUEST['start']) : 0; +$per_page = config()->get('group_members_per_page'); +$view_mode = isset($_REQUEST['view']) ? (string)$_REQUEST['view'] : null; $rel_limit = 50; -$group_info = array(); +$group_info = []; $is_moderator = false; -if ($group_id) -{ - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } - if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) - { - bb_die("Invalid group data [group_id: $group_id]"); - } - $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); +if ($group_id) { + if (!$group_info = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) { + bb_die("Invalid group data [group_id: $group_id]"); + } + $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); } -if (!$group_id) -{ - // Show the main screen where the user can select a group. - $groups = array(); - $pending = 10; - $member = 20; +if (!$group_id) { + // Show the main screen where the user can select a group. + $groups = []; + $pending = 10; + $member = 20; - $sql = " + $sql = " SELECT g.group_name, g.group_description, g.group_id, g.group_type, g.release_group, IF(ug.user_id IS NOT NULL, IF(ug.user_pending = 1, $pending, $member), 0) AS membership, @@ -80,16 +55,16 @@ if (!$group_id) IF(g.group_moderator = ug.user_id, 1, 0) AS is_group_mod, COUNT(ug2.user_id) AS members, SUM(ug2.user_pending) AS candidates FROM - ". BB_GROUPS ." g + " . BB_GROUPS . " g LEFT JOIN - ". BB_USER_GROUP ." ug ON + " . BB_USER_GROUP . " ug ON ug.group_id = g.group_id - AND ug.user_id = ". $userdata['user_id'] ." + AND ug.user_id = " . $userdata['user_id'] . " LEFT JOIN - ". BB_USER_GROUP ." ug2 ON + " . BB_USER_GROUP . " ug2 ON ug2.group_id = g.group_id LEFT JOIN - ". BB_USERS ." u ON g.group_moderator = u.user_id + " . BB_USERS . " u ON g.group_moderator = u.user_id WHERE g.group_single_user = 0 GROUP BY g.group_id @@ -100,597 +75,526 @@ if (!$group_id) g.group_name ASC "; - foreach (DB()->fetch_rowset($sql) as $row) - { - if ($row['is_group_mod']) - { - $type = 'MOD'; - } - else if ($row['membership'] == $member) - { - $type = 'MEMBER'; - } - else if ($row['membership'] == $pending) - { - $type = 'PENDING'; - } - else if ($row['group_type'] == GROUP_OPEN) - { - $type = 'OPEN'; - } - else if ($row['group_type'] == GROUP_CLOSED) - { - $type = 'CLOSED'; - } - else if ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) - { - $type = 'HIDDEN'; - } - else - { - continue; - } + foreach (DB()->fetch_rowset($sql) as $row) { + if ($row['is_group_mod']) { + $type = 'MOD'; + } elseif ($row['membership'] == $member) { + $type = 'MEMBER'; + } elseif ($row['membership'] == $pending) { + $type = 'PENDING'; + } elseif ($row['group_type'] == GROUP_OPEN) { + $type = 'OPEN'; + } elseif ($row['group_type'] == GROUP_CLOSED) { + $type = 'CLOSED'; + } elseif ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) { + $type = 'HIDDEN'; + } else { + continue; + } - $data = array('id' => $row['group_id'], 'm' => ($row['members'] - $row['candidates']), 'c' => $row['candidates'], 'rg' => $row['release_group']); + $data = ['id' => $row['group_id'], 'm' => ($row['members'] - $row['candidates']), 'c' => $row['candidates'], 'rg' => $row['release_group']]; - $groups[$type][$row['group_name']] = $data; - } + $groups[$type][$row['group_name']] = $data; + } - function build_group($params) - { - global $lang; + function build_group($params) + { + global $lang; - $options = ''; - foreach ($params as $name => $data) - { - $text = htmlCHR(str_short(rtrim($name), HTML_SELECT_MAX_LENGTH)); + $options = ''; + foreach ($params as $name => $data) { + $text = str_short(rtrim(htmlCHR($name)), HTML_SELECT_MAX_LENGTH); - $members = ($data['m']) ? $lang['MEMBERS_IN_GROUP'] .': '. $data['m'] : $lang['NO_GROUP_MEMBERS']; - $candidates = ($data['c']) ? $lang['PENDING_MEMBERS'] .': '. $data['c'] : $lang['NO_PENDING_GROUP_MEMBERS']; + $members = ($data['m']) ? $lang['MEMBERS_IN_GROUP'] . ': ' . $data['m'] : $lang['NO_GROUP_MEMBERS']; + $candidates = ($data['c']) ? $lang['PENDING_MEMBERS'] . ': ' . $data['c'] : $lang['NO_PENDING_GROUP_MEMBERS']; - $options .= '
  • '. $text .'
  • '; - $options .= ($data['rg']) ? '
    • '. $lang['RELEASE_GROUP'] .'
    • ' : '
        '; - $options .= '
      • '. $members .'
      • '; - if (IS_AM) - { - $options .= '
      • '. $candidates .'
      • '; - } - $options .= '
      '; - } - return $options; - } + $options .= '
    • ' . $text . '
    • '; + $options .= ($data['rg']) ? '
      • ' . $lang['RELEASE_GROUP'] . '
      • ' : '
          '; + $options .= '
        • ' . $members . '
        • '; + if (IS_AM) { + $options .= '
        • ' . $candidates . '
        • '; + } + $options .= '
        '; + } + return $options; + } - if ($groups) - { - $s_hidden_fields = ''; + if ($groups) { + $s_hidden_fields = ''; - foreach ($groups as $type => $grp) - { - $template->assign_block_vars('groups', array( - 'MEMBERSHIP' => $lang["GROUP_MEMBER_{$type}"], - 'GROUP_SELECT' => build_group($grp), - )); - } + foreach ($groups as $type => $grp) { + $template->assign_block_vars('groups', [ + 'MEMBERSHIP' => $lang["GROUP_MEMBER_{$type}"], + 'GROUP_SELECT' => build_group($grp) + ]); + } - $template->assign_vars(array( - 'SELECT_GROUP' => true, - 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], - 'S_USERGROUP_ACTION' => 'group.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); - } - else - { - if(IS_ADMIN) - { - redirect('admin/admin_groups.php'); - } - else bb_die($lang['NO_GROUPS_EXIST']); - } -} -else if (isset($_POST['joingroup']) && $_POST['joingroup']) -{ - if ($group_info['group_type'] != GROUP_OPEN) - { - bb_die($lang['THIS_CLOSED_GROUP']); - } + $template->assign_vars([ + 'SELECT_GROUP' => true, + 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], + 'S_USERGROUP_ACTION' => 'group.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields + ]); + } else { + if (IS_ADMIN) { + redirect('admin/admin_groups.php'); + } else { + bb_die($lang['NO_GROUPS_EXIST']); + } + } +} elseif (isset($_POST['joingroup']) && $_POST['joingroup']) { + if ($group_info['group_type'] != GROUP_OPEN) { + bb_die($lang['THIS_CLOSED_GROUP']); + } - $sql = "SELECT g.group_id, g.group_name, ug.user_id, u.user_email, u.username, u.user_lang - FROM ". BB_GROUPS ." g - LEFT JOIN ". BB_USERS ." u ON(u.user_id = g.group_moderator) - LEFT JOIN ". BB_USER_GROUP ." ug ON(ug.group_id = g.group_id AND ug.user_id = {$userdata['user_id']}) + $sql = "SELECT g.group_id, g.group_name, ug.user_id, u.user_email, u.username, u.user_lang + FROM " . BB_GROUPS . " g + LEFT JOIN " . BB_USERS . " u ON(u.user_id = g.group_moderator) + LEFT JOIN " . BB_USER_GROUP . " ug ON(ug.group_id = g.group_id AND ug.user_id = {$userdata['user_id']}) WHERE g.group_id = $group_id AND group_single_user = 0 - AND g.group_type = ". GROUP_OPEN ." + AND g.group_type = " . GROUP_OPEN . " LIMIT 1"; - $row = $moderator = DB()->fetch_row($sql); + $row = $moderator = DB()->fetch_row($sql); - if (!$row['group_id']) - { - bb_die($lang['NO_GROUPS_EXIST']); - } - if ($row['user_id']) - { - set_die_append_msg(false, false, $group_id); - bb_die($lang['ALREADY_MEMBER_GROUP']); - } + if (!$row['group_id']) { + bb_die($lang['NO_GROUPS_EXIST']); + } + if ($row['user_id']) { + set_die_append_msg(group_id: $group_id); + bb_die($lang['ALREADY_MEMBER_GROUP']); + } - add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW); + \TorrentPier\Legacy\Group::add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW); - if ($bb_cfg['group_send_email']) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($bb_cfg['smtp_delivery']); + if (config()->get('group_send_email')) { + // Sending email + $emailer = new TorrentPier\Emailer(); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); - $emailer->email_address($moderator['username'] ." <{$moderator['user_email']}>"); + $emailer->set_to($moderator['user_email'], $moderator['username']); + $emailer->set_subject($lang['EMAILER_SUBJECT']['GROUP_REQUEST']); - $emailer->use_template('group_request', $moderator['user_lang']); + $emailer->set_template('group_request', $moderator['user_lang']); + $emailer->assign_vars([ + 'USER' => $userdata['username'], + 'GROUP_MODERATOR' => $moderator['username'], + 'U_GROUP' => make_url(GROUP_URL . $group_id) + ]); - $emailer->assign_vars(array( - 'USER' => $userdata['username'], - 'SITENAME' => $bb_cfg['sitename'], - 'GROUP_MODERATOR' => $moderator['username'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->send(); + } - $emailer->send(); - $emailer->reset(); - } + set_die_append_msg(group_id: $group_id); + bb_die($lang['GROUP_JOINED']); +} elseif (!empty($_POST['unsub']) || !empty($_POST['unsubpending'])) { + \TorrentPier\Legacy\Group::delete_user_group($group_id, $userdata['user_id']); - set_die_append_msg(false, false, $group_id); - bb_die($lang['GROUP_JOINED']); -} -else if (!empty($_POST['unsub']) || !empty($_POST['unsubpending'])) -{ - delete_user_group($group_id, $userdata['user_id']); + set_die_append_msg(group_id: $group_id); + bb_die($lang['UNSUB_SUCCESS']); +} else { + // Handle Additions, removals, approvals and denials + $group_moderator = $group_info['group_moderator']; - set_die_append_msg(false, false, $group_id); - bb_die($lang['UNSUB_SUCCESS']); -} -else -{ - // Handle Additions, removals, approvals and denials - $group_moderator = $group_info['group_moderator']; + if (!empty($_POST['add']) || !empty($_POST['remove']) || !empty($_POST['approve']) || !empty($_POST['deny'])) { + if (!$is_moderator) { + set_die_append_msg(group_id: $group_id); + bb_die($lang['NOT_GROUP_MODERATOR']); + } - if (!empty($_POST['add']) || !empty($_POST['remove']) || !empty($_POST['approve']) || !empty($_POST['deny'])) - { - if (!$is_moderator) - { - bb_die($lang['NOT_GROUP_MODERATOR']); - } + if (!empty($_POST['add'])) { + if (isset($_POST['username']) && !($row = get_userdata($_POST['username'], true))) { + set_die_append_msg(group_id: $group_id); + bb_die($lang['COULD_NOT_ADD_USER']); + } - if (!empty($_POST['add'])) - { - if (isset($_POST['username']) && !($row = get_userdata($_POST['username'], true))) - { - bb_die($lang['COULD_NOT_ADD_USER']); - } + // Prevent adding moderator + if ($row['user_id'] == $group_moderator) { + set_die_append_msg(group_id: $group_id); + bb_die(sprintf($lang['USER_IS_MOD_GROUP'], profile_url($row))); + } - add_user_into_group($group_id, $row['user_id']); + // Prevent infinity user adding into group + if ($is_member = DB()->fetch_row("SELECT user_id FROM " . BB_USER_GROUP . " WHERE group_id = $group_id AND user_id = " . $row['user_id'] . " LIMIT 1")) { + if ($is_member['user_id']) { + set_die_append_msg(group_id: $group_id); + bb_die(sprintf($lang['USER_IS_MEMBER_GROUP'], profile_url($row))); + } + } - if ($bb_cfg['group_send_email']) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($bb_cfg['smtp_delivery']); + \TorrentPier\Legacy\Group::add_user_into_group($group_id, $row['user_id']); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); + if (config()->get('group_send_email')) { + // Sending email + $emailer = new TorrentPier\Emailer(); - $emailer->use_template('group_added', $row['user_lang']); + $emailer->set_to($row['user_email'], $row['username']); + $emailer->set_subject($lang['EMAILER_SUBJECT']['GROUP_ADDED']); - $emailer->assign_vars(array( - 'SITENAME' => $bb_cfg['sitename'], - 'GROUP_NAME' => $group_info['group_name'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->set_template('group_added', $row['user_lang']); + $emailer->assign_vars([ + 'GROUP_NAME' => $group_info['group_name'], + 'U_GROUP' => make_url(GROUP_URL . $group_id) + ]); - $emailer->send(); - $emailer->reset(); - } - } - else - { - if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members']))) - { - $members = (!empty($_POST['approve']) || !empty($_POST['deny'])) ? $_POST['pending_members'] : $_POST['members']; + $emailer->send(); + } + } else { + if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members']))) { + $members = (!empty($_POST['approve']) || !empty($_POST['deny'])) ? $_POST['pending_members'] : $_POST['members']; - $sql_in = array(); - foreach ($members as $members_id) - { - $sql_in[] = (int) $members_id; - } - if (!$sql_in = join(',', $sql_in)) - { - bb_die($lang['NONE_SELECTED']); - } + $sql_in = []; + foreach ($members as $members_id) { + $sql_in[] = (int)$members_id; + } + if (!$sql_in = implode(',', $sql_in)) { + set_die_append_msg(group_id: $group_id); + bb_die($lang['NONE_SELECTED']); + } - if (!empty($_POST['approve'])) - { - DB()->query(" - UPDATE ". BB_USER_GROUP ." SET + if (!empty($_POST['approve'])) { + DB()->query(" + UPDATE " . BB_USER_GROUP . " SET user_pending = 0 WHERE user_id IN($sql_in) AND group_id = $group_id "); - update_user_level($sql_in); - } - else if (!empty($_POST['deny']) || !empty($_POST['remove'])) - { - DB()->query(" - DELETE FROM ". BB_USER_GROUP ." + \TorrentPier\Legacy\Group::update_user_level($sql_in); + } elseif (!empty($_POST['deny']) || !empty($_POST['remove'])) { + DB()->query(" + DELETE FROM " . BB_USER_GROUP . " WHERE user_id IN($sql_in) AND group_id = $group_id "); - if (!empty($_POST['remove'])) - { - update_user_level($sql_in); - } - } - // Email users when they are approved - if (!empty($_POST['approve']) && $bb_cfg['group_send_email']) - { - $sql_select = "SELECT username, user_email, user_lang - FROM ". BB_USERS ." - WHERE user_id IN($sql_in)"; + if (!empty($_POST['remove'])) { + \TorrentPier\Legacy\Group::update_user_level($sql_in); + } + } + // Email users when they are approved + if (!empty($_POST['approve']) && config()->get('group_send_email')) { + $sql_select = "SELECT username, user_email, user_lang + FROM " . BB_USERS . " + WHERE user_id IN($sql_in)"; - if (!$result = DB()->sql_query($sql_select)) - { - bb_die('Could not get user email information'); - } + if (!$result = DB()->sql_query($sql_select)) { + bb_die('Could not get user email information'); + } - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($bb_cfg['smtp_delivery']); + foreach (DB()->fetch_rowset($sql_select) as $row) { + // Sending email + $emailer = new TorrentPier\Emailer(); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); + $emailer->set_to($row['user_email'], $row['username']); + $emailer->set_subject($lang['EMAILER_SUBJECT']['GROUP_APPROVED']); - foreach (DB()->fetch_rowset($sql_select) as $row) - { - $emailer->use_template('group_approved', $row['user_lang']); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); - } + $emailer->set_template('group_approved', $row['user_lang']); + $emailer->assign_vars([ + 'GROUP_NAME' => $group_info['group_name'], + 'U_GROUP' => make_url(GROUP_URL . $group_id) + ]); - $emailer->assign_vars(array( - 'SITENAME' => $bb_cfg['sitename'], - 'GROUP_NAME' => $group_info['group_name'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->send(); + } + } + } + } + } + // END approve or deny - $emailer->send(); - $emailer->reset(); - } - } - } - } - // END approve or deny - - // Get moderator details for this group - $group_moderator = DB()->fetch_row(" + // Get moderator details for this group + $group_moderator = DB()->fetch_row(" SELECT * - FROM ". BB_USERS ." - WHERE user_id = ". $group_info['group_moderator'] ." + FROM " . BB_USERS . " + WHERE user_id = " . $group_info['group_moderator'] . " "); - // Current user membership - $is_group_member = $is_group_pending_member = false; + // Current user membership + $is_group_member = $is_group_pending_member = false; - $sql = "SELECT user_pending - FROM ". BB_USER_GROUP ." + $sql = "SELECT user_pending + FROM " . BB_USER_GROUP . " WHERE group_id = $group_id - AND user_id = ". $userdata['user_id'] ." + AND user_id = " . $userdata['user_id'] . " LIMIT 1"; - if ($row = DB()->fetch_row($sql)) - { - if ($row['user_pending'] == 0) - { - $is_group_member = true; - } - else - { - $is_group_pending_member = true; - } - } + if ($row = DB()->fetch_row($sql)) { + if ($row['user_pending'] == 0) { + $is_group_member = true; + } else { + $is_group_pending_member = true; + } + } - if ($userdata['user_id'] == $group_moderator['user_id']) - { - $group_details = $lang['ARE_GROUP_MODERATOR']; - $s_hidden_fields = ''; - } - else if ($is_group_member || $is_group_pending_member) - { - $template->assign_vars(array( - 'SHOW_UNSUBSCRIBE_CONTROLS' => true, - 'CONTROL_NAME' => ($is_group_member) ? 'unsub' : 'unsubpending', - )); - $group_details = ($is_group_pending_member) ? $lang['PENDING_THIS_GROUP'] : $lang['MEMBER_THIS_GROUP']; - $s_hidden_fields = ''; - } - else if (IS_GUEST) - { - $group_details = $lang['LOGIN_TO_JOIN']; - $s_hidden_fields = ''; - } - else - { - if ($group_info['group_type'] == GROUP_OPEN) - { - $template->assign_var('SHOW_SUBSCRIBE_CONTROLS'); + if ($userdata['user_id'] == $group_moderator['user_id']) { + $group_details = $lang['ARE_GROUP_MODERATOR']; + $s_hidden_fields = ''; + } elseif ($is_group_member || $is_group_pending_member) { + $template->assign_vars([ + 'SHOW_UNSUBSCRIBE_CONTROLS' => true, + 'CONTROL_NAME' => ($is_group_member) ? 'unsub' : 'unsubpending', + ]); + $group_details = ($is_group_pending_member) ? $lang['PENDING_THIS_GROUP'] : $lang['MEMBER_THIS_GROUP']; + $s_hidden_fields = ''; + } elseif (IS_GUEST) { + $group_details = $lang['LOGIN_TO_JOIN']; + $s_hidden_fields = ''; + } else { + if ($group_info['group_type'] == GROUP_OPEN) { + $template->assign_var('SHOW_SUBSCRIBE_CONTROLS'); - $group_details = $lang['THIS_OPEN_GROUP']; - $s_hidden_fields = ''; - } - else if ($group_info['group_type'] == GROUP_CLOSED) - { - $group_details = $lang['THIS_CLOSED_GROUP']; - $s_hidden_fields = ''; - } - else if ($group_info['group_type'] == GROUP_HIDDEN) - { - $group_details = $lang['THIS_HIDDEN_GROUP']; - $s_hidden_fields = ''; - } - } + $group_details = $lang['THIS_OPEN_GROUP']; + $s_hidden_fields = ''; + } elseif ($group_info['group_type'] == GROUP_CLOSED) { + $group_details = $lang['THIS_CLOSED_GROUP']; + $s_hidden_fields = ''; + } elseif ($group_info['group_type'] == GROUP_HIDDEN) { + $group_details = $lang['THIS_HIDDEN_GROUP']; + $s_hidden_fields = ''; + } + } - // Add the moderator - $username = $group_moderator['username']; - $user_id = $group_moderator['user_id']; + // Add the moderator + $username = $group_moderator['username']; + $user_id = $group_moderator['user_id']; - generate_user_info($group_moderator, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + $moderator_info = generate_user_info($group_moderator, $is_moderator); - $group_type = ''; - if ($group_info['group_type'] == GROUP_OPEN) - { - $group_type = $lang['GROUP_OPEN']; - } - elseif ($group_info['group_type'] == GROUP_CLOSED) - { - $group_type = $lang['GROUP_CLOSED']; - } - elseif ($group_info['group_type'] == GROUP_HIDDEN) - { - $group_type = $lang['GROUP_HIDDEN']; - } + $group_type = ''; + if ($group_info['group_type'] == GROUP_OPEN) { + $group_type = $lang['GROUP_OPEN']; + } elseif ($group_info['group_type'] == GROUP_CLOSED) { + $group_type = $lang['GROUP_CLOSED']; + } elseif ($group_info['group_type'] == GROUP_HIDDEN) { + $group_type = $lang['GROUP_HIDDEN']; + } - $i = 0; - $template->assign_vars(array( - 'ROW_NUMBER' => $i + ($start + 1), - 'GROUP_INFO' => true, - 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], - 'GROUP_NAME' => htmlCHR($group_info['group_name']), - 'GROUP_DESCRIPTION' => bbcode2html($group_info['group_description']), - 'GROUP_SIGNATURE' => bbcode2html($group_info['group_signature']), - 'GROUP_AVATAR' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id'], true), - 'GROUP_DETAILS' => $group_details, - 'GROUP_TIME' => (!empty($group_info['group_time'])) ? sprintf('%s (%s)', bb_date($group_info['group_time']), delta_time($group_info['group_time'])) : $lang['NONE'], - 'MOD_USER' => profile_url($group_moderator), - 'MOD_AVATAR' => $avatar, - 'MOD_FROM' => $from, - 'MOD_JOINED' => $joined, - 'MOD_POSTS' => $posts, - 'MOD_PM' => $pm, - 'MOD_EMAIL' => $email, - 'MOD_WWW' => $www, - 'MOD_TIME' => (!empty($group_info['mod_time'])) ? bb_date($group_info['mod_time']) : $lang['NONE'], - 'U_SEARCH_USER' => "search.php?mode=searchuser", - 'U_SEARCH_RELEASES' => "tracker.php?srg=$group_id", - 'U_GROUP_RELEASES' => "group.php?view=releases&". POST_GROUPS_URL ."=$group_id", - 'U_GROUP_MEMBERS' => "group.php?view=members&". POST_GROUPS_URL ."=$group_id", - 'U_GROUP_CONFIG' => "group_edit.php?g=$group_id", - 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, - 'GROUP_TYPE' => $group_type, + $i = 0; + $template->assign_vars([ + 'ROW_NUMBER' => $i + ($start + 1), + 'GROUP_INFO' => true, + 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], + 'GROUP_NAME' => htmlCHR($group_info['group_name']), + 'GROUP_DESCRIPTION' => bbcode2html($group_info['group_description']), + 'GROUP_SIGNATURE' => bbcode2html($group_info['group_signature']), + 'GROUP_AVATAR' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']), + 'GROUP_DETAILS' => $group_details, + 'GROUP_TIME' => !empty($group_info['group_time']) ? sprintf('%s (%s)', bb_date($group_info['group_time']), delta_time($group_info['group_time'])) : $lang['NONE'], + 'MOD_USER' => profile_url($group_moderator), + 'MOD_AVATAR' => $moderator_info['avatar'], + 'MOD_FROM' => $moderator_info['from'], + 'MOD_JOINED' => $moderator_info['joined'], + 'MOD_JOINED_RAW' => $moderator_info['joined_raw'], + 'MOD_POSTS' => $moderator_info['posts'], + 'MOD_PM' => $moderator_info['pm'], + 'MOD_EMAIL' => $moderator_info['email'], + 'MOD_WWW' => $moderator_info['www'], + 'MOD_TIME' => !empty($group_info['mod_time']) ? sprintf('%s (%s)', bb_date($group_info['mod_time']), delta_time($group_info['mod_time'])) : $lang['NONE'], + 'MOD_TIME_RAW' => !empty($group_info['mod_time']) ? $group_info['mod_time'] : '', + 'U_SEARCH_USER' => 'search.php?mode=searchuser', + 'U_SEARCH_RELEASES' => "tracker.php?srg=$group_id", + 'U_GROUP_RELEASES' => GROUP_URL . $group_id . "&view=releases", + 'U_GROUP_MEMBERS' => GROUP_URL . $group_id . "&view=members", + 'U_GROUP_CONFIG' => "group_edit.php?" . POST_GROUPS_URL . "=$group_id", + 'RELEASE_GROUP' => (bool)$group_info['release_group'], + 'GROUP_TYPE' => $group_type, - 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, - 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, - 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, - 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked="checked"' : '', - 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked="checked"' : '', - 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked="checked"' : '', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, + 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, + 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, + 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, + 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked' : '', + 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked' : '', + 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked' : '', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, - 'S_GROUP_ACTION' => "group.php?" . POST_GROUPS_URL . "=$group_id", - )); + 'S_GROUP_ACTION' => GROUP_URL . $group_id, + ]); - switch ($view_mode) - { - case 'releases': - // TODO Correct SQL to posts with attach and limit them, optimization + switch ($view_mode) { + case 'releases': + // TODO Correct SQL to posts with attach and limit them, optimization - if (!$group_info['release_group']) - { - set_die_append_msg(false, false, $group_id); - bb_die($lang['NOT_A_RELEASE_GROUP']); - } + if (!$group_info['release_group']) { + set_die_append_msg(group_id: $group_id); + bb_die($lang['NOT_A_RELEASE_GROUP']); + } - // Count releases for pagination - $all_releases = DB()->fetch_rowset(" + // Count releases for pagination + $all_releases = DB()->fetch_rowset(" SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank - FROM ". BB_POSTS ." p - LEFT JOIN ". BB_TOPICS ." t ON(p.topic_id = t.topic_id) - LEFT JOIN ". BB_FORUMS ." f ON(p.forum_id= f.forum_id) - LEFT JOIN ". BB_USERS ." u ON(p.poster_id = u.user_id) + FROM " . BB_POSTS . " p + LEFT JOIN " . BB_TOPICS . " t ON(p.topic_id = t.topic_id) + LEFT JOIN " . BB_FORUMS . " f ON(p.forum_id= f.forum_id) + LEFT JOIN " . BB_USERS . " u ON(p.poster_id = u.user_id) WHERE p.poster_rg_id = $group_id ORDER BY t.topic_time DESC LIMIT $rel_limit "); - $count_releases = count($all_releases); + $count_releases = count($all_releases); - generate_pagination(GROUP_URL . $group_id ."&view=releases", $count_releases, $per_page, $start); + generate_pagination(GROUP_URL . $group_id . "&view=releases", $count_releases, $per_page, $start); - $sql = " + $sql = " SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank - FROM ". BB_POSTS ." p - LEFT JOIN ". BB_TOPICS ." t ON(p.topic_id = t.topic_id) - LEFT JOIN ". BB_FORUMS ." f ON(p.forum_id= f.forum_id) - LEFT JOIN ". BB_USERS ." u ON(p.poster_id = u.user_id) + FROM " . BB_POSTS . " p + LEFT JOIN " . BB_TOPICS . " t ON(p.topic_id = t.topic_id) + LEFT JOIN " . BB_FORUMS . " f ON(p.forum_id= f.forum_id) + LEFT JOIN " . BB_USERS . " u ON(p.poster_id = u.user_id) WHERE p.poster_rg_id = $group_id ORDER BY t.topic_time DESC LIMIT $start, $per_page "; - if (!$releases = DB()->fetch_rowset($sql)) - { - set_die_append_msg(false, false, $group_id); - bb_die($lang['NO_SEARCH_MATCH']); - } + if (!$releases = DB()->fetch_rowset($sql)) { + set_die_append_msg(group_id: $group_id); + bb_die($lang['NO_SEARCH_MATCH']); + } - foreach ($releases as $i => $release) - { - $row_class = !($i % 2) ? 'row1' : 'row2'; + foreach ($releases as $i => $release) { + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('releases', array( - 'ROW_NUMBER' => $i + ( $start + 1 ), - 'ROW_CLASS' => $row_class, - 'RELEASER' => profile_url(array('user_id' => $release['poster_id'], 'username' => $release['username'], 'user_rank' => $release['user_rank'])), - 'AVATAR_IMG' => get_avatar($release['poster_id'], $release['avatar_ext_id'], !bf($release['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50), - 'RELEASE_NAME' => sprintf('%s', TOPIC_URL . $release['topic_id'], htmlCHR($release['topic_title'])), - 'RELEASE_TIME' => bb_date($release['topic_time']), - 'RELEASE_FORUM' => sprintf('%s', FORUM_URL . $release['forum_id'], htmlCHR($release['forum_name'])), - )); - } + $template->assign_block_vars('releases', [ + 'ROW_NUMBER' => $i + ($start + 1), + 'ROW_CLASS' => $row_class, + 'RELEASER' => profile_url(['user_id' => $release['poster_id'], 'username' => $release['username'], 'user_rank' => $release['user_rank']]), + 'AVATAR_IMG' => get_avatar($release['poster_id'], $release['avatar_ext_id'], !bf($release['user_opt'], 'user_opt', 'dis_avatar'), 50, 50), + 'RELEASE_NAME' => sprintf('%s', TOPIC_URL . $release['topic_id'], htmlCHR($release['topic_title'])), + 'RELEASE_TIME' => bb_date($release['topic_time']), + 'RELEASE_FORUM' => sprintf('%s', FORUM_URL . $release['forum_id'], htmlCHR($release['forum_name'])), + ]); + } - $template->assign_vars(array( - 'RELEASES' => true, - )); + $template->assign_vars(['RELEASES' => true]); - break; + break; - case 'members': - default: + case 'members': + default: - // Members - $count_members = DB()->fetch_rowset(" + // Members + $count_members = DB()->fetch_rowset(" SELECT u.username, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time - FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u + FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u WHERE ug.group_id = $group_id AND ug.user_pending = 0 - AND ug.user_id <> ". $group_moderator['user_id'] ." + AND ug.user_id <> " . $group_moderator['user_id'] . " AND u.user_id = ug.user_id ORDER BY u.username "); - $count_members = count($count_members); + $count_members = count($count_members); - // Get user information for this group - $modgroup_pending_count = 0; + // Get user information for this group + $modgroup_pending_count = 0; - // Members - $group_members = DB()->fetch_rowset(" + // Members + $group_members = DB()->fetch_rowset(" SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time - FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u + FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u WHERE ug.group_id = $group_id AND ug.user_pending = 0 - AND ug.user_id <> ". $group_moderator['user_id'] ." + AND ug.user_id <> " . $group_moderator['user_id'] . " AND u.user_id = ug.user_id ORDER BY u.username LIMIT $start, $per_page "); - $members_count = count($group_members); + $members_count = count($group_members); - generate_pagination(GROUP_URL . $group_id, $count_members, $per_page, $start); + generate_pagination(GROUP_URL . $group_id, $count_members, $per_page, $start); - // Dump out the remaining users - foreach ($group_members as $i => $member) - { - $user_id = $member['user_id']; + // Dump out the remaining users + foreach ($group_members as $i => $member) { + $user_id = $member['user_id']; - generate_user_info($member, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + $member_info = generate_user_info($member, $is_moderator); - if ($group_info['group_type'] != GROUP_HIDDEN || $is_group_member || $is_moderator) - { - $row_class = !($i % 2) ? 'row1' : 'row2'; + if ($group_info['group_type'] != GROUP_HIDDEN || $is_group_member || $is_moderator) { + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('member', array( - 'ROW_NUMBER' => $i + ( $start + 1 ), - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($member), - 'AVATAR_IMG' => $avatar, - 'FROM' => $from, - 'JOINED' => $joined, - 'POSTS' => $posts, - 'USER_ID' => $user_id, - 'PM' => $pm, - 'EMAIL' => $email, - 'WWW' => $www, - 'TIME' => $user_time, - )); + $template->assign_block_vars('member', [ + 'ROW_NUMBER' => $i + ($start + 1), + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($member), + 'AVATAR_IMG' => $member_info['avatar'], + 'FROM' => $member_info['from'], + 'JOINED' => $member_info['joined'], + 'JOINED_RAW' => $member_info['joined_raw'], + 'POSTS' => $member_info['posts'], + 'USER_ID' => $user_id, + 'PM' => $member_info['pm'], + 'EMAIL' => $member_info['email'], + 'WWW' => $member_info['www'], + 'TIME' => $member_info['user_time'], + 'TIME_RAW' => $member_info['user_time_raw'] + ]); - if ($is_moderator) - { - $template->assign_block_vars('member.switch_mod_option', array()); - } - } - } + if ($is_moderator) { + $template->assign_block_vars('member.switch_mod_option', []); + } + } + } - // No group members - if (!$members_count) - { - $template->assign_block_vars('switch_no_members', array()); - } + // No group members + if (!$members_count) { + $template->assign_block_vars('switch_no_members', []); + } - // No group members - if ($group_info['group_type'] == GROUP_HIDDEN && !$is_group_member && !$is_moderator) - { - $template->assign_block_vars('switch_hidden_group', array()); - } + // No group members + if ($group_info['group_type'] == GROUP_HIDDEN && !$is_group_member && !$is_moderator) { + $template->assign_block_vars('switch_hidden_group', []); + } - // Pending - if ($is_moderator) - { - $modgroup_pending_list = DB()->fetch_rowset(" + // Pending + if ($is_moderator) { + $modgroup_pending_list = DB()->fetch_rowset(" SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email - FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u + FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u WHERE ug.group_id = $group_id AND ug.user_pending = 1 AND u.user_id = ug.user_id ORDER BY u.username LIMIT 200 "); - $modgroup_pending_count = count($modgroup_pending_list); - } + $modgroup_pending_count = count($modgroup_pending_list); + } - if ($is_moderator && $modgroup_pending_list) - { - foreach ($modgroup_pending_list as $i => $member) - { - $user_id = $member['user_id']; + if ($is_moderator && $modgroup_pending_list) { + foreach ($modgroup_pending_list as $i => $member) { + $user_id = $member['user_id']; - generate_user_info($member, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + $pending_info = generate_user_info($member, $is_moderator); - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $user_select = ''; + $user_select = ''; - $template->assign_block_vars('pending', array( - 'ROW_CLASS' => $row_class, - 'AVATAR_IMG'=> $avatar, - 'USER' => profile_url($member), - 'FROM' => $from, - 'JOINED' => $joined, - 'POSTS' => $posts, - 'USER_ID' => $user_id, - 'PM' => $pm, - 'EMAIL' => $email, - )); - } + $template->assign_block_vars('pending', [ + 'ROW_CLASS' => $row_class, + 'AVATAR_IMG' => $pending_info['avatar'], + 'USER' => profile_url($member), + 'FROM' => $pending_info['from'], + 'JOINED' => $pending_info['joined'], + 'JOINED_RAW' => $pending_info['joined_raw'], + 'POSTS' => $pending_info['posts'], + 'USER_ID' => $user_id, + 'PM' => $pending_info['pm'], + 'EMAIL' => $pending_info['email'], + 'WWW' => $pending_info['www'] + ]); + } - $template->assign_vars(array( - 'PENDING_USERS' => true, - )); - } + $template->assign_vars(['PENDING_USERS' => true]); + } - $template->assign_vars(array('MEMBERS' => true)); - } + $template->assign_vars(['MEMBERS' => true]); + } - if ($is_moderator) - { - $template->assign_block_vars('switch_mod_option', array()); - $template->assign_block_vars('switch_add_member', array()); - } + if ($is_moderator) { + $template->assign_block_vars('switch_mod_option', []); + $template->assign_block_vars('switch_add_member', []); + } } -print_page('group.tpl'); \ No newline at end of file +print_page('group.tpl'); diff --git a/group_edit.php b/group_edit.php index 801e62f69..041365bf4 100644 --- a/group_edit.php +++ b/group_edit.php @@ -1,114 +1,98 @@ session_start(array('req_login' => true)); +$user->session_start(['req_login' => true]); -$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : null; -$group_info = array(); +$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? (int)$_REQUEST[POST_GROUPS_URL] : null; +$group_info = []; $is_moderator = false; $submit = !empty($_POST['submit']); -if ($group_id) -{ - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } - if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) - { - bb_die("Invalid group data [group_id: $group_id]"); - } - $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); +if ($group_id) { + if (!$group_info = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) { + bb_die("Invalid group data [group_id: $group_id]"); + } + $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); } -if ($is_moderator) -{ - // TODO Admin panel, some tasty features +if ($is_moderator) { + // Avatar + if ($submit) { + if (!empty($_FILES['avatar']['name']) && config()->get('group_avatars.up_allowed')) { + $upload = new TorrentPier\Legacy\Common\Upload(); - // Avatar - if ($submit) - { - if (!empty($_FILES['avatar']['name']) && $bb_cfg['group_avatars']['up_allowed']) - { - require(INC_DIR .'functions_upload.php'); - $upload = new upload_common(); + if ($upload->init(config()->get('group_avatars'), $_FILES['avatar']) and $upload->store('avatar', ['user_id' => GROUP_AVATAR_MASK . $group_id, 'avatar_ext_id' => $group_info['avatar_ext_id']])) { + $avatar_ext_id = (int)$upload->file_ext_id; + DB()->query("UPDATE " . BB_GROUPS . " SET avatar_ext_id = $avatar_ext_id WHERE group_id = $group_id LIMIT 1"); + } else { + bb_die(implode($upload->errors)); + } + } + } - if ($upload->init($bb_cfg['group_avatars'], $_FILES['avatar']) AND $upload->store('avatar', array("user_id" => GROUP_AVATAR_MASK . $group_id, "avatar_ext_id" => $group_info['avatar_ext_id']))) - { - $avatar_ext_id = (int) $upload->file_ext_id; - } - else - { - bb_die(implode($upload->errors)); - } + $group_type = ''; + if ($group_info['group_type'] == GROUP_OPEN) { + $group_type = $lang['GROUP_OPEN']; + } elseif ($group_info['group_type'] == GROUP_CLOSED) { + $group_type = $lang['GROUP_CLOSED']; + } elseif ($group_info['group_type'] == GROUP_HIDDEN) { + $group_type = $lang['GROUP_HIDDEN']; + } - DB()->query("UPDATE ". BB_GROUPS ." SET avatar_ext_id = $avatar_ext_id WHERE group_id = $group_id LIMIT 1"); - } - } + $s_hidden_fields = ''; - $group_type = ''; - if ($group_info['group_type'] == GROUP_OPEN) - { - $group_type = $lang['GROUP_OPEN']; - } - elseif ($group_info['group_type'] == GROUP_CLOSED) - { - $group_type = $lang['GROUP_CLOSED']; - } - elseif ($group_info['group_type'] == GROUP_HIDDEN) - { - $group_type = $lang['GROUP_HIDDEN']; - } + $template->assign_vars([ + 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], + 'GROUP_NAME' => htmlCHR($group_info['group_name']), + 'GROUP_ID' => $group_id, + 'GROUP_DESCRIPTION' => htmlCHR($group_info['group_description']), + 'GROUP_SIGNATURE' => htmlCHR($group_info['group_signature']), + 'U_GROUP_URL' => GROUP_URL . $group_id, + 'RELEASE_GROUP' => (bool)$group_info['release_group'], + 'GROUP_TYPE' => $group_type, + 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, + 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, + 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, + 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked' : '', + 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked' : '', + 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked' : '', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_GROUP_CONFIG_ACTION' => "group_edit.php?" . POST_GROUPS_URL . "=$group_id", - $s_hidden_fields = ''; + 'AVATAR_EXPLAIN' => sprintf($lang['AVATAR_EXPLAIN'], config()->get('group_avatars.max_width'), config()->get('group_avatars.max_height'), humn_size(config()->get('group_avatars.max_size'))), + 'AVATAR_IMG' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']), + ]); - $template->assign_vars(array( - 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], - 'GROUP_NAME' => htmlCHR($group_info['group_name']), - 'GROUP_ID' => $group_id, - 'GROUP_DESCRIPTION' => htmlCHR($group_info['group_description']), - 'GROUP_SIGNATURE' => htmlCHR($group_info['group_signature']), - 'U_GROUP_URL' => GROUP_URL . $group_id, - 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, - 'GROUP_TYPE' => $group_type, - 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, - 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, - 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, - 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked="checked"' : '', - 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked="checked"' : '', - 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked="checked"' : '', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_GROUP_CONFIG_ACTION' => "group_edit.php?" . POST_GROUPS_URL . "=$group_id", + $template->set_filenames(['body' => 'group_edit.tpl']); + $template->assign_vars(['PAGE_TITLE' => $lang['GROUP_CONFIGURATION']]); - 'AVATAR_EXPLAIN' => sprintf($lang['AVATAR_EXPLAIN'], $bb_cfg['group_avatars']['max_width'], $bb_cfg['group_avatars']['max_height'], (round($bb_cfg['group_avatars']['max_size'] / 1024))), - 'AVATAR_IMG' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']), - )); + require(PAGE_HEADER); - $template->set_filenames(array('body' => 'group_edit.tpl')); - $template->assign_vars(array('PAGE_TITLE' => $lang['GROUP_CONFIGURATION'])); + $template->pparse('body'); - require(PAGE_HEADER); + require(PAGE_FOOTER); +} else { + $redirect = 'index.php'; - $template->pparse('body'); - - require(PAGE_FOOTER); + if ($group_id) { + $redirect = GROUP_URL . $group_id; + } + redirect($redirect); } -else -{ - $redirect = 'index.php'; - - if ($group_id) - { - $redirect = GROUP_URL . $group_id; - } - redirect($redirect); -} \ No newline at end of file diff --git a/index.php b/index.php index 7dc7b44a9..2cf22e305 100644 --- a/index.php +++ b/index.php @@ -1,201 +1,201 @@ enqueue(array( - 'stats', - 'moderators', -)); -if ($bb_cfg['show_latest_news']) -{ - $datastore->enqueue('latest_news'); +// Show online stats +$show_online_users = true; + +// Show subforums +$show_subforums = true; + +$datastore->enqueue([ + 'stats', + 'moderators', + 'cat_forums' +]); + +if (config()->get('show_latest_news')) { + $datastore->enqueue([ + 'latest_news' + ]); } -if ($bb_cfg['show_network_news']) -{ - $datastore->enqueue('network_news'); +if (config()->get('show_network_news')) { + $datastore->enqueue([ + 'network_news' + ]); } // Init userdata $user->session_start(); +// Set meta description +$page_cfg['meta_description'] = config()->get('site_desc'); + // Init main vars -$viewcat = isset($_GET['c']) ? (int) $_GET['c'] : 0; -$lastvisit = (IS_GUEST) ? TIMENOW : $userdata['user_lastvisit']; +$viewcat = isset($_GET[POST_CAT_URL]) ? (int)$_GET[POST_CAT_URL] : 0; +$lastvisit = IS_GUEST ? TIMENOW : $userdata['user_lastvisit']; // Caching output $req_page = 'index_page'; -$req_page .= ($viewcat) ? "_c{$viewcat}" : ''; +$req_page .= $viewcat ? "_c{$viewcat}" : ''; define('REQUESTED_PAGE', $req_page); -caching_output(IS_GUEST, 'send', REQUESTED_PAGE .'_guest_'. $bb_cfg['default_lang']); +caching_output(IS_GUEST, 'send', REQUESTED_PAGE . '_guest_' . config()->get('default_lang')); -$hide_cat_opt = isset($user->opt_js['h_cat']) ? (string) $user->opt_js['h_cat'] : 0; +$hide_cat_opt = isset($user->opt_js['h_cat']) ? (string)$user->opt_js['h_cat'] : 0; $hide_cat_user = array_flip(explode('-', $hide_cat_opt)); -$showhide = isset($_GET['sh']) ? (int) $_GET['sh'] : 0; +$showhide = isset($_GET['sh']) ? (int)$_GET['sh'] : 0; // Topics read tracks $tracking_topics = get_tracks('topic'); $tracking_forums = get_tracks('forum'); // Statistics -if (!$stats = $datastore->get('stats')) -{ - $datastore->update('stats'); - $stats = $datastore->get('stats'); +$stats = $datastore->get('stats'); +if ($stats === false) { + $datastore->update('stats'); + $stats = $datastore->get('stats'); } // Forums data -if (!$forums = $datastore->get('cat_forums')) -{ - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); +$forums = $datastore->get('cat_forums'); +if ($forums === false) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); } $cat_title_html = $forums['cat_title_html']; $forum_name_html = $forums['forum_name_html']; $anon = GUEST_UID; $excluded_forums_csv = $user->get_excluded_forums(AUTH_VIEW); +$excluded_forums_array = $excluded_forums_csv ? explode(',', $excluded_forums_csv) : []; $only_new = $user->opt_js['only_new']; // Validate requested category id -if ($viewcat AND !$viewcat =& $forums['c'][$viewcat]['cat_id']) -{ - redirect("index.php"); +if ($viewcat && !($viewcat =& $forums['c'][$viewcat]['cat_id'])) { + redirect('index.php'); } // Forums $forums_join_sql = 'f.cat_id = c.cat_id'; -$forums_join_sql .= ($viewcat) ? " +$forums_join_sql .= $viewcat ? " AND f.cat_id = $viewcat " : ''; -$forums_join_sql .= ($excluded_forums_csv) ? " +$forums_join_sql .= $excluded_forums_csv ? " AND f.forum_id NOT IN($excluded_forums_csv) AND f.forum_parent NOT IN($excluded_forums_csv) " : ''; // Posts -$posts_join_sql = "p.post_id = f.forum_last_post_id"; +$posts_join_sql = 'p.post_id = f.forum_last_post_id'; $posts_join_sql .= ($only_new == ONLY_NEW_POSTS) ? " AND p.post_time > $lastvisit " : ''; $join_p_type = ($only_new == ONLY_NEW_POSTS) ? 'INNER JOIN' : 'LEFT JOIN'; // Topics -$topics_join_sql = "t.topic_last_post_id = p.post_id"; +$topics_join_sql = 't.topic_last_post_id = p.post_id'; $topics_join_sql .= ($only_new == ONLY_NEW_TOPICS) ? " AND t.topic_time > $lastvisit " : ''; $join_t_type = ($only_new == ONLY_NEW_TOPICS) ? 'INNER JOIN' : 'LEFT JOIN'; $sql = " - SELECT SQL_CACHE - f.cat_id, f.forum_id, f.forum_status, f.forum_parent, f.show_on_index, + SELECT f.cat_id, f.forum_id, f.forum_status, f.forum_parent, f.show_on_index, p.post_id AS last_post_id, p.post_time AS last_post_time, t.topic_id AS last_topic_id, t.topic_title AS last_topic_title, u.user_id AS last_post_user_id, u.user_rank AS last_post_user_rank, IF(p.poster_id = $anon, p.post_username, u.username) AS last_post_username - FROM ". BB_CATEGORIES ." c - INNER JOIN ". BB_FORUMS ." f ON($forums_join_sql) - $join_p_type ". BB_POSTS ." p ON($posts_join_sql) - $join_t_type ". BB_TOPICS ." t ON($topics_join_sql) - LEFT JOIN ". BB_USERS ." u ON(u.user_id = p.poster_id) + FROM " . BB_CATEGORIES . ' c + INNER JOIN ' . BB_FORUMS . " f ON($forums_join_sql) + $join_p_type " . BB_POSTS . " p ON($posts_join_sql) + $join_t_type " . BB_TOPICS . " t ON($topics_join_sql) + LEFT JOIN " . BB_USERS . ' u ON(u.user_id = p.poster_id) ORDER BY c.cat_order, f.forum_order -"; +'; -$replace_in_parent = array( - 'last_post_id', - 'last_post_time', - 'last_post_user_id', - 'last_post_username', - 'last_post_user_rank', - 'last_topic_title', - 'last_topic_id', -); +$replace_in_parent = [ + 'last_post_id', + 'last_post_time', + 'last_post_user_id', + 'last_post_username', + 'last_post_user_rank', + 'last_topic_title', + 'last_topic_id' +]; -$cache_name = 'index_sql_' . md5($sql); -if (!$cat_forums = CACHE('bb_cache')->get($cache_name)) -{ - $cat_forums = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - if (!$cat_id = $row['cat_id'] OR !$forum_id = $row['forum_id']) - { - continue; - } +$cache_name = 'index_sql_' . hash('xxh128', $sql); +if (!$cat_forums = CACHE('bb_cache')->get($cache_name)) { + $cat_forums = []; + foreach (DB()->fetch_rowset($sql) as $row) { + if (!($cat_id = $row['cat_id']) || !($forum_id = $row['forum_id'])) { + continue; + } - if ($parent_id = $row['forum_parent']) - { - if (!$parent =& $cat_forums[$cat_id]['f'][$parent_id]) - { - $parent = $forums['f'][$parent_id]; - $parent['last_post_time'] = 0; - } - if ($row['last_post_time'] > $parent['last_post_time']) - { - foreach ($replace_in_parent as $key) - { - $parent[$key] = $row[$key]; - } - } - if ($show_subforums && $row['show_on_index']) - { - $parent['last_sf_id'] = $forum_id; - } - else - { - continue; - } - } - else - { - $f =& $forums['f'][$forum_id]; - $row['forum_desc'] = $f['forum_desc']; - $row['forum_posts'] = $f['forum_posts']; - $row['forum_topics'] = $f['forum_topics']; - } - $cat_forums[$cat_id]['f'][$forum_id] = $row; - } - CACHE('bb_cache')->set($cache_name, $cat_forums, 180); - unset($row, $forums); - $datastore->rm('cat_forums'); + if ($parent_id = $row['forum_parent']) { + if (!$parent =& $cat_forums[$cat_id]['f'][$parent_id]) { + $parent = $forums['f'][$parent_id]; + $parent['last_post_time'] = 0; + } + if ($row['last_post_time'] > $parent['last_post_time']) { + foreach ($replace_in_parent as $key) { + $parent[$key] = $row[$key]; + } + } + if ($show_subforums && $row['show_on_index']) { + $parent['last_sf_id'] = $forum_id; + } else { + continue; + } + } else { + $f =& $forums['f'][$forum_id]; + $row['forum_desc'] = $f['forum_desc']; + $row['forum_posts'] = $f['forum_posts']; + $row['forum_topics'] = $f['forum_topics']; + } + $cat_forums[$cat_id]['f'][$forum_id] = $row; + } + CACHE('bb_cache')->set($cache_name, $cat_forums, 180); + unset($row, $forums); + $datastore->rm('cat_forums'); } // Obtain list of moderators -$moderators = array(); -if (!$mod = $datastore->get('moderators')) -{ - $datastore->update('moderators'); - $mod = $datastore->get('moderators'); +$moderators = []; +$mod = $datastore->get('moderators'); +if ($mod === false) { + $datastore->update('moderators'); + $mod = $datastore->get('moderators'); } -if (!empty($mod)) -{ - foreach ($mod['mod_users'] as $forum_id => $user_ids) - { - foreach ($user_ids as $user_id) - { - $moderators[$forum_id][] = ''. $mod['name_users'][$user_id] .''; - } - } - foreach ($mod['mod_groups'] as $forum_id => $group_ids) - { - foreach ($group_ids as $group_id) - { - $moderators[$forum_id][] = ''. $mod['name_groups'][$group_id] .''; - } - } +if (!empty($mod)) { + foreach ($mod['mod_users'] as $forum_id => $user_ids) { + foreach ($user_ids as $user_id) { + $moderators[$forum_id][] = '' . $mod['name_users'][$user_id] . ''; + } + } + foreach ($mod['mod_groups'] as $forum_id => $group_ids) { + foreach ($group_ids as $group_id) { + $moderators[$forum_id][] = '' . $mod['name_groups'][$group_id] . ''; + } + } } unset($mod); @@ -203,229 +203,232 @@ $datastore->rm('moderators'); // Build index page $forums_count = 0; -foreach ($cat_forums as $cid => $c) -{ - $template->assign_block_vars('h_c', array( - 'H_C_ID' => $cid, - 'H_C_TITLE' => $cat_title_html[$cid], - 'H_C_CHEKED' => in_array($cid, preg_split("/[-]+/", $hide_cat_opt)) ? 'checked' : '', - )); +foreach ($cat_forums as $cid => $c) { + $template->assign_block_vars('h_c', [ + 'H_C_ID' => $cid, + 'H_C_TITLE' => $cat_title_html[$cid], + 'H_C_CHEKED' => in_array($cid, preg_split('/[-]+/', $hide_cat_opt)) ? 'checked' : '', + ]); - $template->assign_vars(array( - 'H_C_AL_MESS' => ($hide_cat_opt && !$showhide) ? true : false, - )); + $template->assign_vars(['H_C_AL_MESS' => $hide_cat_opt && !$showhide]); - if (!$showhide && isset($hide_cat_user[$cid]) && !$viewcat) - { - continue; - } + if (!$showhide && isset($hide_cat_user[$cid]) && !$viewcat) { + continue; + } - $template->assign_block_vars('c', array( - 'CAT_ID' => $cid, - 'CAT_TITLE' => $cat_title_html[$cid], - 'U_VIEWCAT' => CAT_URL . $cid, - )); + $template->assign_block_vars('c', [ + 'CAT_ID' => $cid, + 'CAT_TITLE' => $cat_title_html[$cid], + 'U_VIEWCAT' => CAT_URL . $cid, + ]); - foreach ($c['f'] as $fid => $f) - { - if (!$fname_html =& $forum_name_html[$fid]) - { - continue; - } - $is_sf = $f['forum_parent']; + foreach ($c['f'] as $fid => $f) { + if (!$fname_html =& $forum_name_html[$fid]) { + continue; + } + $is_sf = $f['forum_parent']; - $forums_count++; - $new = is_unread($f['last_post_time'], $f['last_topic_id'], $f['forum_id']) ? '_new' : ''; - $folder_image = ($is_sf) ? $images["icon_minipost{$new}"] : $images["forum{$new}"]; + $forums_count++; + $new = is_unread($f['last_post_time'], $f['last_topic_id'], $f['forum_id']) ? '_new' : ''; + $folder_image = $is_sf ? $images["icon_minipost{$new}"] : $images["forum{$new}"]; - if ($f['forum_status'] == FORUM_LOCKED) - { - $folder_image = ($is_sf) ? $images['icon_minipost'] : $images['forum_locked']; - } + if ($f['forum_status'] == FORUM_LOCKED) { + $folder_image = $is_sf ? $images['icon_minipost'] : $images['forum_locked']; + } - if ($is_sf) - { - $template->assign_block_vars('c.f.sf', array( - 'SF_ID' => $fid, - 'SF_NAME' => $fname_html, - 'SF_NEW' => $new ? ' new' : '', - )); - continue; - } + if ($is_sf) { + $template->assign_block_vars('c.f.sf', [ + 'SF_ID' => $fid, + 'SF_NAME' => $fname_html, + 'SF_NEW' => $new ? ' new' : '' + ]); + continue; + } - $template->assign_block_vars('c.f', array( - 'FORUM_FOLDER_IMG' => $folder_image, - 'FORUM_ID' => $fid, - 'FORUM_NAME' => $fname_html, - 'FORUM_DESC' => $f['forum_desc'], - 'POSTS' => commify($f['forum_posts']), - 'TOPICS' => commify($f['forum_topics']), - 'LAST_SF_ID' => isset($f['last_sf_id']) ? $f['last_sf_id'] : null, - 'MODERATORS' => isset($moderators[$fid]) ? join(', ', $moderators[$fid]) : '', - 'FORUM_FOLDER_ALT' => ($new) ? $lang['NEW'] : $lang['OLD'], - )); + $template->assign_block_vars('c.f', [ + 'FORUM_FOLDER_IMG' => $folder_image, + 'FORUM_ID' => $fid, + 'FORUM_NAME' => $fname_html, + 'FORUM_DESC' => $f['forum_desc'], + 'POSTS' => commify($f['forum_posts']), + 'TOPICS' => commify($f['forum_topics']), + 'LAST_SF_ID' => $f['last_sf_id'] ?? null, + 'MODERATORS' => isset($moderators[$fid]) ? implode(', ', $moderators[$fid]) : '', + 'FORUM_FOLDER_ALT' => $new ? $lang['NEW'] : $lang['OLD'] + ]); - if ($f['last_post_id']) - { - $template->assign_block_vars('c.f.last', array( - 'LAST_TOPIC_ID' => $f['last_topic_id'], - 'LAST_TOPIC_TIP' => $f['last_topic_title'], - 'LAST_TOPIC_TITLE' => wbr(str_short($f['last_topic_title'], $last_topic_max_len)), - 'LAST_POST_TIME' => bb_date($f['last_post_time'], $bb_cfg['last_post_date_format']), - 'LAST_POST_USER' => profile_url(array('username' => str_short($f['last_post_username'], 15), 'user_id' => $f['last_post_user_id'], 'user_rank' => $f['last_post_user_rank'])), - )); - } - } + if ($f['last_post_id']) { + $template->assign_block_vars('c.f.last', [ + 'LAST_TOPIC_ID' => $f['last_topic_id'], + 'LAST_TOPIC_TIP' => $f['last_topic_title'], + 'LAST_TOPIC_TITLE' => str_short($f['last_topic_title'], $last_topic_max_len), + 'LAST_POST_TIME' => bb_date($f['last_post_time'], config()->get('last_post_date_format')), + 'LAST_POST_USER' => profile_url(['username' => str_short($f['last_post_username'], 15), 'user_id' => $f['last_post_user_id'], 'user_rank' => $f['last_post_user_rank']]), + ]); + } + } } -$template->assign_vars(array( - 'SHOW_FORUMS' => $forums_count, - 'SHOW_MAP' => (isset($_GET['map']) && !IS_GUEST), - 'PAGE_TITLE' => ($viewcat) ? $cat_title_html[$viewcat] : $lang['HOME'], - 'NO_FORUMS_MSG' => ($only_new) ? $lang['NO_NEW_POSTS'] : $lang['NO_FORUMS'], +$template->assign_vars([ + 'SHOW_FORUMS' => $forums_count, + 'SHOW_MAP' => isset($_GET['map']) && !IS_GUEST, + 'PAGE_TITLE' => $viewcat ? $cat_title_html[$viewcat] : $lang['HOME'], + 'NO_FORUMS_MSG' => $only_new ? $lang['NO_NEW_POSTS'] : $lang['NO_FORUMS'], - 'TOTAL_TOPICS' => sprintf($lang['POSTED_TOPICS_TOTAL'], $stats['topiccount']), - 'TOTAL_POSTS' => sprintf($lang['POSTED_ARTICLES_TOTAL'], $stats['postcount']), - 'TOTAL_USERS' => sprintf($lang['REGISTERED_USERS_TOTAL'], $stats['usercount']), - 'TOTAL_GENDER' => ($bb_cfg['gender']) ? sprintf($lang['USERS_TOTAL_GENDER'], $stats['male'], $stats['female'], $stats['unselect']) : '', - 'NEWEST_USER' => sprintf($lang['NEWEST_USER'], profile_url($stats['newestuser'])), + 'TOTAL_TOPICS' => sprintf($lang['POSTED_TOPICS_TOTAL'], $stats['topiccount']), + 'TOTAL_POSTS' => sprintf($lang['POSTED_ARTICLES_TOTAL'], $stats['postcount']), + 'TOTAL_USERS' => sprintf($lang['REGISTERED_USERS_TOTAL'], $stats['usercount']), + 'TOTAL_GENDER' => config()->get('gender') ? sprintf( + $lang['USERS_TOTAL_GENDER'], + $stats['male'], + $stats['female'], + $stats['unselect'] + ) : '', + 'NEWEST_USER' => sprintf($lang['NEWEST_USER'], profile_url($stats['newestuser'])), - // Tracker stats - 'TORRENTS_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['TORRENTS_STAT'], $stats['torrentcount'], humn_size($stats['size'])) : '', - 'PEERS_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['PEERS_STAT'], $stats['peers'], $stats['seeders'], $stats['leechers']) : '', - 'SPEED_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['SPEED_STAT'], humn_size($stats['speed']) .'/s') : '', - 'SHOW_MOD_INDEX' => $bb_cfg['show_mod_index'], - 'FORUM_IMG' => $images['forum'], - 'FORUM_NEW_IMG' => $images['forum_new'], - 'FORUM_LOCKED_IMG' => $images['forum_locked'], + // Tracker stats + 'TORRENTS_STAT' => config()->get('tor_stats') ? sprintf( + $lang['TORRENTS_STAT'], + $stats['torrentcount'], + humn_size($stats['size']) + ) : '', + 'PEERS_STAT' => config()->get('tor_stats') ? sprintf( + $lang['PEERS_STAT'], + $stats['peers'], + $stats['seeders'], + $stats['leechers'] + ) : '', + 'SPEED_STAT' => config()->get('tor_stats') ? sprintf( + $lang['SPEED_STAT'], + humn_size($stats['speed']) . '/s' + ) : '', + 'SHOW_MOD_INDEX' => config()->get('show_mod_index'), + 'FORUM_IMG' => $images['forum'], + 'FORUM_NEW_IMG' => $images['forum_new'], + 'FORUM_LOCKED_IMG' => $images['forum_locked'], - 'SHOW_ONLY_NEW_MENU' => true, - 'ONLY_NEW_POSTS_ON' => ($only_new == ONLY_NEW_POSTS), - 'ONLY_NEW_TOPICS_ON' => ($only_new == ONLY_NEW_TOPICS), + 'SHOW_ONLY_NEW_MENU' => true, + 'ONLY_NEW_POSTS_ON' => $only_new == ONLY_NEW_POSTS, + 'ONLY_NEW_TOPICS_ON' => $only_new == ONLY_NEW_TOPICS, - 'U_SEARCH_NEW' => "search.php?new=1", - 'U_SEARCH_SELF_BY_MY' => "search.php?uid={$userdata['user_id']}&o=1", - 'U_SEARCH_LATEST' => "search.php?search_id=latest", - 'U_SEARCH_UNANSWERED' => "search.php?search_id=unanswered", + 'U_SEARCH_NEW' => 'search.php?new=1', + 'U_SEARCH_SELF_BY_MY' => "search.php?uid={$userdata['user_id']}&o=1", + 'U_SEARCH_LATEST' => 'search.php?search_id=latest', + 'U_SEARCH_UNANSWERED' => 'search.php?search_id=unanswered', + 'U_ATOM_FEED' => is_file(config()->get('atom.path') . '/f/0.atom') ? make_url(config()->get('atom.url') . '/f/0.atom') : false, - 'SHOW_LAST_TOPIC' => $show_last_topic, -)); + 'SHOW_LAST_TOPIC' => $show_last_topic, + 'BOARD_START' => config()->get('show_board_start_index') ? ($lang['BOARD_STARTED'] . ': ' . '' . bb_date(config()->get('board_startdate')) . '') : false, +]); // Set tpl vars for bt_userdata -if ($bb_cfg['bt_show_dl_stat_on_index'] && !IS_GUEST) -{ - show_bt_userdata($userdata['user_id']); +if (config()->get('bt_show_dl_stat_on_index') && !IS_GUEST) { + show_bt_userdata($userdata['user_id']); } // Latest news -if ($bb_cfg['show_latest_news']) -{ - if (!$latest_news = $datastore->get('latest_news')) - { - $datastore->update('latest_news'); - $latest_news = $datastore->get('latest_news'); - } +if (config()->get('show_latest_news')) { + $latest_news = $datastore->get('latest_news'); + if ($latest_news === false) { + $datastore->update('latest_news'); + $latest_news = $datastore->get('latest_news'); + } - $template->assign_vars(array( - 'SHOW_LATEST_NEWS' => true, - )); + $template->assign_vars(['SHOW_LATEST_NEWS' => true]); - foreach ($latest_news as $news) - { - $template->assign_block_vars('news', array( - 'NEWS_TOPIC_ID' => $news['topic_id'], - 'NEWS_TITLE' => str_short($news['topic_title'], $bb_cfg['max_news_title']), - 'NEWS_TIME' => bb_date($news['topic_time'], 'd-M', false), - 'NEWS_IS_NEW' => is_unread($news['topic_time'], $news['topic_id'], $news['forum_id']), - )); - } + foreach ($latest_news as $news) { + if (in_array($news['forum_id'], $excluded_forums_array)) { + continue; + } + + $template->assign_block_vars('news', [ + 'NEWS_TOPIC_ID' => $news['topic_id'], + 'NEWS_TITLE' => str_short(censor()->censorString($news['topic_title']), config()->get('max_news_title')), + 'NEWS_TIME' => bb_date($news['topic_time'], 'd-M', false), + 'NEWS_IS_NEW' => is_unread($news['topic_time'], $news['topic_id'], $news['forum_id']), + ]); + } } // Network news -if ($bb_cfg['show_network_news']) -{ - if (!$network_news = $datastore->get('network_news')) - { - $datastore->update('network_news'); - $network_news = $datastore->get('network_news'); - } +if (config()->get('show_network_news')) { + $network_news = $datastore->get('network_news'); + if ($network_news === false) { + $datastore->update('network_news'); + $network_news = $datastore->get('network_news'); + } - $template->assign_vars(array( - 'SHOW_NETWORK_NEWS' => true, - )); + $template->assign_vars(['SHOW_NETWORK_NEWS' => true]); - foreach ($network_news as $net) - { - $template->assign_block_vars('net', array( - 'NEWS_TOPIC_ID' => $net['topic_id'], - 'NEWS_TITLE' => str_short($net['topic_title'], $bb_cfg['max_net_title']), - 'NEWS_TIME' => bb_date($net['topic_time'], 'd-M', false), - 'NEWS_IS_NEW' => is_unread($net['topic_time'], $net['topic_id'], $net['forum_id']), - )); - } + foreach ($network_news as $net) { + if (in_array($net['forum_id'], $excluded_forums_array)) { + continue; + } + + $template->assign_block_vars('net', [ + 'NEWS_TOPIC_ID' => $net['topic_id'], + 'NEWS_TITLE' => str_short(censor()->censorString($net['topic_title']), config()->get('max_net_title')), + 'NEWS_TIME' => bb_date($net['topic_time'], 'd-M', false), + 'NEWS_IS_NEW' => is_unread($net['topic_time'], $net['topic_id'], $net['forum_id']), + ]); + } } -if ($bb_cfg['birthday_check_day'] && $bb_cfg['birthday_enabled']) -{ - $week_list = $today_list = array(); - $week_all = $today_all = false; +if (config()->get('birthday_check_day') && config()->get('birthday_enabled')) { + $week_list = $today_list = []; + $week_all = $today_all = false; - if ($stats['birthday_week_list']) - { - shuffle($stats['birthday_week_list']); - foreach ($stats['birthday_week_list'] as $i => $week) - { - if ($i >= 5) - { - $week_all = true; - continue; - } - $week_list[] = profile_url($week) .' ('. birthday_age($week['user_birthday']-1) .')'; - } - $week_all = ($week_all) ? ' ...' : ''; - $week_list = sprintf($lang['BIRTHDAY_WEEK'], $bb_cfg['birthday_check_day'], join(', ', $week_list)) . $week_all; - } - else $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], $bb_cfg['birthday_check_day']); + if (!empty($stats['birthday_week_list'])) { + shuffle($stats['birthday_week_list']); + foreach ($stats['birthday_week_list'] as $i => $week) { + if ($i >= 5) { + $week_all = true; + continue; + } + $week_list[] = profile_url($week) . ' (' . birthday_age(date('Y-m-d', strtotime('-1 year', strtotime($week['user_birthday'])))) . ')'; + } + $week_all = $week_all ? ' ...' : ''; + $week_list = sprintf($lang['BIRTHDAY_WEEK'], config()->get('birthday_check_day'), implode(', ', $week_list)) . $week_all; + } else { + $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], config()->get('birthday_check_day')); + } - if ($stats['birthday_today_list']) - { - shuffle($stats['birthday_today_list']); - foreach ($stats['birthday_today_list'] as $i => $today) - { - if ($i >= 5) - { - $today_all = true; - continue; - } - $today_list[] = profile_url($today) .' ('. birthday_age($today['user_birthday']) .')'; - } - $today_all = ($today_all) ? ' ...' : ''; - $today_list = $lang['BIRTHDAY_TODAY'] . join(', ', $today_list) . $today_all; - } - else $today_list = $lang['NOBIRTHDAY_TODAY']; + if (!empty($stats['birthday_today_list'])) { + shuffle($stats['birthday_today_list']); + foreach ($stats['birthday_today_list'] as $i => $today) { + if ($i >= 5) { + $today_all = true; + continue; + } + $today_list[] = profile_url($today) . ' (' . birthday_age($today['user_birthday']) . ')'; + } + $today_all = $today_all ? ' ...' : ''; + $today_list = $lang['BIRTHDAY_TODAY'] . implode(', ', $today_list) . $today_all; + } else { + $today_list = $lang['NOBIRTHDAY_TODAY']; + } - $template->assign_vars(array( - 'WHOSBIRTHDAY_WEEK' => $week_list, - 'WHOSBIRTHDAY_TODAY' => $today_list, - )); + $template->assign_vars([ + 'WHOSBIRTHDAY_WEEK' => $week_list, + 'WHOSBIRTHDAY_TODAY' => $today_list + ]); } // Allow cron -if (IS_AM) -{ - if (file_exists(CRON_RUNNING)) - { - if (file_exists(CRON_ALLOWED)) - { - unlink (CRON_ALLOWED); - } - rename(CRON_RUNNING, CRON_ALLOWED); - } +if (IS_AM) { + if (is_file(CRON_RUNNING)) { + if (is_file(CRON_ALLOWED)) { + unlink(CRON_ALLOWED); + } + rename(CRON_RUNNING, CRON_ALLOWED); + } } // Display page define('SHOW_ONLINE', $show_online_users); -if (isset($_GET['map'])) $template->assign_vars(array('PAGE_TITLE' => $lang['FORUM_MAP'])); +if (isset($_GET['map'])) { + $template->assign_vars(['PAGE_TITLE' => $lang['FORUM_MAP']]); +} -print_page('index.tpl'); \ No newline at end of file +print_page('index.tpl'); diff --git a/info.php b/info.php index 500596c8d..e47c3ef32 100644 --- a/info.php +++ b/info.php @@ -1,71 +1,51 @@ session_start(); -global $lang; +$info = []; +$htmlDir = LANG_DIR . 'html/'; +$show = isset($_REQUEST['show']) ? (string)$_REQUEST['show'] : ''; -$info = array(); -$html_dir = LANG_DIR . 'html/'; -$req_mode = !empty($_REQUEST['show']) ? (string) $_REQUEST['show'] : 'not_found'; +switch ($show) { + case 'advert': + $info['title'] = $lang['ADVERT']; + $info['src'] = 'advert.html'; + break; -switch ($req_mode) -{ - case 'advert': - $info['title'] = $lang['ADVERT']; - $info['src'] = 'advert.html'; - break; + case 'copyright_holders': + $info['title'] = $lang['COPYRIGHT_HOLDERS']; + $info['src'] = 'copyright_holders.html'; + break; - case 'copyright_holders': - $info['title'] = $lang['COPYRIGHT_HOLDERS']; - $info['src'] = 'copyright_holders.html'; - break; + case 'user_agreement': + $info['title'] = $lang['USER_AGREEMENT']; + $info['src'] = 'user_agreement.html'; + break; - case 'not_found': - $info['title'] = $lang['NOT_FOUND']; - $info['src'] = 'not_found.html'; - break; - - case 'user_agreement': - $info['title'] = $lang['USER_AGREEMENT']; - $info['src'] = 'user_agreement.html'; - break; - - default: - bb_simple_die('Invalid request'); + default: + case 'not_found': + $info['title'] = $lang['NOT_FOUND']; + $info['src'] = 'not_found.html'; + break; } -$require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $html_dir . 'not_found.html'; +$require = is_file($htmlDir . $info['src']) ? ($htmlDir . $info['src']) : false; -?> - - - - - - - - -
        -
        -
        - -
        - -
        -
        -

        [ ]

        -
        - - \ No newline at end of file +$template->assign_vars([ + 'PAGE_TITLE' => mb_strtoupper($info['title'], DEFAULT_CHARSET), + 'REQUIRE' => $require ? file_get_contents($require) : $lang['NOT_FOUND'], +]); + +print_page('info.tpl', 'simple'); diff --git a/install.php b/install.php new file mode 100644 index 000000000..b04535eda --- /dev/null +++ b/install.php @@ -0,0 +1,331 @@ +php ' . basename(__FILE__) . ' in CLI mode'); +} + +// Get all constants +require_once BB_ROOT . 'library/defines.php'; + +// Include CLI functions +require INC_DIR . '/functions_cli.php'; + +/** + * System requirements + */ +const CHECK_REQUIREMENTS = [ + 'php_min_version' => '8.2.0', + 'ext_list' => [ + 'json', + 'curl', + 'readline', + 'mysqli', + 'bcmath', + 'mbstring', + 'intl', + 'xml', + 'xmlwriter', + 'zip', + 'gd' + ], +]; + +// Welcoming message +out("--- TorrentPier Installer ---\n", 'info'); + +// Checking extensions +out("- Checking installed extensions...", 'info'); + +// [1] Check PHP Version +if (!version_compare(PHP_VERSION, CHECK_REQUIREMENTS['php_min_version'], '>=')) { + out("- TorrentPier requires PHP version " . CHECK_REQUIREMENTS['php_min_version'] . "+ Your PHP version " . PHP_VERSION, 'warning'); +} + +// [2] Check installed PHP Extensions on server +foreach (CHECK_REQUIREMENTS['ext_list'] as $ext) { + if (!extension_loaded($ext)) { + out("- ext-$ext not installed. Check out php.ini file", 'error'); + if (!defined('EXTENSIONS_NOT_INSTALLED')) { + define('EXTENSIONS_NOT_INSTALLED', true); + } + } else { + out("- ext-$ext installed!"); + } +} +if (!defined('EXTENSIONS_NOT_INSTALLED')) { + out("- All extensions are installed!\n", 'success'); +} else { + exit; +} + +// Check if already installed +if (is_file(BB_ROOT . '.env')) { + out('- TorrentPier already installed', 'warning'); + echo 'Are you sure want to re-install TorrentPier? [y/N]: '; + if (str_starts_with(mb_strtolower(trim(readline())), 'y')) { + out("\n- Re-install process started...", 'info'); + // environment + if (is_file(BB_ROOT . '.env')) { + if (unlink(BB_ROOT . '.env')) { + out('- Environment file successfully removed!'); + } else { + out('- Cannot remove environment (.env) file. Delete it manually', 'error'); + exit; + } + } + // composer.phar + if (is_file(BB_ROOT . 'composer.phar')) { + if (unlink(BB_ROOT . 'composer.phar')) { + out("- composer.phar file successfully removed!"); + } else { + out('- Cannot remove composer.phar file. Delete it manually', 'error'); + exit; + } + } + // composer dir + if (is_dir(BB_ROOT . 'vendor')) { + removeDir(BB_ROOT . 'vendor', true); + if (!is_dir(BB_ROOT . 'vendor')) { + out("- Composer directory successfully removed!"); + } else { + out('- Cannot remove Composer directory. Delete it manually', 'error'); + exit; + } + } + out("- Re-install process completed!\n", 'success'); + out('- Starting installation...', 'info'); + } else { + exit; + } +} + +// Applying permissions +out("- Applying permissions for folders...", 'info'); +chmod_r(BB_ROOT . 'data', 0755, 0644); +chmod_r(BB_ROOT . 'internal_data', 0755, 0644); +chmod_r(BB_ROOT . 'sitemap', 0755, 0644); +out("- Permissions successfully applied!\n", 'success'); + +// Check composer installation +if (!is_file(BB_ROOT . 'vendor/autoload.php')) { + out('- Hmm, it seems there are no Composer dependencies', 'info'); + + // Downloading composer + if (!is_file(BB_ROOT . 'composer.phar')) { + out('- Downloading Composer...', 'info'); + if (copy('https://getcomposer.org/installer', BB_ROOT . 'composer-setup.php')) { + out("- Composer successfully downloaded!\n", 'success'); + runProcess('php ' . BB_ROOT . 'composer-setup.php --install-dir=' . BB_ROOT); + } else { + out('- Cannot download Composer. Please, download it (composer.phar) manually', 'error'); + exit; + } + if (is_file(BB_ROOT . 'composer-setup.php')) { + if (unlink(BB_ROOT . 'composer-setup.php')) { + out("- Composer installation file successfully removed!\n", 'success'); + } else { + out('- Cannot remove Composer installation file (composer-setup.php). Please, delete it manually', 'warning'); + } + } + } else { + out("- composer.phar file found!\n", 'success'); + } + + // Installing dependencies + if (is_file(BB_ROOT . 'composer.phar')) { + out('- Installing dependencies...', 'info'); + + runProcess('php ' . BB_ROOT . 'composer.phar install --no-interaction --no-ansi'); + define('COMPOSER_COMPLETED', true); + } else { + out('- composer.phar not found. Please, download it (composer.phar) manually', 'error'); + exit; + } +} else { + out('- Composer dependencies are present!', 'success'); + out("- Note: Remove 'vendor' folder if you want to re-install dependencies\n"); +} + +// Check composer dependencies +if (defined('COMPOSER_COMPLETED')) { + if (is_file(BB_ROOT . 'vendor/autoload.php')) { + out("- Completed! Composer dependencies are installed!\n", 'success'); + } else { + exit; + } +} + +// Preparing ENV +if (is_file(BB_ROOT . '.env.example') && !is_file(BB_ROOT . '.env')) { + if (copy(BB_ROOT . '.env.example', BB_ROOT . '.env')) { + out("- Environment file created!\n", 'success'); + } else { + out('- Cannot create environment file', 'error'); + exit; + } +} + +// Editing ENV file +$DB_HOST = 'localhost'; +$DB_PORT = 3306; +$DB_DATABASE = ''; +$DB_USERNAME = ''; +$DB_PASSWORD = ''; + +if (is_file(BB_ROOT . '.env')) { + out("--- Configuring TorrentPier ---", 'info'); + + $envContent = file_get_contents(BB_ROOT . '.env'); + if ($envContent === false) { + out('- Cannot open environment file', 'error'); + exit; + } + $envLines = explode("\n", $envContent); + + $editedLines = []; + foreach ($envLines as $line) { + if (trim($line) !== '' && !str_starts_with($line, '#')) { + $parts = explode('=', $line, 2); + $key = trim($parts[0]); + $value = (!empty($parts[1]) && $key !== 'DB_PASSWORD') ? trim($parts[1]) : ''; + + out("\nCurrent value of $key: $value", 'debug'); + echo "Enter a new value for $key (or leave empty to not change): "; + $newValue = trim(readline()); + + if (!empty($newValue) || $key === 'DB_PASSWORD') { + if ($key === 'TP_HOST') { + if (!preg_match('/^https?:\/\//', $newValue)) { + $newValue = 'https://' . $newValue; + } + $newValue = parse_url($newValue, PHP_URL_HOST); + } + $line = "$key=$newValue"; + $$key = $newValue; + } else { + $$key = $value; + } + } + + $editedLines[] = $line; + } + + $newEnvContent = implode("\n", $editedLines); + if (file_put_contents(BB_ROOT . '.env', $newEnvContent)) { + out("- TorrentPier successfully configured!\n", 'success'); + } else { + out('- Cannot save environment file', 'error'); + exit; + } +} else { + out('- Environment file not found', 'error'); + exit; +} + +if (!empty($DB_HOST) && !empty($DB_DATABASE) && !empty($DB_USERNAME)) { + out("--- Checking environment settings ---\n", 'info'); + // Connecting to database + out("- Trying connect to MySQL...", 'info'); + + // Checking mysqli extension installed + if (!extension_loaded('mysqli')) { + out('- ext-mysqli not found. Check out php.ini file', 'error'); + exit; + } + + // Connect to MySQL server + try { + $conn = new mysqli($DB_HOST, $DB_USERNAME, $DB_PASSWORD, port: $DB_PORT); + } catch (mysqli_sql_exception $exception) { + out("- Connection failed: {$exception->getMessage()}", 'error'); + exit; + } + if (!$conn->connect_error) { + out('- Connected successfully!', 'success'); + } + + // Creating database if not exist + if ($conn->query("CREATE DATABASE IF NOT EXISTS $DB_DATABASE CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")) { + out('- Database created successfully!', 'success'); + } else { + out("- Cannot create database: $DB_DATABASE", 'error'); + exit; + } + $conn->select_db($DB_DATABASE); + + // Close database connection - migrations will handle their own connections + $conn->close(); + + // Run database migrations + out('- Setting up database using migrations...', 'info'); + + // Check if phinx.php exists + if (!is_file(BB_ROOT . 'phinx.php')) { + out('- Migration configuration (phinx.php) not found', 'error'); + exit; + } + + // Run migrations + $migrationResult = runProcess('php vendor/bin/phinx migrate --configuration=' . BB_ROOT . 'phinx.php'); + if ($migrationResult !== 0) { + out('- Database migration failed', 'error'); + exit; + } + + out("- Database setup completed!\n", 'success'); + + // Autofill host in robots.txt + $robots_txt_file = BB_ROOT . 'robots.txt'; + if (isset($TP_HOST) && is_file($robots_txt_file)) { + $content = file_get_contents($robots_txt_file); + $content = str_replace('example.com', $TP_HOST, $content); + file_put_contents($robots_txt_file, $content); + } + + if (isset($APP_ENV) && $APP_ENV === 'local') { + if (!is_file(BB_ROOT . 'library/config.local.php')) { + if (copy(BB_ROOT . 'library/config.php', BB_ROOT . 'library/config.local.php')) { + out('- Local configuration file created!', 'success'); + } else { + out('- Cannot create library/config.local.php file. You can create it manually, just copy config.php and rename it to config.local.php', 'warning'); + } + } + } else { + if (rename(__FILE__, __FILE__ . '_' . hash('xxh128', time()))) { + out("- Installation file renamed!", 'success'); + } else { + out('- Cannot rename installation file (' . __FILE__ . '). Please, rename it manually for security reasons', 'warning'); + } + } + + // Cleanup... + if (is_file(BB_ROOT . '_cleanup.php')) { + out("\n--- Finishing installation (Cleanup) ---\n", 'info'); + out('The cleanup process will remove:'); + out('- Development documentation (README, CHANGELOG)', 'debug'); + out('- Git configuration files', 'debug'); + out('- CI/CD pipelines and code analysis tools', 'debug'); + out('- Translation and contribution guidelines', 'debug'); + echo 'Do you want to delete these files permanently? [y/N]: '; + if (str_starts_with(mb_strtolower(trim(readline())), 'y')) { + out("\n- Cleanup...", 'info'); + require_once BB_ROOT . '_cleanup.php'; + unlink(BB_ROOT . '_cleanup.php'); + } else { + out('- Skipping...', 'info'); + } + } + + out("\n- Voila! Good luck & have fun!", 'success'); +} diff --git a/install/.htaccess b/install/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/install/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/install/Caddyfile b/install/Caddyfile new file mode 100644 index 000000000..683d69994 --- /dev/null +++ b/install/Caddyfile @@ -0,0 +1,27 @@ +# Example Caddy configuration for TorrentPier + +example.com { + root * /path/to/root + encode gzip zstd + php_fastcgi unix//run/php/php-fpm.sock + try_files {path} {path}/ /index.php?{query} + file_server + + @blocked { + path /install/* /internal_data/* /library/* + path /.ht* /.en* + path /.git/* + path *.sql *.tpl *.db *.inc *.log *.md + } + respond @blocked 404 + + redir /sitemap.xml /sitemap/sitemap.xml + + @html_css_js { + path *.html *.css *.js *.json *.xml *.txt + } + header @html_css_js Content-Type "{mime}; charset=utf-8" +} + +# Refer to the Caddy docs for more information: +# https://caddyserver.com/docs/caddyfile diff --git a/install/nginx.conf b/install/nginx.conf new file mode 100644 index 000000000..49a407ba4 --- /dev/null +++ b/install/nginx.conf @@ -0,0 +1,39 @@ +# Example nginx configuration for TorrentPier + +server { + listen 80; # port + server_name example.com; # your domain + root /path/to/root; # folder with TorrentPier installed + index index.php; + charset utf-8; + + location / { + try_files \$uri \$uri/ /index.php?\$args; + } + + location ~ \/(install|internal_data|library)\/ { + return 404; + } + + location ~ /\.(ht|en) { + return 404; + } + + location ~ /\.git { + return 404; + } + + location ~ \.(.*sql|tpl|db|inc|log|md)$ { + return 404; + } + + rewrite ^/sitemap.xml$ /sitemap/sitemap.xml; + + location ~ \.php$ { + include fastcgi_params; + fastcgi_pass unix:/run/php/php-fpm.sock; + fastcgi_index index.php; + fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name; + include fastcgi_params; + } +} diff --git a/install/other/converter/TBDevYSE_pre6/ReadMe.txt b/install/other/converter/TBDevYSE_pre6/ReadMe.txt deleted file mode 100644 index 198424165..000000000 --- a/install/other/converter/TBDevYSE_pre6/ReadMe.txt +++ /dev/null @@ -1,21 +0,0 @@ -TBDev Yuna Scatari Edition pre6 to TorrentPier 1.0.x converter. - -Quick guide: -1. Install and configure TorrentPier 1.0.0 or higher. -2. Import your TBDevYSE database into TorrentPier database (concretely 'comments', 'categories', 'torrents' and 'users' tables). -3. Put the contents of folder 'root' into your TorrentPier root. -4. Configure 'converter/settings.php' for optimal settings. -5. Run convert.php. -6. See 'converter/passwords.php' for new password to login under admin account. -7. Resychronize statistics using admin panel. -8. Make your new tracker popular! ----- -9. If you need to notify users for new passwords (which are needed to login in TorrentPier) via TBDevYSE PM system, - copy two files: automatically generated 'converter/passwords.php' and 'for_tbdev/pass.php' to your TBDevYSE root and run pass.php - (Don't forget to remove these files after completion). - You allow to change message text, see $msg in pass.php for this. -10. If you want to redirect peers from older announce to new announce everytime, replace original TBDev's announce.php with - 'for_tbdev/announce.php' - -Cheers, RoadTrain. -http://torrentpier.me/ \ No newline at end of file diff --git a/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php b/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php deleted file mode 100644 index f419ab6d9..000000000 --- a/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php +++ /dev/null @@ -1,62 +0,0 @@ - -
        -
        - -
        -
        - '; -} -else -{ - if (!file_exists('passwords.php')) stderr($tracker_lang['error'], 'passwords.php not exists'); - - include('passwords.php'); - stdhead(); - foreach ($passwords as $user) - { - $msg_sql = sprintf($msg, $user['username'], $user['new_passwd']); - sql_query("INSERT INTO messages (receiver, added, subject, msg) VALUES({$user['tb_user_id']}, NOW(), ".sqlesc($subject).", ".sqlesc($msg_sql).")"); - } - stdmsg('OK', 'Mass PM succesful'); -} - -stdfoot(); \ No newline at end of file diff --git a/install/other/converter/TBDevYSE_pre6/root/convert.php b/install/other/converter/TBDevYSE_pre6/root/convert.php deleted file mode 100644 index 48192b3a2..000000000 --- a/install/other/converter/TBDevYSE_pre6/root/convert.php +++ /dev/null @@ -1,261 +0,0 @@ -session_start(); - -if (!IS_ADMIN) die("Restricted access"); -while (@ob_end_flush()); -ob_implicit_flush(); - -error_reporting(E_ALL); -@ini_set('display_errors', 1); - -?> - - - - - - - - - - -
        -
        - -
        -
        - - '; - - exit; -} -else -{ - -@ini_set('memory_limit', '512M'); -@ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); - -// Step 1: Converting Users -if (CONVERT_USERS) -{ - if (CLEAN) - { - tp_users_cleanup(); - print_ok ("Users cleared"); - } - - $max_uid = (int) get_max_val(BB_USERS, 'user_id'); - $max_uid = ($max_uid > 1) ? $max_uid : 1; - - $users_count = (int) get_count(TB_USERS_TABLE, 'id'); - $loops = (int) ceil($users_count / C_USERS_PER_ONCE); - $pass = array(); - - switch(TR_TYPE) - { - case 'yse': - $_sql = 'avatar, '; - break; - - default: - $_sql = ''; - break; - } - - for ($i = 0; $i < $loops; $i++) - { - $start = $i * C_USERS_PER_ONCE; - $offset = C_USERS_PER_ONCE; - - $sql = " - SELECT - id, username, email, status, UNIX_TIMESTAMP(added) AS added, UNIX_TIMESTAMP(last_access) AS last_access, - class, icq, msn, aim, yahoo, website, $_sql - uploaded, downloaded, enabled, language - FROM ". TB_USERS_TABLE ." - ORDER BY id - LIMIT $start, $offset"; - - $users = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); - - foreach ($users as $user) - { - $user['id'] += $max_uid; - $user['password'] = make_rand_str(15); - convert_user($user); - $pass[] = array( - 'tb_user_id' => $user['id'] - $max_uid, - 'username' => $user['username'], - 'new_passwd' => $user['password'], - ); - } - } - $passf = fopen('./converter/passwords.php', 'w'); - $to_write = " $tr_cat_id, - "cat_title" => 'Tracker', - ); - tp_add_category($tp_cat_data); - set_auto_increment(BB_CATEGORIES, 'cat_id'); - unset($tp_cat_data); - - $cats = $db->fetch_rowset("SELECT id, sort, name FROM ". TB_CATEGORIES_TABLE); - DB()->sql_freeresult(); - - $max_forum_id = (int) get_max_val(BB_FORUMS, 'forum_id'); - - foreach ($cats as $cat) - { - $cat['id'] += $max_forum_id; - $cat['cat_id'] = $tr_cat_id; - convert_cat($cat); - } - set_auto_increment(BB_FORUMS, 'forum_id'); - print_ok ("Categories from TBDev converted"); - unset($cats); - - // Start of torrents converting - switch(TR_TYPE) - { - case 'yse': - $_sql = 'image1, image2, '; - break; - - case 'sky': - $_sql = 'poster, screenshot1, screenshot2, screenshot3, screenshot4, '; - break; - - default: - $_sql = ''; - break; - } - - $max_topic_id = (int) get_max_val(BB_TOPICS, 'topic_id'); - $max_post_id = (int) get_max_val(BB_POSTS, 'post_id'); - $max_attach_id = (int) get_max_val(BB_ATTACHMENTS, 'attach_id'); - - $torrents_count = (int) get_count(TB_TORRENTS_TABLE, 'id'); - $loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); - - for ($i = 0; $i < $loops; $i++) - { - $start = $i * C_TORRENTS_PER_ONCE; - $offset = C_TORRENTS_PER_ONCE; - $sql = " - SELECT - id, info_hash, name, filename, search_text, descr, $_sql - category, UNIX_TIMESTAMP(added) AS added, size, views, - UNIX_TIMESTAMP(last_action) AS lastseed, times_completed, owner, sticky - FROM ". TB_TORRENTS_TABLE ." - ORDER BY id - LIMIT $start, $offset"; - - $torrents = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); - - foreach ($torrents as $torrent) - { - $torrent['topic_id'] = $torrent['id'] + $max_topic_id; - $torrent['post_id'] = $torrent['id'] + $max_post_id; - $torrent['attach_id'] = $torrent['id'] + $max_attach_id; - $torrent['owner'] += $max_uid; - $torrent['descr'] = append_images($torrent); - convert_torrent($torrent); - //print_r($torrent); - } - } - set_auto_increment(BB_TOPICS, 'topic_id'); - set_auto_increment(BB_POSTS, 'post_id'); - print_ok ("Total $torrents_count torrents from TBDev converted"); - unset($torrents); - - if (CONVERT_COMMENTS) - { - $max_post_id = (int) get_max_val(BB_POSTS, 'post_id'); - $max_topic_id = (int) get_max_val(BB_TOPICS, 'topic_id'); - $max_attach_id = (int) get_max_val(BB_ATTACHMENTS, 'attach_id'); - - $comments_count = (int) get_count(TB_COMMENTS_TABLE, 'id'); - $loops = (int) ceil($comments_count / C_COMMENTS_PER_ONCE); - - for ($i = 0; $i < $loops; $i++) - { - $start = $i * C_COMMENTS_PER_ONCE; - $offset = C_COMMENTS_PER_ONCE; - $sql = " - SELECT - c.id, c.user, c.torrent, c.text, tor.category, - UNIX_TIMESTAMP(c.added) AS added, UNIX_TIMESTAMP(c.editedat) AS editedat, c.ip - FROM ". TB_COMMENTS_TABLE ." c - LEFT JOIN ". TB_TORRENTS_TABLE ." tor ON(tor.id = c.torrent) - WHERE c.torrent <> 0 - ORDER BY c.id - LIMIT $start, $offset"; - - $comments = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); - - foreach ($comments as $comment) - { - $comment['user'] += $max_uid; - $comment['id'] += $max_post_id; - convert_comment($comment); - } - } - unset($comments); - set_auto_increment(BB_POSTS, 'post_id'); - print_ok ("Total $comments_count comments from TBDev converted"); - } -} - -?> - -
        -Converting completed. - - - \ No newline at end of file diff --git a/install/other/converter/TBDevYSE_pre6/root/converter/constants.php b/install/other/converter/TBDevYSE_pre6/root/converter/constants.php deleted file mode 100644 index 106438984..000000000 --- a/install/other/converter/TBDevYSE_pre6/root/converter/constants.php +++ /dev/null @@ -1,8 +0,0 @@ -" : ''; - $err = ''; - - echo '
        '; - echo "OK - $sql". str_repeat(' ', 256) ."\n
        "; - echo '
        '; -} - -function hex2bin($h) -{ - if (!is_string($h)) return null; - $r=''; - for ($a=0; $afetch_row("SELECT MAX($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; -} - -function get_count($table_name, $column) -{ - $row = DB()->fetch_row("SELECT COUNT($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; -} - -function set_auto_increment($table_name, $column, $val = null) -{ - if (empty($val)) - { - $row = DB()->fetch_row("SELECT MAX($column) AS val FROM $table_name LIMIT 1"); - DB()->sql_freeresult(); - $val = (int) $row['val'] + 1; - } - DB()->query("ALTER TABLE $table_name auto_increment = $val"); -} - -// Users functions -function tp_users_cleanup() -{ - DB()->query('DELETE FROM '. BB_USERS .' WHERE user_id NOT IN('. EXCLUDED_USERS_CSV .')'); - DB()->query('TRUNCATE '. BB_BT_USERS); -} - -function tp_user_level($tb_class) -{ - switch($tb_class) - { - case 0: - case 1: - case 2: - case 3: - $level = 0; - break; - case 4: - $level = 2; - break; - case 5: - case 6: - case 7: - $level = 1; - break; - default: - $level = 0; - break; - } - return $level; -} - -function convert_user($user) -{ - $user_data = array( - "user_id" => $user['id'], - "user_active" => ($user['enabled'] == 'yes') ? true : false, - "username" => $user['username'], - "user_password" => md5($user['password']), - "user_lastvisit" => $user['last_access'], - "user_regdate" => $user['added'], - "user_level" => tp_user_level($user['class']), - "user_lang" => $user['language'], - "user_dateformat" => "Y-m-d H:i", - "user_opt" => 0, - "user_avatar" => !empty($user['avatar']) ? $user['avatar'] : null, - "user_avatar_type" => !empty($user['avatar']) ? 2 : null, - "user_email" => $user['email'], - "user_website" => $user['website'], - ); - - $columns = $values = array(); - - foreach ($user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_USERS . " ($sql_columns) VALUES($sql_values);"); - - $bt_user_data = array( - "user_id" => $user['id'], - "auth_key" => make_rand_str(BT_AUTH_KEY_LENGTH), - "u_up_total" => $user['uploaded'], - "u_down_total" => $user['downloaded'], - ); - $columns = $values = array(); - - foreach ($bt_user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_BT_USERS . " ($sql_bt_columns) VALUES($sql_bt_values);"); -} - -//Torrents and categories functions -function tp_categories_cleanup() -{ - DB()->query('DELETE FROM '. BB_CATEGORIES); -} - -function tp_add_category_old($id, $cat_title) -{ - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES ." (cat_id, cat_title) - VALUES ($id, '". DB()->escape($cat_title) ."')"); - return; -} - -function tp_add_category($cat_data) -{ - $columns = $values = array(); - - foreach ($cat_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES . " ($sql_bt_columns) VALUES($sql_bt_values);"); -} - -function tp_topics_cleanup() -{ - DB()->query("TRUNCATE ". BB_ATTACHMENTS); - DB()->query("TRUNCATE ". BB_ATTACHMENTS_DESC); - DB()->query("TRUNCATE ". BB_BT_TORRENTS); - DB()->query("TRUNCATE ". BB_POSTS); - DB()->query("TRUNCATE ". BB_POSTS_HTML); - DB()->query("TRUNCATE ". BB_POSTS_SEARCH); - DB()->query("TRUNCATE ". BB_POSTS_TEXT); - DB()->query("TRUNCATE ". BB_TOPICS); - - return; -} - -function tp_add_topic($topic_data) -{ - $columns = $values = array(); - foreach ($topic_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_TOPICS . " ($sql_columns) VALUES($sql_values);"); - return; -} - -function tp_add_post($post_data) -{ - foreach ($post_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES($sql_values);"); - } - return; -} - -function tp_add_attach($attach_data) -{ - foreach ($attach_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES($sql_values);"); - } - return; -} - -function make_img_path ($name) -{ - global $bb_cfg; - - return make_url("files/images/" . $name); -} - -function append_images($tor) -{ - $poster = $screens = ''; - switch(TR_TYPE) - { - case 'yse': - if (!empty($tor['image1'])) - { - $poster = "[img=right]".make_img_path($tor['image1'])."[/img]"; - } - if (!empty($tor['image2'])) - { - $screens = '[spoiler="Скриншоты"][img]'.make_img_path($tor['image2'])."[/img][/spoiler]"; - } - break; - case 'sky': - if (!empty($tor['poster'])) - { - $poster = "[img=right]".make_img_path($tor['poster'])."[/img]"; - } - $has_screens = !empty($tor['screenshot1']) || !empty($tor['screenshot2']) || !empty($tor['screenshot3']) || !empty($tor['screenshot4']); - if ($has_screens) - { - $screens .= '[spoiler="Скриншоты"]'; - for ($i = 1; $i <= 4; $i++) - { - if (!empty($tor['screenshot'.$i])) - { - $screens .= "[img]".make_img_path($tor['screenshot'.$i])."[/img] \n"; - } - } - $screens .= "[/spoiler]"; - } - break; - } - return ($poster . $tor['descr'] . $screens); -} - -function convert_torrent($torrent) -{ - $topic_data = array( - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "topic_title" => $torrent['name'], - "topic_poster" => $torrent['owner'], - "topic_time" => $torrent['added'], - "topic_views" => $torrent['views'], - "topic_type" => ($torrent['sticky'] == 'yes') ? 1 : 0, - "topic_first_post_id" => $torrent['id'], - "topic_last_post_id" => $torrent['id'], - "topic_attachment" => 1, - "topic_dl_type" => 1, - "topic_last_post_time" => $torrent['added'], - ); - tp_add_topic($topic_data); - $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); - - $post_data = array( - "posts" => array( - "post_id" => $torrent['post_id'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "poster_id" => $torrent['owner'], - "post_time" => $torrent['added'], - "post_attachment" => 1, - ), - "posts_text" => array( - "post_id" => $torrent['post_id'], - "post_text" => $post_text, - ), - "posts_search" => array( - "post_id" => $torrent['post_id'], - "search_words" => $torrent['search_text'], - ), - ); - tp_add_post($post_data); - - $attach_data = array( - "attachments" => array( - "attach_id" => $torrent['attach_id'], - "post_id" => $torrent['post_id'], - "user_id_1" => $torrent['owner'], - ), - "attachments_desc" => array( - "attach_id" => $torrent['attach_id'], - "physical_filename" => $torrent['id'] . ".torrent", - "real_filename" => $torrent['filename'], - "extension" => "torrent", - "mimetype" => "application/x-bittorrent", - "filesize" => @filesize(get_attachments_dir() .'/'. $torrent['id'] .".torrent"), - "filetime" => $torrent['added'], - "tracker_status" => 1, - ), - ); - tp_add_attach($attach_data); - - //Torrents - if (BDECODE) - { - $filename = get_attachments_dir() .'/'. $torrent['id'] .".torrent"; - if (!file_exists($filename)) - { - return; - } - if (!function_exists('bdecode_file')) include_once(INC_DIR .'functions_torrent.php'); - $tor = bdecode_file($filename); - $info = ($tor['info']) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - } - else - { - $info_hash_sql = hex2bin($torrent['info_hash']); - } - - $torrent_data = array( - "info_hash" => $info_hash_sql, - "post_id" => $torrent['post_id'], - "poster_id" => $torrent['owner'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "attach_id" => $torrent['attach_id'], - "size" => $torrent['size'], - "reg_time" => $torrent['added'], - "complete_count" => $torrent['times_completed'], - "seeder_last_seen" => $torrent['lastseed'], - ); - - $columns = $values = array(); - - foreach ($torrent_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". $db->escape($value) ."'"; - } - $sql_columns = implode(', ', $columns); - $sql_values = implode(', ', $values); - - DB()->query("INSERT IGNORE INTO ". BB_BT_TORRENTS . " ($sql_columns) VALUES($sql_values);"); - return; -} - -// Comments functions -function convert_comment($comment) -{ - $post_text = prepare_message($comment['text'], true, true); - - $post_data = array( - "posts" => array( - "post_id" => $comment['id'], - "topic_id" => $comment['torrent'], - "forum_id" => $comment['category'], - "poster_id" => $comment['user'], - "post_time" => $comment['added'], - "poster_ip" => encode_ip($comment['ip']), - "post_edit_time" => $comment['editedat'], - "post_edit_count" => $comment['editedat'] ? 1 : 0, - ), - "posts_text" => array( - "post_id" => $comment['id'], - "post_text" => $post_text, - ), - ); - tp_add_post($post_data); - return; -} - -//Forums functions -function tp_forums_cleanup() -{ - DB()->query('TRUNCATE '. BB_FORUMS); -} - -function convert_cat($forum, $allow_torrents = true) -{ - $forum_data = array( - "forum_id" => $forum['id'], - "cat_id" => $forum['cat_id'], - "forum_name" => $forum['name'], - "forum_order" => $forum['sort'], - "allow_reg_tracker" => $allow_torrents, - "allow_porno_topic" => $allow_torrents, - ); - - $columns = $values = array(); - - foreach ($forum_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_FORUMS . " ($sql_columns) VALUES($sql_values);"); - return; -} diff --git a/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php b/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php deleted file mode 100644 index 63c2de744..000000000 --- a/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php +++ /dev/null @@ -1,3 +0,0 @@ -session_start(); - -while (@ob_end_flush()); -ob_implicit_flush(); - -?> - - - - - - - - - - -
        -
        - -
        -
        - - '; - - exit; -} -else -{ - -@ini_set('memory_limit', '512M'); -@ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); - -$torrents_count = (int) get_count(BB_BT_TORRENTS, 'attach_id'); -$loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); - -$not_exist = array(); - -$attach_dir = get_attachments_dir() .'/'; - -for ($i = 0; $i < $loops; $i++) -{ - $start = $i * C_TORRENTS_PER_ONCE; - $offset = C_TORRENTS_PER_ONCE; - - $sql = "SELECT - tor.attach_id, tor.topic_id, ad.physical_filename - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_ATTACHMENTS_DESC ." ad ON(ad.attach_id = tor.attach_id) - ORDER BY tor.attach_id - LIMIT $start, $offset"; - - $torrents = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); - - foreach ($torrents as $torrent) - { - $filename = $attach_dir . $torrent['physical_filename']; - if (!file_exists($filename)) - { - $not_exist[] = ''. $filename .''; - } - else - { - $tor = bdecode_file($filename); - $info = (!empty($tor['info'])) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - - DB()->query("UPDATE ". BB_BT_TORRENTS ." - SET info_hash = '$info_hash_sql' - WHERE attach_id = {$torrent['attach_id']}"); - } - } -} - -print_ok ("Completed"); - -if (!empty($not_exist)) -{ - print_ok ("These torrents doesn't exist in filesystem: ". implode(', ', array_unique($not_exist))); -} - -} \ No newline at end of file diff --git a/install/other/recover/converter/constants.php b/install/other/recover/converter/constants.php deleted file mode 100644 index 106438984..000000000 --- a/install/other/recover/converter/constants.php +++ /dev/null @@ -1,8 +0,0 @@ -" : ''; - $err = ''; - - echo '
        '; - echo "OK - $sql". str_repeat(' ', 256) ."\n
        "; - echo '
        '; -} - -function hex2bin($h) -{ - if (!is_string($h)) return null; - $r=''; - for ($a=0; $afetch_row("SELECT MAX($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; -} - -function get_count($table_name, $column) -{ - $row = DB()->fetch_row("SELECT COUNT($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; -} - -function set_auto_increment($table_name, $column, $val = null) -{ - if (empty($val)) - { - $row = DB()->fetch_row("SELECT MAX($column) AS val FROM $table_name LIMIT 1"); - DB()->sql_freeresult(); - $val = (int) $row['val'] + 1; - } - DB()->query("ALTER TABLE $table_name auto_increment = $val"); -} - -//Users functions -function tp_users_cleanup() -{ - DB()->query('DELETE FROM '. BB_USERS .' WHERE user_id NOT IN('. EXCLUDED_USERS_CSV .')'); - DB()->query('TRUNCATE '. BB_BT_USERS); -} - -function tp_user_level($tb_class) -{ - switch($tb_class) - { - case 0: - case 1: - case 2: - case 3: - $level = 0; - break; - case 4: - $level = 2; - break; - case 5: - case 6: - case 7: - $level = 1; - break; - default: - $level = 0; - break; - } - return $level; -} - -function convert_user($user) -{ - $user_data = array( - "user_id" => $user['id'], - "user_active" => ($user['enabled'] == 'yes') ? true : false, - "username" => $user['username'], - "user_password" => md5($user['password']), - "user_lastvisit" => $user['last_access'], - "user_regdate" => $user['added'], - "user_level" => tp_user_level($user['class']), - "user_lang" => $user['language'], - "user_dateformat" => "Y-m-d H:i", - "user_opt" => $user['opt'], // Added - "user_avatar" => !empty($user['avatar']) ? $user['avatar'] : null, - "user_avatar_type" => !empty($user['avatar']) ? 2 : null, - "user_email" => $user['email'], - "user_website" => $user['website'], - "user_icq" => $user['icq'], - "user_skype" => $user['skype'], - "user_twitter" => $user['twitter'], - "user_gender" => $user['gender'], - "user_birthday" => $user['user_birthday'], - ); - - $columns = $values = array(); - - foreach ($user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_USERS . " ($sql_columns) VALUES ($sql_values);"); - - $bt_user_data = array( - "user_id" => $user['id'], - "auth_key" => make_rand_str(BT_AUTH_KEY_LENGTH), - "u_up_total" => $user['uploaded'], - "u_down_total" => $user['downloaded'], - ); - $columns = $values = array(); - - foreach ($bt_user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_BT_USERS . " ($sql_bt_columns) VALUES ($sql_bt_values);"); -} - -//Torrents and categories functions -function tp_categories_cleanup() -{ - DB()->query('DELETE FROM '. BB_CATEGORIES); -} - -function tp_add_category_old($id, $cat_title) -{ - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES ." (cat_id, cat_title) - VALUES ($id, '". DB()->escape($cat_title) ."')"); - return; -} - -function tp_add_category($cat_data) -{ - $columns = $values = array(); - - foreach ($cat_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES . " ($sql_bt_columns) VALUES ($sql_bt_values);"); -} - -function tp_topics_cleanup() -{ - DB()->query("TRUNCATE ". BB_ATTACHMENTS); - DB()->query("TRUNCATE ". BB_ATTACHMENTS_DESC); - DB()->query("TRUNCATE ". BB_BT_TORRENTS); - DB()->query("TRUNCATE ". BB_POSTS); - DB()->query("TRUNCATE ". BB_POSTS_HTML); - DB()->query("TRUNCATE ". BB_POSTS_SEARCH); - DB()->query("TRUNCATE ". BB_POSTS_TEXT); - DB()->query("TRUNCATE ". BB_TOPICS); - - return; -} - -function tp_add_topic($topic_data) -{ - $columns = $values = array(); - foreach ($topic_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_TOPICS . " ($sql_columns) VALUES ($sql_values);"); - return; -} - -function tp_add_post($post_data) -{ - foreach ($post_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES ($sql_values);"); - } - return; -} - -function tp_add_attach($attach_data) -{ - foreach ($attach_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES ($sql_values);"); - } - return; -} - -function make_img_path ($name) -{ - global $bb_cfg; - - return make_url("files/images/" . $name); -} - -function append_images($tor) -{ - $poster = $screens = ''; - switch(TR_TYPE) - { - case 'yse': - if (!empty($tor['image1'])) - { - $poster = "[img=right]".make_img_path($tor['image1'])."[/img]"; - } - if (!empty($tor['image2'])) - { - $screens = '[spoiler="Скриншоты"][img]'.make_img_path($tor['image2'])."[/img][/spoiler]"; - } - break; - case 'sky': - if (!empty($tor['poster'])) - { - $poster = "[img=right]".make_img_path($tor['poster'])."[/img]"; - } - $has_screens = !empty($tor['screenshot1']) || !empty($tor['screenshot2']) || !empty($tor['screenshot3']) || !empty($tor['screenshot4']); - if ($has_screens) - { - $screens .= '[spoiler="Скриншоты"]'; - for ($i = 1; $i <= 4; $i++) - { - if (!empty($tor['screenshot'.$i])) - { - $screens .= "[img]".make_img_path($tor['screenshot'.$i])."[/img] \n"; - } - } - $screens .= "[/spoiler]"; - } - break; - } - return ($poster . $tor['descr'] . $screens); -} - -function convert_torrent($torrent) -{ - $topic_data = array( - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "topic_title" => $torrent['name'], - "topic_poster" => $torrent['owner'], - "topic_time" => $torrent['added'], - "topic_views" => $torrent['views'], - "topic_type" => ($torrent['sticky'] == 'yes') ? 1 : 0, - "topic_first_post_id" => $torrent['id'], - "topic_last_post_id" => $torrent['id'], - "topic_attachment" => 1, - "topic_dl_type" => 1, - "topic_last_post_time" => $torrent['added'], - ); - tp_add_topic($topic_data); - - $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); - - $post_data = array( - "posts" => array( - "post_id" => $torrent['post_id'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "poster_id" => $torrent['owner'], - "post_time" => $torrent['added'], - "post_attachment" => 1, - ), - "posts_text" => array( - "post_id" => $torrent['post_id'], - "post_text" => $post_text, - ), - "posts_search" => array( - "post_id" => $torrent['post_id'], - "search_words" => $torrent['search_text'], - ), - ); - tp_add_post($post_data); - - $attach_data = array( - "attachments" => array( - "attach_id" => $torrent['attach_id'], - "post_id" => $torrent['post_id'], - "user_id_1" => $torrent['owner'], - ), - "attachments_desc" => array( - "attach_id" => $torrent['attach_id'], - "physical_filename" => $torrent['id'] . ".torrent", - "real_filename" => $torrent['filename'], - "extension" => "torrent", - "mimetype" => "application/x-bittorrent", - "filesize" => @filesize(get_attachments_dir() .'/'. $torrent['id'] .".torrent"), - "filetime" => $torrent['added'], - "tracker_status" => 1, - ), - ); - tp_add_attach($attach_data); - - //Torrents - if (BDECODE) - { - $filename = get_attachments_dir() .'/'. $torrent['id'] .".torrent"; - if (!file_exists($filename)) - { - return; - } - if (!function_exists('bdecode_file')) include_once('./includes/functions_torrent.php'); - $tor = bdecode_file($filename); - $info = ($tor['info']) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - } - else - { - $info_hash_sql = hex2bin($torrent['info_hash']); - } - - $torrent_data = array( - "info_hash" => $info_hash_sql, - "post_id" => $torrent['post_id'], - "poster_id" => $torrent['owner'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "attach_id" => $torrent['attach_id'], - "size" => $torrent['size'], - "reg_time" => $torrent['added'], - "complete_count" => $torrent['times_completed'], - "seeder_last_seen" => $torrent['lastseed'], - ); - - $columns = $values = array(); - - foreach ($torrent_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(', ', $columns); - $sql_values = implode(', ', $values); - - DB()->query("INSERT IGNORE INTO ". BB_BT_TORRENTS . " ($sql_columns) VALUES($sql_values);"); - return; -} - -//Comments functions -function convert_comment($comment) -{ - $post_text = prepare_message($comment['text'], true, true); - - $post_data = array( - "posts" => array( - "post_id" => $comment['id'], - "topic_id" => $comment['torrent'], - "forum_id" => $comment['category'], - "poster_id" => $comment['user'], - "post_time" => $comment['added'], - "poster_ip" => encode_ip($comment['ip']), - "post_edit_time" => $comment['editedat'], - "post_edit_count" => $comment['editedat'] ? 1 : 0, - ), - "posts_text" => array( - "post_id" => $comment['id'], - "post_text" => $post_text, - ), - ); - tp_add_post($post_data); - return; -} - -//Forums functions -function tp_forums_cleanup() -{ - DB()->query('TRUNCATE '. BB_FORUMS); -} - -function convert_cat($forum, $allow_torrents = true) -{ - $forum_data = array( - "forum_id" => $forum['id'], - "cat_id" => $forum['cat_id'], - "forum_name" => $forum['name'], - "forum_order" => $forum['sort'], - "allow_reg_tracker" => $allow_torrents, - "allow_dl_topic" => $allow_torrents, - ); - - $columns = $values = array(); - - foreach ($forum_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); - - DB()->query("INSERT IGNORE INTO ". BB_FORUMS . " ($sql_columns) VALUES ($sql_values);"); - return; -} \ No newline at end of file diff --git a/install/other/recover/converter/passwords.php b/install/other/recover/converter/passwords.php deleted file mode 100644 index 63c2de744..000000000 --- a/install/other/recover/converter/passwords.php +++ /dev/null @@ -1,3 +0,0 @@ -session_start(); - -while (@ob_end_flush()); -ob_implicit_flush(); - -?> - - - - - - - - - -
        -
        - -
        -
        - - '; - - exit; -} -else -{ - -@ini_set('memory_limit', '512M'); -@ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); - -$torrents_count = (int) get_count(BB_BT_TORRENTS, 'attach_id'); -$loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); - -$not_exist = array(); - -$attach_dir = get_attachments_dir() .'/'; - -for ($i = 0; $i < $loops; $i++) -{ - $start = $i * C_TORRENTS_PER_ONCE; - $offset = C_TORRENTS_PER_ONCE; - - $sql = "SELECT - tor.attach_id, tor.topic_id, ad.physical_filename - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_ATTACHMENTS_DESC ." ad ON(ad.attach_id = tor.attach_id) - ORDER BY tor.attach_id - LIMIT $start, $offset"; - - $torrents = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); - - foreach ($torrents as $torrent) - { - $filename = $attach_dir . $torrent['physical_filename']; - if (!file_exists($filename)) - { - $not_exist[] = ''. $filename .''; - } - else - { - $tor = bdecode_file($filename); - $info = (!empty($tor['info'])) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - - DB()->query("UPDATE ". BB_BT_TORRENTS ." - SET info_hash = '$info_hash_sql' - WHERE attach_id = {$torrent['attach_id']}"); - } - } -} - -print_ok ("Completed"); - -if (!empty($not_exist)) -{ - print_ok ("These torrents doesn't exist in filesystem: ". implode(', ', array_unique($not_exist))); -} - -} \ No newline at end of file diff --git a/install/php-fpm+nginx/bash.txt b/install/php-fpm+nginx/bash.txt deleted file mode 100644 index 0cb7a314b..000000000 --- a/install/php-fpm+nginx/bash.txt +++ /dev/null @@ -1,5 +0,0 @@ -$ mkdir /tmp/nginx -$ mkdir /tmp/nginx/fastcgi_temp -$ mkdir /tmp/nginx/client_temp - -$ mkdir /var/log/nginx/ \ No newline at end of file diff --git a/install/php-fpm+nginx/fastcgi_params b/install/php-fpm+nginx/fastcgi_params deleted file mode 100644 index 425b73424..000000000 --- a/install/php-fpm+nginx/fastcgi_params +++ /dev/null @@ -1,31 +0,0 @@ -fastcgi_connect_timeout 60; -fastcgi_send_timeout 180; -fastcgi_read_timeout 180; -fastcgi_buffer_size 32k; -fastcgi_buffers 4 32k; -fastcgi_busy_buffers_size 32k; -fastcgi_temp_file_write_size 32k; -fastcgi_temp_path /tmp/nginx/fastcgi_temp 1 2; - -fastcgi_param QUERY_STRING $query_string; -fastcgi_param REQUEST_METHOD $request_method; -fastcgi_param CONTENT_TYPE $content_type; -fastcgi_param CONTENT_LENGTH $content_length; - -fastcgi_param SCRIPT_NAME $fastcgi_script_name; -fastcgi_param REQUEST_URI $request_uri; -fastcgi_param DOCUMENT_URI $document_uri; -fastcgi_param DOCUMENT_ROOT $document_root; -fastcgi_param SERVER_PROTOCOL $server_protocol; - -fastcgi_param GATEWAY_INTERFACE CGI/1.1; -fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; - -fastcgi_param REMOTE_ADDR $remote_addr; -fastcgi_param REMOTE_PORT $remote_port; -fastcgi_param SERVER_ADDR $server_addr; -fastcgi_param SERVER_PORT $server_port; -fastcgi_param SERVER_NAME $server_name; - -# PHP only, required if PHP was built with --enable-force-cgi-redirect -fastcgi_param REDIRECT_STATUS 200; \ No newline at end of file diff --git a/install/php-fpm+nginx/nginx.conf b/install/php-fpm+nginx/nginx.conf deleted file mode 100644 index 1e24a39a0..000000000 --- a/install/php-fpm+nginx/nginx.conf +++ /dev/null @@ -1,154 +0,0 @@ -user www www; -worker_processes auto; - -#error_log /var/log/nginx/error.log; -#error_log /var/log/nginx/error.log notice; -#error_log /var/log/nginx/error.log info; - -pid /var/run/nginx.pid; - -worker_rlimit_nofile 1024; -events { - worker_connections 1024; -} - -http { - include mime.types; - default_type application/octet-stream; - - #log_format main '$remote_addr - $remote_user [$time_local] $request ' - # '"$status" $body_bytes_sent "$http_referer" ' - # '"$http_user_agent" "$http_x_forwarded_for"'; - - #log_format IP .$remote_addr.; - - access_log off; - - server_tokens off; - reset_timedout_connection on; - - sendfile on; - - # http://en.wikipedia.org/wiki/Asynchronous_I/O - # aio sendfile; - - output_buffers 1 64k; - - tcp_nopush on; - tcp_nodelay on; - send_lowat 12000; - log_not_found off; - - keepalive_timeout 65; - - limit_req_zone $binary_remote_addr zone=one:16m rate=5r/s; - - gzip on; - gzip_vary on; - gzip_min_length 2048; - gzip_comp_level 5; - gzip_http_version 1.0; - gzip_proxied any; - gzip_disable "msie6"; - gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript; - - client_max_body_size 10m; - large_client_header_buffers 4 8k; - client_body_temp_path /tmp/nginx/client_temp 1 2; - - server { - #listen 80 default sndbuf=32k rcvbuf=8k accept_filter=httpready; - #listen [::]:80 default sndbuf=32k rcvbuf=8k accept_filter=httpready; - - listen 80 default sndbuf=32k rcvbuf=8k; - server_name sitedomain.ru; - - charset utf8; - - access_log off; - - location / { - root /var/www; - index index.php index.html index.htm; - } - - error_page 404 /404.html; - error_page 500 502 503 504 /50x.html; - - # pass the PHP scripts to FastCGI server listening on /tmp/php.sock - location ~ \.php$ { - #limit_req zone=one burst=20 nodelay; - #limit_req_log_level info; - - root /var/www; - fastcgi_index index.php; - fastcgi_pass unix:/tmp/php.sock; # 127.0.0.1:9000; - fastcgi_intercept_errors on; - - # FreeBSD Optimization - fastcgi_pass_request_body off; - client_body_in_file_only clean; - fastcgi_param REQUEST_BODY_FILE $request_body_file; - - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name; - - include fastcgi_params; - } - - # rewrite to XBTT (old) -# location ^~ /bt/ { -# access_log off; -# if ( $query_string ~ "^uk=([^&?]{10})[&?]+(.*)$" ) { -# set $uk $1; -# set $qs $2&ip=$remote_addr; -# } -# if ( $query_string ~ "^uk=([^&?]{10})[&?]+((.*&|)ip=.*)$" ) { -# set $uk $1; -# set $qs $2; -# } -# if ( $qs ) { -# rewrite ^.*/([a-z]+)(\.php|)$ /$uk/$1?$qs break; -# } -# rewrite ^/?(.*)$ /$1?ip=$remote_addr&$query_string break; -# proxy_pass http://127.0.0.1:2710/; -# } - - # cache static files - location ~* \.(jpg|jpeg|gif|png|css|js|ico)$ { - root /var/www; - access_log off; - expires 30d; - add_header Cache-Control public; - } - - # sitemap rewrite - rewrite ^/sitemap.xml$ /internal_data/sitemap/sitemap.xml; - - # deny access to admin folder - location ~ \/admin|backup\/ { - deny all; - #allow YOUR_IP; - } - - # deny access to system folder - location ~ \/(install|internal_data|library)\/ { - deny all; - } - - # deny access to git folder - location ~ /\.git { - deny all; - } - - # deny access to .htaccess, if apache's document root concurs with nginx's one - location ~ /\.ht { - deny all; - } - - # deny access to critical files - location ~ \.(.*sql|tpl|db|inc|log|md)$ { - deny all; - } - } -} \ No newline at end of file diff --git a/install/sphinx/sphinx.conf b/install/sphinx/sphinx.conf deleted file mode 100644 index d29033d81..000000000 --- a/install/sphinx/sphinx.conf +++ /dev/null @@ -1,104 +0,0 @@ -source torrentpier -{ - type = mysql - sql_host = localhost - sql_user = user - sql_pass = pass - sql_db = dbase - sql_query_pre = SET NAMES utf8 - sql_query_pre = SET CHARACTER_SET_RESULTS=utf8 - sql_query_pre = SET CHARACTER_SET_CLIENT=utf8 -} - -source topics: torrentpier -{ - sql_query = \ - SELECT topic_id, forum_id, topic_title \ - FROM bb_topics \ - WHERE topic_id BETWEEN $start AND $end - - sql_query_range = SELECT MIN(topic_id), MAX(topic_id) FROM bb_topics - sql_range_step = 100000 - - sql_attr_uint = forum_id - sql_ranged_throttle = 50 - sql_query_info = SELECT * FROM bb_topics WHERE topic_id = $id -} - -source posts: torrentpier -{ - sql_query = \ - SELECT pt.post_id, pt.post_text, t.topic_title, t.topic_id, t.forum_id \ - FROM bb_posts_text pt \ - LEFT JOIN bb_topics t on pt.post_id = t.topic_first_post_id \ - WHERE pt.post_id BETWEEN $start AND $end - - sql_query_range = SELECT MIN(post_id), MAX(post_id) FROM bb_posts_text - sql_range_step = 100000 - - sql_attr_uint = topic_id - sql_attr_uint = forum_id - sql_ranged_throttle = 50 - sql_query_info = SELECT * FROM bb_posts_text WHERE post_id = $id -} - -source users: torrentpier -{ - sql_query = \ - SELECT user_id, username \ - FROM bb_users \ - WHERE user_id BETWEEN $start AND $end - - sql_query_range = SELECT 1, MAX(user_id) FROM bb_users - sql_range_step = 1000 - sql_query_info = SELECT * FROM bb_users WHERE user_id = $id -} - -index topics -{ - docinfo = extern - morphology = stem_enru - charset_type = utf-8 - charset_table = 0..9, A..Z->a..z, _, a..z, U+410..U+42C->U+430..U+44C, U+42E..U+42F->U+44E..U+44F, U+430..U+44C, U+44E..U+44F, U+0401->U+0435, U+0451->U+0435, U+042D->U+0435, U+044D->U+0435 - min_prefix_len = 0 - min_infix_len = 0 - min_word_len = 1 - min_stemming_len = 4 - enable_star = 1 - phrase_boundary = :, - , . , $ - phrase_boundary_step = 1 - html_strip = 1 - path = ./sphinx/data/topics - source = topics -} - -index posts: topics -{ - path = ./sphinx/data/posts - source = posts -} - -index users: topics -{ - path = ./sphinx/data/users - source = users -} - -indexer -{ - mem_limit = 256M -} - -searchd -{ - listen = 127.0.0.1:3312 - log = ./sphinx/log/searchd.log - query_log = ./sphinx/log/query.log - read_timeout = 5 - max_children = 15 - max_matches = 5000 - seamless_rotate = 1 - preopen_indexes = 0 - unlink_old = 1 - pid_file = ./sphinx/searchd.pid -} \ No newline at end of file diff --git a/install/sql/mysql.sql b/install/sql/mysql.sql deleted file mode 100644 index 186a10624..000000000 --- a/install/sql/mysql.sql +++ /dev/null @@ -1,1277 +0,0 @@ -SET SQL_MODE = ""; - --- ---------------------------- --- Table structure for `bb_ads` --- ---------------------------- -DROP TABLE IF EXISTS `bb_ads`; -CREATE TABLE IF NOT EXISTS `bb_ads` ( - `ad_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `ad_block_ids` varchar(255) NOT NULL DEFAULT '', - `ad_start_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `ad_active_days` smallint(6) NOT NULL DEFAULT '0', - `ad_status` tinyint(4) NOT NULL DEFAULT '1', - `ad_desc` varchar(255) NOT NULL DEFAULT '', - `ad_html` text NOT NULL, - PRIMARY KEY (`ad_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_ads --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_attachments` --- ---------------------------- -DROP TABLE IF EXISTS `bb_attachments`; -CREATE TABLE IF NOT EXISTS `bb_attachments` ( - `attach_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id_1` mediumint(8) NOT NULL DEFAULT '0', - PRIMARY KEY (`attach_id`,`post_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_attachments --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_attachments_config` --- ---------------------------- -DROP TABLE IF EXISTS `bb_attachments_config`; -CREATE TABLE IF NOT EXISTS `bb_attachments_config` ( - `config_name` varchar(255) NOT NULL DEFAULT '', - `config_value` varchar(255) NOT NULL DEFAULT '', - PRIMARY KEY (`config_name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_attachments_config --- ---------------------------- -INSERT INTO `bb_attachments_config` VALUES ('upload_dir', 'data/old_files'); -INSERT INTO `bb_attachments_config` VALUES ('upload_img', 'styles/images/icon_clip.gif'); -INSERT INTO `bb_attachments_config` VALUES ('topic_icon', 'styles/images/icon_clip.gif'); -INSERT INTO `bb_attachments_config` VALUES ('display_order', '0'); -INSERT INTO `bb_attachments_config` VALUES ('max_filesize', '262144'); -INSERT INTO `bb_attachments_config` VALUES ('attachment_quota', '52428800'); -INSERT INTO `bb_attachments_config` VALUES ('max_filesize_pm', '262144'); -INSERT INTO `bb_attachments_config` VALUES ('max_attachments', '1'); -INSERT INTO `bb_attachments_config` VALUES ('max_attachments_pm', '1'); -INSERT INTO `bb_attachments_config` VALUES ('disable_mod', '0'); -INSERT INTO `bb_attachments_config` VALUES ('allow_pm_attach', '1'); -INSERT INTO `bb_attachments_config` VALUES ('attach_version', '2.3.14'); -INSERT INTO `bb_attachments_config` VALUES ('default_upload_quota', '0'); -INSERT INTO `bb_attachments_config` VALUES ('default_pm_quota', '0'); -INSERT INTO `bb_attachments_config` VALUES ('img_display_inlined', '1'); -INSERT INTO `bb_attachments_config` VALUES ('img_max_width', '200'); -INSERT INTO `bb_attachments_config` VALUES ('img_max_height', '200'); -INSERT INTO `bb_attachments_config` VALUES ('img_link_width', '0'); -INSERT INTO `bb_attachments_config` VALUES ('img_link_height', '0'); -INSERT INTO `bb_attachments_config` VALUES ('img_create_thumbnail', '0'); -INSERT INTO `bb_attachments_config` VALUES ('img_min_thumb_filesize', '12000'); -INSERT INTO `bb_attachments_config` VALUES ('img_imagick', '/usr/bin/convert'); -INSERT INTO `bb_attachments_config` VALUES ('use_gd2', '1'); -INSERT INTO `bb_attachments_config` VALUES ('wma_autoplay', '0'); -INSERT INTO `bb_attachments_config` VALUES ('flash_autoplay', '0'); - --- ---------------------------- --- Table structure for `bb_attachments_desc` --- ---------------------------- -DROP TABLE IF EXISTS `bb_attachments_desc`; -CREATE TABLE IF NOT EXISTS `bb_attachments_desc` ( - `attach_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `physical_filename` varchar(255) NOT NULL DEFAULT '', - `real_filename` varchar(255) NOT NULL DEFAULT '', - `download_count` mediumint(8) unsigned NOT NULL DEFAULT '0', - `comment` varchar(255) NOT NULL DEFAULT '', - `extension` varchar(100) NOT NULL DEFAULT '', - `mimetype` varchar(100) NOT NULL DEFAULT '', - `filesize` int(20) NOT NULL DEFAULT '0', - `filetime` int(11) NOT NULL DEFAULT '0', - `thumbnail` tinyint(1) NOT NULL DEFAULT '0', - `tracker_status` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`attach_id`), - KEY `filetime` (`filetime`), - KEY `filesize` (`filesize`), - KEY `physical_filename` (`physical_filename`(10)) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_attachments_desc --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_attach_quota` --- ---------------------------- -DROP TABLE IF EXISTS `bb_attach_quota`; -CREATE TABLE IF NOT EXISTS `bb_attach_quota` ( - `user_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `group_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `quota_type` smallint(2) NOT NULL DEFAULT '0', - `quota_limit_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - KEY `quota_type` (`quota_type`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_attach_quota --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_auth_access` --- ---------------------------- -DROP TABLE IF EXISTS `bb_auth_access`; -CREATE TABLE IF NOT EXISTS `bb_auth_access` ( - `group_id` mediumint(8) NOT NULL DEFAULT '0', - `forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `forum_perm` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`group_id`,`forum_id`), - KEY `forum_id` (`forum_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_auth_access --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_auth_access_snap` --- ---------------------------- -DROP TABLE IF EXISTS `bb_auth_access_snap`; -CREATE TABLE IF NOT EXISTS `bb_auth_access_snap` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `forum_id` smallint(6) NOT NULL DEFAULT '0', - `forum_perm` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`user_id`,`forum_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_auth_access_snap --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_banlist` --- ---------------------------- -DROP TABLE IF EXISTS `bb_banlist`; -CREATE TABLE IF NOT EXISTS `bb_banlist` ( - `ban_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `ban_userid` mediumint(8) NOT NULL DEFAULT '0', - `ban_ip` varchar(32) NOT NULL DEFAULT '', - `ban_email` varchar(255) NOT NULL DEFAULT '', - PRIMARY KEY (`ban_id`), - KEY `ban_ip_user_id` (`ban_ip`,`ban_userid`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_banlist --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_dlstatus` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_dlstatus`; -CREATE TABLE IF NOT EXISTS `bb_bt_dlstatus` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_status` tinyint(1) NOT NULL DEFAULT '0', - `last_modified_dlstatus` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`user_id`,`topic_id`), - KEY `topic_id` (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_dlstatus --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_dlstatus_snap` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_dlstatus_snap`; -CREATE TABLE IF NOT EXISTS `bb_bt_dlstatus_snap` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `dl_status` tinyint(4) NOT NULL DEFAULT '0', - `users_count` smallint(5) unsigned NOT NULL DEFAULT '0', - KEY `topic_id` (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_dlstatus_snap --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_last_torstat` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_last_torstat`; -CREATE TABLE IF NOT EXISTS `bb_bt_last_torstat` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `dl_status` tinyint(1) NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `release_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `bonus_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_down` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) USING BTREE -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_last_torstat --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_last_userstat` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_last_userstat`; -CREATE TABLE IF NOT EXISTS `bb_bt_last_userstat` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `release_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `bonus_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_down` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_last_userstat --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_torhelp` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_torhelp`; -CREATE TABLE IF NOT EXISTS `bb_bt_torhelp` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `topic_id_csv` text NOT NULL, - PRIMARY KEY (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_torhelp --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_torrents` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_torrents`; -CREATE TABLE IF NOT EXISTS `bb_bt_torrents` ( - `info_hash` varbinary(20) NOT NULL DEFAULT '', - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `poster_id` mediumint(9) NOT NULL DEFAULT '0', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `attach_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `size` bigint(20) unsigned NOT NULL DEFAULT '0', - `reg_time` int(11) NOT NULL DEFAULT '0', - `call_seed_time` int(11) NOT NULL DEFAULT '0', - `complete_count` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeder_last_seen` int(11) NOT NULL DEFAULT '0', - `tor_status` tinyint(4) NOT NULL DEFAULT '0', - `checked_user_id` mediumint(8) NOT NULL DEFAULT '0', - `checked_time` int(11) NOT NULL DEFAULT '0', - `tor_type` tinyint(1) NOT NULL DEFAULT '0', - `speed_up` int(11) NOT NULL DEFAULT '0', - `speed_down` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`info_hash`), - UNIQUE KEY `post_id` (`post_id`), - UNIQUE KEY `topic_id` (`topic_id`), - UNIQUE KEY `attach_id` (`attach_id`), - KEY `reg_time` (`reg_time`), - KEY `forum_id` (`forum_id`), - KEY `poster_id` (`poster_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_torrents --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_torstat` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_torstat`; -CREATE TABLE IF NOT EXISTS `bb_bt_torstat` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `last_modified_torstat` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `completed` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_torstat --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_tor_dl_stat` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_tor_dl_stat`; -CREATE TABLE IF NOT EXISTS `bb_bt_tor_dl_stat` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `attach_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `t_up_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `t_down_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `t_bonus_total` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_tor_dl_stat --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_tracker` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_tracker`; -CREATE TABLE IF NOT EXISTS `bb_bt_tracker` ( - `peer_hash` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `peer_id` varchar(20) NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `ip` char(8) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '0', - `ipv6` varchar(32) DEFAULT NULL, - `port` smallint(5) unsigned NOT NULL DEFAULT '0', - `client` varchar(51) NOT NULL DEFAULT 'Unknown', - `seeder` tinyint(1) NOT NULL DEFAULT '0', - `releaser` tinyint(1) NOT NULL DEFAULT '0', - `tor_type` tinyint(1) NOT NULL DEFAULT '0', - `uploaded` bigint(20) unsigned NOT NULL DEFAULT '0', - `downloaded` bigint(20) unsigned NOT NULL DEFAULT '0', - `remain` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` mediumint(8) unsigned NOT NULL DEFAULT '0', - `speed_down` mediumint(8) unsigned NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `update_time` int(11) NOT NULL DEFAULT '0', - `complete_percent` bigint(20) NOT NULL DEFAULT '0', - `complete` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`peer_hash`), - KEY `topic_id` (`topic_id`), - KEY `user_id` (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_tracker --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_tracker_snap` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_tracker_snap`; -CREATE TABLE IF NOT EXISTS `bb_bt_tracker_snap` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeders` mediumint(8) unsigned NOT NULL DEFAULT '0', - `leechers` mediumint(8) unsigned NOT NULL DEFAULT '0', - `speed_up` int(10) unsigned NOT NULL DEFAULT '0', - `speed_down` int(10) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_tracker_snap --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_users` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_users`; -CREATE TABLE IF NOT EXISTS `bb_bt_users` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `auth_key` char(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `u_up_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `u_down_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `u_up_release` bigint(20) unsigned NOT NULL DEFAULT '0', - `u_up_bonus` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_release_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_bonus_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `points_today` float(16,2) unsigned NOT NULL DEFAULT '0.00', - `up_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_release_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_bonus_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `points_yesterday` float(16,2) unsigned NOT NULL DEFAULT '0.00', - PRIMARY KEY (`user_id`), - UNIQUE KEY `auth_key` (`auth_key`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_users --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_user_settings` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_user_settings`; -CREATE TABLE IF NOT EXISTS `bb_bt_user_settings` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `tor_search_set` text NOT NULL, - `last_modified` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_user_settings --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_captcha` --- ---------------------------- -DROP TABLE IF EXISTS `bb_captcha`; -CREATE TABLE IF NOT EXISTS `bb_captcha` ( - `cap_id` int(10) NOT NULL DEFAULT '0', - `cap_code` char(6) NOT NULL DEFAULT '', - `cap_expire` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`cap_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_captcha --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_categories` --- ---------------------------- -DROP TABLE IF EXISTS `bb_categories`; -CREATE TABLE IF NOT EXISTS `bb_categories` ( - `cat_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `cat_title` varchar(100) NOT NULL DEFAULT '', - `cat_order` smallint(5) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`cat_id`), - KEY `cat_order` (`cat_order`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_categories --- ---------------------------- -INSERT INTO `bb_categories` VALUES ('1', 'Ваша первая категория', '10'); - --- ---------------------------- --- Table structure for `bb_config` --- ---------------------------- -DROP TABLE IF EXISTS `bb_config`; -CREATE TABLE IF NOT EXISTS `bb_config` ( - `config_name` varchar(255) NOT NULL DEFAULT '', - `config_value` text NOT NULL, - PRIMARY KEY (`config_name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_config --- ---------------------------- -INSERT INTO `bb_config` VALUES ('allow_autologin', '1'); -INSERT INTO `bb_config` VALUES ('allow_bbcode', '1'); -INSERT INTO `bb_config` VALUES ('allow_namechange', '0'); -INSERT INTO `bb_config` VALUES ('allow_sig', '1'); -INSERT INTO `bb_config` VALUES ('allow_smilies', '1'); -INSERT INTO `bb_config` VALUES ('board_disable', '0'); -INSERT INTO `bb_config` VALUES ('board_startdate', UNIX_TIMESTAMP()); -INSERT INTO `bb_config` VALUES ('board_timezone', '0'); -INSERT INTO `bb_config` VALUES ('bonus_upload', ''); -INSERT INTO `bb_config` VALUES ('bonus_upload_price', ''); -INSERT INTO `bb_config` VALUES ('birthday_enabled', '1'); -INSERT INTO `bb_config` VALUES ('birthday_max_age', '99'); -INSERT INTO `bb_config` VALUES ('birthday_min_age', '10'); -INSERT INTO `bb_config` VALUES ('birthday_check_day', '7'); -INSERT INTO `bb_config` VALUES ('bt_add_auth_key', '1'); -INSERT INTO `bb_config` VALUES ('bt_allow_spmode_change', '1'); -INSERT INTO `bb_config` VALUES ('bt_announce_url', 'https://demo.torrentpier.me/bt/announce.php'); -INSERT INTO `bb_config` VALUES ('bt_disable_dht', '0'); -INSERT INTO `bb_config` VALUES ('bt_check_announce_url', '0'); -INSERT INTO `bb_config` VALUES ('bt_del_addit_ann_urls', '1'); -INSERT INTO `bb_config` VALUES ('bt_dl_list_only_1st_page', '1'); -INSERT INTO `bb_config` VALUES ('bt_dl_list_only_count', '1'); -INSERT INTO `bb_config` VALUES ('bt_newtopic_auto_reg', '1'); -INSERT INTO `bb_config` VALUES ('bt_replace_ann_url', '1'); -INSERT INTO `bb_config` VALUES ('bt_search_bool_mode', '1'); -INSERT INTO `bb_config` VALUES ('bt_set_dltype_on_tor_reg', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_but_cancel', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_but_compl', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_but_down', '0'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_but_will', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_list', '0'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_list_buttons', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_dl_stat_on_index', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_ip_only_moder', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_peers', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_peers_mode', '1'); -INSERT INTO `bb_config` VALUES ('bt_show_port_only_moder', '1'); -INSERT INTO `bb_config` VALUES ('bt_tor_browse_only_reg', '0'); -INSERT INTO `bb_config` VALUES ('bt_unset_dltype_on_tor_unreg', '1'); -INSERT INTO `bb_config` VALUES ('cron_last_check', '0'); -INSERT INTO `bb_config` VALUES ('default_dateformat', 'Y-m-d H:i'); -INSERT INTO `bb_config` VALUES ('default_lang', 'ru'); -INSERT INTO `bb_config` VALUES ('flood_interval', '15'); -INSERT INTO `bb_config` VALUES ('hot_threshold', '300'); -INSERT INTO `bb_config` VALUES ('login_reset_time', '30'); -INSERT INTO `bb_config` VALUES ('max_autologin_time', '10'); -INSERT INTO `bb_config` VALUES ('max_login_attempts', '5'); -INSERT INTO `bb_config` VALUES ('max_poll_options', '6'); -INSERT INTO `bb_config` VALUES ('max_sig_chars', '255'); -INSERT INTO `bb_config` VALUES ('posts_per_page', '15'); -INSERT INTO `bb_config` VALUES ('prune_enable', '1'); -INSERT INTO `bb_config` VALUES ('record_online_date', UNIX_TIMESTAMP()); -INSERT INTO `bb_config` VALUES ('record_online_users', '0'); -INSERT INTO `bb_config` VALUES ('seed_bonus_enabled', '1'); -INSERT INTO `bb_config` VALUES ('seed_bonus_release', ''); -INSERT INTO `bb_config` VALUES ('seed_bonus_points', ''); -INSERT INTO `bb_config` VALUES ('seed_bonus_tor_size', '0'); -INSERT INTO `bb_config` VALUES ('seed_bonus_user_regdate', '0'); -INSERT INTO `bb_config` VALUES ('site_desc', 'A little text to describe your forum'); -INSERT INTO `bb_config` VALUES ('sitemap_time', ''); -INSERT INTO `bb_config` VALUES ('sitename', 'TorrentPier II - Torrent Tracker'); -INSERT INTO `bb_config` VALUES ('smilies_path', 'styles/images/smiles'); -INSERT INTO `bb_config` VALUES ('static_sitemap', ''); -INSERT INTO `bb_config` VALUES ('topics_per_page', '50'); -INSERT INTO `bb_config` VALUES ('xs_use_cache', '1'); -INSERT INTO `bb_config` VALUES ('active_ads', ''); -INSERT INTO `bb_config` VALUES ('cron_enabled', '1'); -INSERT INTO `bb_config` VALUES ('cron_check_interval', '180'); -INSERT INTO `bb_config` VALUES ('magnet_links_enabled', '1'); -INSERT INTO `bb_config` VALUES ('gender', '1'); -INSERT INTO `bb_config` VALUES ('callseed', '0'); -INSERT INTO `bb_config` VALUES ('tor_stats', '1'); -INSERT INTO `bb_config` VALUES ('show_latest_news', '1'); -INSERT INTO `bb_config` VALUES ('max_news_title', '50'); -INSERT INTO `bb_config` VALUES ('latest_news_count', '5'); -INSERT INTO `bb_config` VALUES ('latest_news_forum_id', '1'); -INSERT INTO `bb_config` VALUES ('show_network_news', '1'); -INSERT INTO `bb_config` VALUES ('max_net_title', '50'); -INSERT INTO `bb_config` VALUES ('network_news_count', '5'); -INSERT INTO `bb_config` VALUES ('network_news_forum_id', '2'); -INSERT INTO `bb_config` VALUES ('whois_info', 'http://ip-whois.net/ip_geos.php?ip='); -INSERT INTO `bb_config` VALUES ('show_mod_index', '0'); -INSERT INTO `bb_config` VALUES ('premod', '0'); -INSERT INTO `bb_config` VALUES ('new_tpls', '1'); -INSERT INTO `bb_config` VALUES ('tor_comment', '1'); -INSERT INTO `bb_config` VALUES ('terms', ''); - --- ---------------------------- --- Table structure for `bb_cron` --- ---------------------------- -DROP TABLE IF EXISTS `bb_cron`; -CREATE TABLE IF NOT EXISTS `bb_cron` ( - `cron_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `cron_active` tinyint(4) NOT NULL DEFAULT '1', - `cron_title` char(120) NOT NULL DEFAULT '', - `cron_script` char(120) NOT NULL DEFAULT '', - `schedule` enum('hourly','daily','weekly','monthly','interval') NOT NULL DEFAULT 'daily', - `run_day` enum('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28') DEFAULT NULL, - `run_time` time DEFAULT '04:00:00', - `run_order` tinyint(4) unsigned NOT NULL DEFAULT '0', - `last_run` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `next_run` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `run_interval` time DEFAULT NULL DEFAULT '0', - `log_enabled` tinyint(1) NOT NULL DEFAULT '0', - `log_file` char(120) NOT NULL DEFAULT '', - `log_sql_queries` tinyint(4) NOT NULL DEFAULT '0', - `disable_board` tinyint(1) NOT NULL DEFAULT '0', - `run_counter` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`cron_id`), - UNIQUE KEY `title` (`cron_title`), - UNIQUE KEY `script` (`cron_script`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_cron --- ---------------------------- -INSERT INTO `bb_cron` VALUES ('', '1', 'Attach maintenance', 'attach_maintenance.php', 'daily', '', '05:00:00', '40', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Board maintenance', 'board_maintenance.php', 'daily', '', '05:00:00', '40', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Prune forums', 'prune_forums.php', 'daily', '', '05:00:00', '50', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Prune topic moved stubs', 'prune_topic_moved.php', 'daily', '', '05:00:00', '60', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Logs cleanup', 'clean_log.php', 'daily', '', '05:00:00', '70', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker maintenance', 'tr_maintenance.php', 'daily', '', '05:00:00', '90', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Clean dlstat', 'clean_dlstat.php', 'daily', '', '05:00:00', '100', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Prune inactive users', 'prune_inactive_users.php', 'daily', '', '05:00:00', '110', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Sessions cleanup', 'sessions_cleanup.php', 'interval', '', '', '255', '', '', '00:03:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'DS update cat_forums', 'ds_update_cat_forums.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'DS update stats', 'ds_update_stats.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Flash topic view', 'flash_topic_view.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Clean search results', 'clean_search_results.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker cleanup and dlstat', 'tr_cleanup_and_dlstat.php', 'interval', '', '', '20', '', '', '00:15:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Make tracker snapshot', 'tr_make_snapshot.php', 'interval', '', '', '10', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Seeder last seen', 'tr_update_seeder_last_seen.php', 'interval', '', '', '255', '', '', '01:00:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Captcha', 'captcha_gen_gc.php', 'daily', '', '05:00:00', '120', '', '', '', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker dl-complete count', 'tr_complete_count.php', 'interval', '', '', '255', '', '', '06:00:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Cache garbage collector', 'cache_gc.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Sitemap update', 'sitemap.php', 'daily', '', '06:00:00', '30', '', '', '', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Update forums atom', 'update_forums_atom.php', 'interval', '', '', '255', '', '', '00:15:00', '0', '', '0', '0', '0'); - --- ---------------------------- --- Table structure for `bb_disallow` --- ---------------------------- -DROP TABLE IF EXISTS `bb_disallow`; -CREATE TABLE IF NOT EXISTS `bb_disallow` ( - `disallow_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `disallow_username` varchar(25) NOT NULL DEFAULT '', - PRIMARY KEY (`disallow_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_disallow --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_extensions` --- ---------------------------- -DROP TABLE IF EXISTS `bb_extensions`; -CREATE TABLE IF NOT EXISTS `bb_extensions` ( - `ext_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `group_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `extension` varchar(100) NOT NULL DEFAULT '', - `comment` varchar(100) NOT NULL DEFAULT '', - PRIMARY KEY (`ext_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_extensions --- ---------------------------- -INSERT INTO `bb_extensions` VALUES ('', '1', 'gif', ''); -INSERT INTO `bb_extensions` VALUES ('', '1', 'png', ''); -INSERT INTO `bb_extensions` VALUES ('', '1', 'jpeg', ''); -INSERT INTO `bb_extensions` VALUES ('', '1', 'jpg', ''); -INSERT INTO `bb_extensions` VALUES ('', '1', 'tif', ''); -INSERT INTO `bb_extensions` VALUES ('', '1', 'tga', ''); -INSERT INTO `bb_extensions` VALUES ('', '2', 'gtar', ''); -INSERT INTO `bb_extensions` VALUES ('', '2', 'gz', ''); -INSERT INTO `bb_extensions` VALUES ('', '2', 'tar', ''); -INSERT INTO `bb_extensions` VALUES ('', '2', 'zip', ''); -INSERT INTO `bb_extensions` VALUES ('', '2', 'rar', ''); -INSERT INTO `bb_extensions` VALUES ('', '2', 'ace', ''); -INSERT INTO `bb_extensions` VALUES ('', '3', 'txt', ''); -INSERT INTO `bb_extensions` VALUES ('', '3', 'c', ''); -INSERT INTO `bb_extensions` VALUES ('', '3', 'h', ''); -INSERT INTO `bb_extensions` VALUES ('', '3', 'cpp', ''); -INSERT INTO `bb_extensions` VALUES ('', '3', 'hpp', ''); -INSERT INTO `bb_extensions` VALUES ('', '3', 'diz', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'xls', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'doc', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'dot', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'pdf', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'ai', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'ps', ''); -INSERT INTO `bb_extensions` VALUES ('', '4', 'ppt', ''); -INSERT INTO `bb_extensions` VALUES ('', '5', 'rm', ''); -INSERT INTO `bb_extensions` VALUES ('', '6', 'torrent', ''); - --- ---------------------------- --- Table structure for `bb_extension_groups` --- ---------------------------- -DROP TABLE IF EXISTS `bb_extension_groups`; -CREATE TABLE IF NOT EXISTS `bb_extension_groups` ( - `group_id` mediumint(8) NOT NULL AUTO_INCREMENT, - `group_name` varchar(20) NOT NULL DEFAULT '', - `cat_id` tinyint(2) NOT NULL DEFAULT '0', - `allow_group` tinyint(1) NOT NULL DEFAULT '0', - `download_mode` tinyint(1) unsigned NOT NULL DEFAULT '1', - `upload_icon` varchar(100) NOT NULL DEFAULT '', - `max_filesize` int(20) NOT NULL DEFAULT '0', - `forum_permissions` text NOT NULL, - PRIMARY KEY (`group_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_extension_groups --- ---------------------------- -INSERT INTO `bb_extension_groups` VALUES ('', 'Images', '1', '1', '1', '', '262144', ''); -INSERT INTO `bb_extension_groups` VALUES ('', 'Archives', '0', '1', '1', '', '262144', ''); -INSERT INTO `bb_extension_groups` VALUES ('', 'Plain text', '0', '0', '1', '', '262144', ''); -INSERT INTO `bb_extension_groups` VALUES ('', 'Documents', '0', '0', '1', '', '262144', ''); -INSERT INTO `bb_extension_groups` VALUES ('', 'Real media', '0', '0', '2', '', '262144', ''); -INSERT INTO `bb_extension_groups` VALUES ('', 'Torrent', '0', '1', '1', '', '122880', ''); - --- ---------------------------- --- Table structure for `bb_forums` --- ---------------------------- -DROP TABLE IF EXISTS `bb_forums`; -CREATE TABLE IF NOT EXISTS `bb_forums` ( - `forum_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `cat_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `forum_name` varchar(150) NOT NULL DEFAULT '', - `forum_desc` text NOT NULL, - `forum_status` tinyint(4) NOT NULL DEFAULT '0', - `forum_order` smallint(5) unsigned NOT NULL DEFAULT '1', - `forum_posts` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_topics` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_last_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_tpl_id` smallint(6) NOT NULL DEFAULT '0', - `prune_days` smallint(5) unsigned NOT NULL DEFAULT '0', - `auth_view` tinyint(2) NOT NULL DEFAULT '0', - `auth_read` tinyint(2) NOT NULL DEFAULT '0', - `auth_post` tinyint(2) NOT NULL DEFAULT '0', - `auth_reply` tinyint(2) NOT NULL DEFAULT '0', - `auth_edit` tinyint(2) NOT NULL DEFAULT '0', - `auth_delete` tinyint(2) NOT NULL DEFAULT '0', - `auth_sticky` tinyint(2) NOT NULL DEFAULT '0', - `auth_announce` tinyint(2) NOT NULL DEFAULT '0', - `auth_vote` tinyint(2) NOT NULL DEFAULT '0', - `auth_pollcreate` tinyint(2) NOT NULL DEFAULT '0', - `auth_attachments` tinyint(2) NOT NULL DEFAULT '0', - `auth_download` tinyint(2) NOT NULL DEFAULT '0', - `allow_reg_tracker` tinyint(1) NOT NULL DEFAULT '0', - `allow_porno_topic` tinyint(1) NOT NULL DEFAULT '0', - `self_moderated` tinyint(1) NOT NULL DEFAULT '0', - `forum_parent` smallint(5) unsigned NOT NULL DEFAULT '0', - `show_on_index` tinyint(1) NOT NULL DEFAULT '1', - `forum_display_sort` tinyint(1) NOT NULL DEFAULT '0', - `forum_display_order` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`forum_id`), - KEY `forums_order` (`forum_order`), - KEY `cat_id` (`cat_id`), - KEY `forum_last_post_id` (`forum_last_post_id`), - KEY `forum_parent` (`forum_parent`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_forums --- ---------------------------- -INSERT INTO `bb_forums` VALUES ('1', '1', 'Ваш первый форум', 'Описание вашего первого форума.', '0', '10', '1', '1', '1', '0', '0', '0', '0', '1', '1', '1', '1', '3', '3', '1', '1', '1', '1', '0', '0', '0', '0', '1', '0', '0'); - --- ---------------------------- --- Table structure for `bb_groups` --- ---------------------------- -DROP TABLE IF EXISTS `bb_groups`; -CREATE TABLE IF NOT EXISTS `bb_groups` ( - `group_id` mediumint(8) NOT NULL AUTO_INCREMENT, - `avatar_ext_id` int(15) NOT NULL DEFAULT '0', - `group_time` int(11) NOT NULL DEFAULT '0', - `mod_time` int(11) NOT NULL DEFAULT '0', - `group_type` tinyint(4) NOT NULL DEFAULT '1', - `release_group` tinyint(4) NOT NULL DEFAULT '0', - `group_name` varchar(40) NOT NULL DEFAULT '', - `group_description` text NOT NULL, - `group_signature` text NOT NULL, - `group_moderator` mediumint(8) NOT NULL DEFAULT '0', - `group_single_user` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`group_id`), - KEY `group_single_user` (`group_single_user`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_groups --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_log` --- ---------------------------- -DROP TABLE IF EXISTS `bb_log`; -CREATE TABLE IF NOT EXISTS `bb_log` ( - `log_type_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `log_user_id` mediumint(9) NOT NULL DEFAULT '0', - `log_username` varchar(25) NOT NULL DEFAULT '', - `log_user_ip` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `log_forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `log_forum_id_new` smallint(5) unsigned NOT NULL DEFAULT '0', - `log_topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `log_topic_id_new` mediumint(8) unsigned NOT NULL DEFAULT '0', - `log_topic_title` varchar(250) NOT NULL DEFAULT '', - `log_topic_title_new` varchar(250) NOT NULL DEFAULT '', - `log_time` int(11) NOT NULL DEFAULT '0', - `log_msg` text NOT NULL, - KEY `log_time` (`log_time`), - FULLTEXT KEY `log_topic_title` (`log_topic_title`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_log --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_poll_users` --- ---------------------------- -DROP TABLE IF EXISTS `bb_poll_users`; -CREATE TABLE IF NOT EXISTS `bb_poll_users` ( - `topic_id` int(10) unsigned NOT NULL, - `user_id` int(11) NOT NULL, - `vote_ip` varchar(32) NOT NULL, - `vote_dt` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_poll_users --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_poll_votes` --- ---------------------------- -DROP TABLE IF EXISTS `bb_poll_votes`; -CREATE TABLE IF NOT EXISTS `bb_poll_votes` ( - `topic_id` int(10) unsigned NOT NULL, - `vote_id` tinyint(4) unsigned NOT NULL, - `vote_text` varchar(255) NOT NULL, - `vote_result` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`topic_id`,`vote_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_poll_votes --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_posts` --- ---------------------------- -DROP TABLE IF EXISTS `bb_posts`; -CREATE TABLE IF NOT EXISTS `bb_posts` ( - `post_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `poster_id` mediumint(8) NOT NULL DEFAULT '0', - `post_time` int(11) NOT NULL DEFAULT '0', - `poster_ip` char(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `poster_rg_id` mediumint(8) NOT NULL DEFAULT '0', - `attach_rg_sig` tinyint(4) NOT NULL DEFAULT '0', - `post_username` varchar(25) NOT NULL DEFAULT '', - `post_edit_time` int(11) NOT NULL DEFAULT '0', - `post_edit_count` smallint(5) unsigned NOT NULL DEFAULT '0', - `post_attachment` tinyint(1) NOT NULL DEFAULT '0', - `user_post` tinyint(1) NOT NULL DEFAULT '1', - `mc_comment` text NOT NULL, - `mc_type` tinyint(1) NOT NULL DEFAULT '0', - `mc_user_id` mediumint(8) NOT NULL DEFAULT '0', - PRIMARY KEY (`post_id`), - KEY `topic_id` (`topic_id`), - KEY `poster_id` (`poster_id`), - KEY `post_time` (`post_time`), - KEY `forum_id_post_time` (`forum_id`,`post_time`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_posts --- ---------------------------- -INSERT INTO `bb_posts` VALUES ('1', '1', '1', '2', UNIX_TIMESTAMP(), '', '0', '0', '', '0', '0', '0', '1', '', '0', '0'); - --- ---------------------------- --- Table structure for `bb_posts_html` --- ---------------------------- -DROP TABLE IF EXISTS `bb_posts_html`; -CREATE TABLE IF NOT EXISTS `bb_posts_html` ( - `post_id` mediumint(9) NOT NULL DEFAULT '0', - `post_html_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `post_html` mediumtext NOT NULL DEFAULT '', - PRIMARY KEY (`post_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_posts_html --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_posts_search` --- ---------------------------- -DROP TABLE IF EXISTS `bb_posts_search`; -CREATE TABLE IF NOT EXISTS `bb_posts_search` ( - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `search_words` text NOT NULL, - PRIMARY KEY (`post_id`), - FULLTEXT KEY `search_words` (`search_words`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_posts_search --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_posts_text` --- ---------------------------- -DROP TABLE IF EXISTS `bb_posts_text`; -CREATE TABLE IF NOT EXISTS `bb_posts_text` ( - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `post_text` text NOT NULL, - PRIMARY KEY (`post_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_posts_text --- ---------------------------- -INSERT INTO `bb_posts_text` VALUES ('1', 'Благодарим вас за установку новой версии TorrentPier II!\n\nЧто делать дальше? Сперва настройте ваш сайт в администраторском разделе. Измените базовые опции: заголовок сайта, число сообщений на страницу, часовой пояс, язык по-умолчанию, настройки сидбонусов, дней рождения и т.д. Создайте несколько форумов, а также не забудьте переименовать или удалить этот. Обязательно настройте возможность создания релизов в созданных вами разделах и добавьте [url=https://torrentpier.me/threads/25867/]шаблоны оформления раздач[/url] для них. Если у вас возникнут вопросы или потребность в дополнительных модификациях, [url=https://torrentpier.me/]посетите наш форум[/url].\n\nТакже напоминаем, что у проекта TorrentPier II есть несколько сайтов, которые могут оказаться полезны для вас:\n[list]\n[*]Форум: https://torrentpier.me/\n[*]Демо-версия: https://demo.torrentpier.me/\n[*]Инструкция: https://faq.torrentpier.me/\n[*]Центр загрузки: https://get.torrentpier.me/\n[*]Перевод на другие языки: http://translate.torrentpier.me/\n[/list]\nНе забудьте добавить их себе в закладки и регулярно проверять наличие новых версий движка на нашем форуме, для своевременного обновления.\n\nНе сомневаемся, вам под силу создать самый лучший трекер. Удачи!'); - --- ---------------------------- --- Table structure for `bb_privmsgs` --- ---------------------------- -DROP TABLE IF EXISTS `bb_privmsgs`; -CREATE TABLE IF NOT EXISTS `bb_privmsgs` ( - `privmsgs_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `privmsgs_type` tinyint(4) NOT NULL DEFAULT '0', - `privmsgs_subject` varchar(255) NOT NULL DEFAULT '0', - `privmsgs_from_userid` mediumint(8) NOT NULL DEFAULT '0', - `privmsgs_to_userid` mediumint(8) NOT NULL DEFAULT '0', - `privmsgs_date` int(11) NOT NULL DEFAULT '0', - `privmsgs_ip` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - PRIMARY KEY (`privmsgs_id`), - KEY `privmsgs_from_userid` (`privmsgs_from_userid`), - KEY `privmsgs_to_userid` (`privmsgs_to_userid`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_privmsgs --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_privmsgs_text` --- ---------------------------- -DROP TABLE IF EXISTS `bb_privmsgs_text`; -CREATE TABLE IF NOT EXISTS `bb_privmsgs_text` ( - `privmsgs_text_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `privmsgs_text` text NOT NULL, - PRIMARY KEY (`privmsgs_text_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_privmsgs_text --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_quota_limits` --- ---------------------------- -DROP TABLE IF EXISTS `bb_quota_limits`; -CREATE TABLE IF NOT EXISTS `bb_quota_limits` ( - `quota_limit_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `quota_desc` varchar(20) NOT NULL DEFAULT '', - `quota_limit` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`quota_limit_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_quota_limits --- ---------------------------- -INSERT INTO `bb_quota_limits` VALUES ('1', 'Low', '262144'); -INSERT INTO `bb_quota_limits` VALUES ('2', 'Medium', '10485760'); -INSERT INTO `bb_quota_limits` VALUES ('3', 'High', '15728640'); - --- ---------------------------- --- Table structure for `bb_ranks` --- ---------------------------- -DROP TABLE IF EXISTS `bb_ranks`; -CREATE TABLE IF NOT EXISTS `bb_ranks` ( - `rank_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `rank_title` varchar(50) NOT NULL DEFAULT '', - `rank_min` mediumint(8) NOT NULL DEFAULT '0', - `rank_special` tinyint(1) NOT NULL DEFAULT '1', - `rank_image` varchar(255) NOT NULL DEFAULT '', - `rank_style` varchar(255) NOT NULL DEFAULT '', - PRIMARY KEY (`rank_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_ranks --- ---------------------------- -INSERT INTO `bb_ranks` VALUES ('', 'Администратор', '-1', '1', 'styles/images/ranks/admin.png', 'colorAdmin'); - --- ---------------------------- --- Table structure for `bb_search_rebuild` --- ---------------------------- -DROP TABLE IF EXISTS `bb_search_rebuild`; -CREATE TABLE IF NOT EXISTS `bb_search_rebuild` ( - `rebuild_session_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `start_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `end_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `start_time` int(11) NOT NULL DEFAULT '0', - `end_time` int(11) NOT NULL DEFAULT '0', - `last_cycle_time` int(11) NOT NULL DEFAULT '0', - `session_time` int(11) NOT NULL DEFAULT '0', - `session_posts` mediumint(8) unsigned NOT NULL DEFAULT '0', - `session_cycles` mediumint(8) unsigned NOT NULL DEFAULT '0', - `search_size` int(10) unsigned NOT NULL DEFAULT '0', - `rebuild_session_status` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`rebuild_session_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_search_rebuild --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_search_results` --- ---------------------------- -DROP TABLE IF EXISTS `bb_search_results`; -CREATE TABLE IF NOT EXISTS `bb_search_results` ( - `session_id` char(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `search_type` tinyint(4) NOT NULL DEFAULT '0', - `search_id` varchar(12) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `search_time` int(11) NOT NULL DEFAULT '0', - `search_settings` text NOT NULL, - `search_array` text NOT NULL, - PRIMARY KEY (`session_id`,`search_type`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_search_results --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_sessions` --- ---------------------------- -DROP TABLE IF EXISTS `bb_sessions`; -CREATE TABLE IF NOT EXISTS `bb_sessions` ( - `session_id` char(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `session_user_id` mediumint(8) NOT NULL DEFAULT '0', - `session_start` int(11) NOT NULL DEFAULT '0', - `session_time` int(11) NOT NULL DEFAULT '0', - `session_ip` char(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `session_logged_in` tinyint(1) NOT NULL DEFAULT '0', - `session_admin` tinyint(2) NOT NULL DEFAULT '0', - PRIMARY KEY (`session_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_sessions --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_smilies` --- ---------------------------- -DROP TABLE IF EXISTS `bb_smilies`; -CREATE TABLE IF NOT EXISTS `bb_smilies` ( - `smilies_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `code` varchar(50) NOT NULL DEFAULT '', - `smile_url` varchar(100) NOT NULL DEFAULT '', - `emoticon` varchar(75) NOT NULL DEFAULT '', - PRIMARY KEY (`smilies_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_smilies --- ---------------------------- -INSERT INTO `bb_smilies` VALUES ('', ':aa:', 'aa.gif', 'aa'); -INSERT INTO `bb_smilies` VALUES ('', ':ab:', 'ab.gif', 'ab'); -INSERT INTO `bb_smilies` VALUES ('', ':ac:', 'ac.gif', 'ac'); -INSERT INTO `bb_smilies` VALUES ('', ':ad:', 'ad.gif', 'ad'); -INSERT INTO `bb_smilies` VALUES ('', ':ae:', 'ae.gif', 'ae'); -INSERT INTO `bb_smilies` VALUES ('', ':af:', 'af.gif', 'af'); -INSERT INTO `bb_smilies` VALUES ('', ':ag:', 'ag.gif', 'ag'); -INSERT INTO `bb_smilies` VALUES ('', ':ah:', 'ah.gif', 'ah'); -INSERT INTO `bb_smilies` VALUES ('', ':ai:', 'ai.gif', 'ai'); -INSERT INTO `bb_smilies` VALUES ('', ':aj:', 'aj.gif', 'aj'); -INSERT INTO `bb_smilies` VALUES ('', ':ak:', 'ak.gif', 'ak'); -INSERT INTO `bb_smilies` VALUES ('', ':al:', 'al.gif', 'al'); -INSERT INTO `bb_smilies` VALUES ('', ':am:', 'am.gif', 'am'); -INSERT INTO `bb_smilies` VALUES ('', ':an:', 'an.gif', 'an'); -INSERT INTO `bb_smilies` VALUES ('', ':ao:', 'ao.gif', 'ao'); -INSERT INTO `bb_smilies` VALUES ('', ':ap:', 'ap.gif', 'ap'); -INSERT INTO `bb_smilies` VALUES ('', ':aq:', 'aq.gif', 'aq'); -INSERT INTO `bb_smilies` VALUES ('', ':ar:', 'ar.gif', 'ar'); -INSERT INTO `bb_smilies` VALUES ('', ':as:', 'as.gif', 'as'); -INSERT INTO `bb_smilies` VALUES ('', ':at:', 'at.gif', 'at'); -INSERT INTO `bb_smilies` VALUES ('', ':au:', 'au.gif', 'au'); -INSERT INTO `bb_smilies` VALUES ('', ':av:', 'av.gif', 'av'); -INSERT INTO `bb_smilies` VALUES ('', ':aw:', 'aw.gif', 'aw'); -INSERT INTO `bb_smilies` VALUES ('', ':ax:', 'ax.gif', 'ax'); -INSERT INTO `bb_smilies` VALUES ('', ':ay:', 'ay.gif', 'ay'); -INSERT INTO `bb_smilies` VALUES ('', ':az:', 'az.gif', 'az'); -INSERT INTO `bb_smilies` VALUES ('', ':ba:', 'ba.gif', 'ba'); -INSERT INTO `bb_smilies` VALUES ('', ':bb:', 'bb.gif', 'bb'); -INSERT INTO `bb_smilies` VALUES ('', ':bc:', 'bc.gif', 'bc'); -INSERT INTO `bb_smilies` VALUES ('', ':bd:', 'bd.gif', 'bd'); -INSERT INTO `bb_smilies` VALUES ('', ':be:', 'be.gif', 'be'); -INSERT INTO `bb_smilies` VALUES ('', ':bf:', 'bf.gif', 'bf'); -INSERT INTO `bb_smilies` VALUES ('', ':bg:', 'bg.gif', 'bg'); -INSERT INTO `bb_smilies` VALUES ('', ':bh:', 'bh.gif', 'bh'); -INSERT INTO `bb_smilies` VALUES ('', ':bi:', 'bi.gif', 'bi'); -INSERT INTO `bb_smilies` VALUES ('', ':bj:', 'bj.gif', 'bj'); -INSERT INTO `bb_smilies` VALUES ('', ':bk:', 'bk.gif', 'bk'); -INSERT INTO `bb_smilies` VALUES ('', ':bl:', 'bl.gif', 'bl'); -INSERT INTO `bb_smilies` VALUES ('', ':bm:', 'bm.gif', 'bm'); -INSERT INTO `bb_smilies` VALUES ('', ':bn:', 'bn.gif', 'bn'); -INSERT INTO `bb_smilies` VALUES ('', ':bo:', 'bo.gif', 'bo'); -INSERT INTO `bb_smilies` VALUES ('', ':bp:', 'bp.gif', 'bp'); -INSERT INTO `bb_smilies` VALUES ('', ':bq:', 'bq.gif', 'bq'); -INSERT INTO `bb_smilies` VALUES ('', ':br:', 'br.gif', 'br'); -INSERT INTO `bb_smilies` VALUES ('', ':bs:', 'bs.gif', 'bs'); -INSERT INTO `bb_smilies` VALUES ('', ':bt:', 'bt.gif', 'bt'); -INSERT INTO `bb_smilies` VALUES ('', ':bu:', 'bu.gif', 'bu'); -INSERT INTO `bb_smilies` VALUES ('', ':bv:', 'bv.gif', 'bv'); -INSERT INTO `bb_smilies` VALUES ('', ':bw:', 'bw.gif', 'bw'); -INSERT INTO `bb_smilies` VALUES ('', ':bx:', 'bx.gif', 'bx'); -INSERT INTO `bb_smilies` VALUES ('', ':by:', 'by.gif', 'by'); -INSERT INTO `bb_smilies` VALUES ('', ':bz:', 'bz.gif', 'bz'); -INSERT INTO `bb_smilies` VALUES ('', ':ca:', 'ca.gif', 'ca'); -INSERT INTO `bb_smilies` VALUES ('', ':cb:', 'cb.gif', 'cb'); -INSERT INTO `bb_smilies` VALUES ('', ':cc:', 'cc.gif', 'cc'); - --- ---------------------------- --- Table structure for `bb_topics` --- ---------------------------- -DROP TABLE IF EXISTS `bb_topics`; -CREATE TABLE IF NOT EXISTS `bb_topics` ( - `topic_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `forum_id` smallint(8) unsigned NOT NULL DEFAULT '0', - `topic_title` varchar(250) NOT NULL DEFAULT '', - `topic_poster` mediumint(8) NOT NULL DEFAULT '0', - `topic_time` int(11) NOT NULL DEFAULT '0', - `topic_views` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_replies` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_status` tinyint(3) NOT NULL DEFAULT '0', - `topic_vote` tinyint(1) NOT NULL DEFAULT '0', - `topic_type` tinyint(3) NOT NULL DEFAULT '0', - `topic_first_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_last_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_moved_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_attachment` tinyint(1) NOT NULL DEFAULT '0', - `topic_dl_type` tinyint(1) NOT NULL DEFAULT '0', - `topic_last_post_time` int(11) NOT NULL DEFAULT '0', - `topic_show_first_post` tinyint(1) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`), - KEY `forum_id` (`forum_id`), - KEY `topic_last_post_id` (`topic_last_post_id`), - KEY `topic_last_post_time` (`topic_last_post_time`), - FULLTEXT KEY `topic_title` (`topic_title`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_topics --- ---------------------------- -INSERT INTO `bb_topics` VALUES ('1', '1', 'Добро пожаловать в TorrentPier II', '2', UNIX_TIMESTAMP(), '2', '0', '0', '0', '0', '1', '1', '0', '0', '0', '1414658247', '0'); - --- ---------------------------- --- Table structure for `bb_topics_watch` --- ---------------------------- -DROP TABLE IF EXISTS `bb_topics_watch`; -CREATE TABLE IF NOT EXISTS `bb_topics_watch` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(8) NOT NULL DEFAULT '0', - `notify_status` tinyint(1) NOT NULL DEFAULT '0', - KEY `topic_id` (`topic_id`), - KEY `user_id` (`user_id`), - KEY `notify_status` (`notify_status`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_topics_watch --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_topic_tpl` --- ---------------------------- -DROP TABLE IF EXISTS `bb_topic_tpl`; -CREATE TABLE IF NOT EXISTS `bb_topic_tpl` ( - `tpl_id` smallint(6) NOT NULL AUTO_INCREMENT, - `tpl_name` varchar(60) NOT NULL DEFAULT '', - `tpl_src_form` text NOT NULL, - `tpl_src_title` text NOT NULL, - `tpl_src_msg` text NOT NULL, - `tpl_comment` text NOT NULL, - `tpl_rules_post_id` int(10) unsigned NOT NULL DEFAULT '0', - `tpl_last_edit_tm` int(11) NOT NULL DEFAULT '0', - `tpl_last_edit_by` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`tpl_id`), - UNIQUE KEY `tpl_name` (`tpl_name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_topic_tpl --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_users` --- ---------------------------- -DROP TABLE IF EXISTS `bb_users`; -CREATE TABLE IF NOT EXISTS `bb_users` ( - `user_id` mediumint(8) NOT NULL AUTO_INCREMENT, - `user_active` tinyint(1) NOT NULL DEFAULT '1', - `username` varchar(25) NOT NULL DEFAULT '', - `user_password` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `user_session_time` int(11) NOT NULL DEFAULT '0', - `user_lastvisit` int(11) NOT NULL DEFAULT '0', - `user_last_ip` char(32) NOT NULL DEFAULT '', - `user_regdate` int(11) NOT NULL DEFAULT '0', - `user_reg_ip` char(32) NOT NULL DEFAULT '', - `user_level` tinyint(4) NOT NULL DEFAULT '0', - `user_posts` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_timezone` decimal(5,2) NOT NULL DEFAULT '0.00', - `user_lang` varchar(255) NOT NULL DEFAULT 'ru', - `user_new_privmsg` smallint(5) unsigned NOT NULL DEFAULT '0', - `user_unread_privmsg` smallint(5) unsigned NOT NULL DEFAULT '0', - `user_last_privmsg` int(11) NOT NULL DEFAULT '0', - `user_opt` int(11) NOT NULL DEFAULT '0', - `user_rank` int(11) NOT NULL DEFAULT '0', - `avatar_ext_id` tinyint(4) NOT NULL DEFAULT '0', - `user_gender` tinyint(1) NOT NULL DEFAULT '0', - `user_birthday` date NOT NULL DEFAULT '0000-00-00', - `user_email` varchar(255) NOT NULL DEFAULT '', - `user_skype` varchar(32) NOT NULL DEFAULT '', - `user_twitter` varchar(15) NOT NULL DEFAULT '', - `user_icq` varchar(15) NOT NULL DEFAULT '', - `user_website` varchar(100) NOT NULL DEFAULT '', - `user_from` varchar(100) NOT NULL DEFAULT '', - `user_sig` text NOT NULL, - `user_occ` varchar(100) NOT NULL DEFAULT '', - `user_interests` varchar(255) NOT NULL DEFAULT '', - `user_actkey` varchar(32) NOT NULL DEFAULT '', - `user_newpasswd` varchar(32) NOT NULL DEFAULT '', - `autologin_id` varchar(12) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `user_newest_pm_id` mediumint(8) NOT NULL DEFAULT '0', - `user_points` float(16,2) NOT NULL DEFAULT '0.00', - `tpl_name` varchar(255) NOT NULL DEFAULT 'default', - PRIMARY KEY (`user_id`), - KEY `username` (`username`(10)), - KEY `user_email` (`user_email`(10)), - KEY `user_level` (`user_level`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_users --- ---------------------------- -INSERT INTO `bb_users` VALUES ('-1', '0', 'Guest', 'd41d8cd98f00b204e9800998ecf8427e', '0', '0', '0', UNIX_TIMESTAMP(), '0', '0', '0', '', '', '0', '0', '0', '0', '0', '0', '0', '0000-00-00', '', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); -INSERT INTO `bb_users` VALUES ('-746', '0', 'bot', 'd41d8cd98f00b204e9800998ecf8427e', '0', '0', '0', UNIX_TIMESTAMP(), '0', '0', '0', '', '', '0', '0', '0', '144', '0', '0', '0', '0000-00-00', 'bot@torrentpier.me', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); -INSERT INTO `bb_users` VALUES ('2', '1', 'admin', 'c3284d0f94606de1fd2af172aba15bf3', '0', '0', '0', UNIX_TIMESTAMP(), '0', '1', '1', '', '', '0', '0', '0', '304', '1', '0', '0', '0000-00-00', 'admin@torrentpier.me', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); - --- ---------------------------- --- Table structure for `bb_user_group` --- ---------------------------- -DROP TABLE IF EXISTS `bb_user_group`; -CREATE TABLE IF NOT EXISTS `bb_user_group` ( - `group_id` mediumint(8) NOT NULL DEFAULT '0', - `user_id` mediumint(8) NOT NULL DEFAULT '0', - `user_pending` tinyint(1) NOT NULL DEFAULT '0', - `user_time` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`group_id`,`user_id`), - KEY `user_id` (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_user_group --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_words` --- ---------------------------- -DROP TABLE IF EXISTS `bb_words`; -CREATE TABLE IF NOT EXISTS `bb_words` ( - `word_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `word` char(100) NOT NULL DEFAULT '', - `replacement` char(100) NOT NULL DEFAULT '', - PRIMARY KEY (`word_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_words --- ---------------------------- - --- ---------------------------- --- Table structure for `buf_last_seeder` --- ---------------------------- -DROP TABLE IF EXISTS `buf_last_seeder`; -CREATE TABLE IF NOT EXISTS `buf_last_seeder` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeder_last_seen` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of buf_last_seeder --- ---------------------------- - --- ---------------------------- --- Table structure for `buf_topic_view` --- ---------------------------- -DROP TABLE IF EXISTS `buf_topic_view`; -CREATE TABLE IF NOT EXISTS `buf_topic_view` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_views` mediumint(8) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of buf_topic_view --- ---------------------------- \ No newline at end of file diff --git a/install/sql/ocelot.sql b/install/sql/ocelot.sql deleted file mode 100644 index b7d35c6e9..000000000 --- a/install/sql/ocelot.sql +++ /dev/null @@ -1,53 +0,0 @@ -SET SQL_MODE = ""; - --- ---------------------------- --- Table structure for `bb_bt_tracker` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_tracker`; -CREATE TABLE IF NOT EXISTS `bb_bt_tracker` ( - `peer_hash` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `peer_id` varchar(20) NOT NULL, - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `ip` varchar(15) NOT NULL DEFAULT '0', - `ipv6` varchar(32) DEFAULT NULL, - `port` smallint(5) unsigned NOT NULL DEFAULT '0', - `client` varchar(51) NOT NULL DEFAULT 'Unknown', - `seeder` tinyint(1) NOT NULL DEFAULT '0', - `releaser` tinyint(1) NOT NULL DEFAULT '0', - `tor_type` tinyint(1) NOT NULL DEFAULT '0', - `uploaded` bigint(20) unsigned NOT NULL DEFAULT '0', - `downloaded` bigint(20) unsigned NOT NULL DEFAULT '0', - `remain` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` mediumint(8) unsigned NOT NULL DEFAULT '0', - `speed_down` mediumint(8) unsigned NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `update_time` int(11) NOT NULL DEFAULT '0', - `complete_percent` bigint(20) NOT NULL DEFAULT '0', - PRIMARY KEY (`peer_hash`), - KEY `topic_id` (`topic_id`), - KEY `user_id` (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_tracker --- ---------------------------- - --- ---------------------------- --- Table structure for `bb_bt_tracker_snap` --- ---------------------------- -DROP TABLE IF EXISTS `bb_bt_tracker_snap`; -CREATE TABLE IF NOT EXISTS `bb_bt_tracker_snap` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeders` mediumint(8) unsigned NOT NULL DEFAULT '0', - `leechers` mediumint(8) unsigned NOT NULL DEFAULT '0', - `speed_up` int(10) unsigned NOT NULL DEFAULT '0', - `speed_down` int(10) unsigned NOT NULL DEFAULT '0', - `complete` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of bb_bt_tracker_snap --- ---------------------------- \ No newline at end of file diff --git a/install/upgrade/changes.txt b/install/upgrade/changes.txt deleted file mode 100644 index a18e98d6b..000000000 --- a/install/upgrade/changes.txt +++ /dev/null @@ -1,21 +0,0 @@ -Схема изменений начиная с версии 2.1 (R600): - -Изменения в базе: - -DROP TABLE IF EXISTS `bb_reports`; -DROP TABLE IF EXISTS `bb_reports_changes`; -DROP TABLE IF EXISTS `bb_reports_modules`; -DROP TABLE IF EXISTS `bb_reports_reasons`; -DELETE FROM `bb_config` WHERE `config_name` = 'report_subject_auth'; -DELETE FROM `bb_config` WHERE `config_name` = 'report_modules_cache'; -DELETE FROM `bb_config` WHERE `config_name` = 'report_hack_count'; -DELETE FROM `bb_config` WHERE `config_name` = 'report_notify'; -DELETE FROM `bb_config` WHERE `config_name` = 'report_list_admin'; -DELETE FROM `bb_config` WHERE `config_name` = 'report_new_window'; -DELETE FROM `bb_config` WHERE `config_name` = 'reports_enabled'; -ALTER TABLE `bb_posts` DROP COLUMN `post_reported`; -ALTER TABLE `bb_privmsgs` DROP COLUMN `privmsgs_reported`; -ALTER TABLE `bb_topics` DROP COLUMN `topic_reported`; -DELETE FROM `bb_cron` WHERE `cron_script` = 'site_backup.php'; -DELETE FROM `bb_cron` WHERE `cron_script` = 'db_backup.php'; -UPDATE `bb_cron` SET `cron_script` = 'board_maintenance.php' WHERE `cron_script` = 'bb_maintenance.php'; \ No newline at end of file diff --git a/install/upgrade/r496-user_birthday.php b/install/upgrade/r496-user_birthday.php deleted file mode 100644 index a82c8f2c0..000000000 --- a/install/upgrade/r496-user_birthday.php +++ /dev/null @@ -1,36 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); - -$confirm = request_var('confirm', ''); - -if ($confirm) { - DB()->query("ALTER TABLE ". BB_USERS ." CHANGE COLUMN user_birthday user_birthday_old int(11) NOT NULL DEFAULT 0 AFTER user_gender"); - DB()->query("ALTER TABLE ". BB_USERS ." ADD user_birthday date NOT NULL DEFAULT '0000-00-00' AFTER user_gender"); - - $sql = "SELECT user_id, user_birthday_old FROM ". BB_USERS ." WHERE user_birthday_old != 0 AND user_id NOT IN ('". EXCLUDED_USERS_CSV ."')"; - - foreach (DB()->fetch_rowset($sql) as $row) - { - $birthday = bb_date($row['user_birthday_old'] * 86400 + 1, 'Y-m-d', 0); - DB()->query("UPDATE ". BB_USERS ." SET user_birthday = '". $birthday ."' WHERE user_id = ". $row['user_id'] .""); - } - - DB()->query("ALTER TABLE ". BB_USERS ." DROP user_birthday_old"); - - bb_die('

        База данных обновлена

        '); -} else { - $msg = '
        '; - $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; - $msg .= ''; - $msg .= '
        '; - - bb_die($msg); -} \ No newline at end of file diff --git a/install/upgrade/r571-dl_upgrade.php b/install/upgrade/r571-dl_upgrade.php deleted file mode 100644 index 90adb63b5..000000000 --- a/install/upgrade/r571-dl_upgrade.php +++ /dev/null @@ -1,54 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); - -$confirm = request_var('confirm', ''); - -if ($confirm) { - DB()->query(" - CREATE TEMPORARY TABLE tmp_buf_dlstatus ( - user_id mediumint(9) NOT NULL default '0', - topic_id mediumint(8) unsigned NOT NULL default '0', - user_status tinyint(1) NOT NULL default '0', - PRIMARY KEY (user_id, topic_id) - ) ENGINE = MyISAM - "); - - DB()->query(" - INSERT INTO tmp_buf_dlstatus - (user_id, topic_id, user_status) - SELECT - user_id, topic_id, user_status - FROM bb_bt_dlstatus_new - "); - - DB()->query(" - REPLACE INTO bb_bt_dlstatus_main - (user_id, topic_id, user_status) - SELECT - user_id, topic_id, user_status - FROM tmp_buf_dlstatus - "); - - DB()->query("DROP TEMPORARY TABLE IF EXISTS tmp_buf_dlstatus"); - DB()->query("RENAME TABLE bb_bt_dlstatus_main TO bb_bt_dlstatus"); - - DB()->query("DROP TABLE IF EXISTS bb_bt_dlstatus_mrg"); - DB()->query("DROP TABLE IF EXISTS bb_bt_dlstatus_new"); - - bb_die('

        База данных обновлена

        '); -} else { - $msg = '
        '; - $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; - $msg .= ''; - $msg .= '
        '; - - bb_die($msg); -} \ No newline at end of file diff --git a/install/upgrade/r575-poll_upgrade.php b/install/upgrade/r575-poll_upgrade.php deleted file mode 100644 index 71388bdb4..000000000 --- a/install/upgrade/r575-poll_upgrade.php +++ /dev/null @@ -1,76 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); - -$confirm = request_var('confirm', ''); - -if ($confirm) { - DB()->query(" - CREATE TABLE IF NOT EXISTS `bb_poll_users` ( - `topic_id` int(10) unsigned NOT NULL, - `user_id` int(11) NOT NULL, - `vote_ip` varchar(32) NOT NULL, - `vote_dt` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 - "); - - DB()->query(" - CREATE TABLE IF NOT EXISTS `bb_poll_votes` ( - `topic_id` int(10) unsigned NOT NULL, - `vote_id` tinyint(4) unsigned NOT NULL, - `vote_text` varchar(255) NOT NULL, - `vote_result` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`topic_id`,`vote_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 - "); - - DB()->query(" - INSERT IGNORE INTO bb_poll_votes - (topic_id, vote_id, vote_text, vote_result) - SELECT - topic_id, 0, vote_text, 0 - FROM bb_vote_desc; - "); - - DB()->query(" - INSERT IGNORE INTO bb_poll_votes - (topic_id, vote_id, vote_text, vote_result) - SELECT - d.topic_id, r.vote_option_id, r.vote_option_text, r.vote_result - FROM bb_vote_desc d, bb_vote_results r - WHERE - d.vote_id = r.vote_id; - "); - - DB()->query(" - INSERT IGNORE INTO bb_poll_users - (topic_id, user_id, vote_ip) - SELECT - d.topic_id, v.vote_user_id, v.vote_user_ip - FROM bb_vote_desc d, bb_vote_voters v - WHERE - d.vote_id = v.vote_id - AND v.vote_user_id > 0; - "); - - DB()->query("DROP TABLE IF EXISTS bb_vote_desc"); - DB()->query("DROP TABLE IF EXISTS bb_vote_results"); - DB()->query("DROP TABLE IF EXISTS bb_vote_voters"); - - bb_die('

        База данных обновлена

        '); -} else { - $msg = '
        '; - $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; - $msg .= ''; - $msg .= '
        '; - - bb_die($msg); -} \ No newline at end of file diff --git a/install/upgrade/r583-convert_avatars.php b/install/upgrade/r583-convert_avatars.php deleted file mode 100644 index 20fbe2878..000000000 --- a/install/upgrade/r583-convert_avatars.php +++ /dev/null @@ -1,84 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); - -$confirm = request_var('confirm', ''); - -if ($confirm) { - DB()->query("ALTER TABLE " . BB_USERS . " ADD `avatar_ext_id` TINYINT( 4 ) NOT NULL AFTER `user_rank`"); - - $rows_per_cycle = 10000; - - $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); - $end_id = (int)$row['end_id']; - $start = $avatars_ok = $avatars_err = 0; - - echo "
        \n";
        -
        -	while (true) {
        -		set_time_limit(600);
        -		echo "$start [ $avatars_ok / $avatars_err ]\n";
        -		$end = $start + $rows_per_cycle - 1;
        -		$sql = "
        -			SELECT user_id, avatar_ext_id, user_avatar
        -			FROM " . BB_USERS . "
        -			WHERE user_avatar != ''
        -				AND avatar_ext_id = 0
        -				AND user_id BETWEEN $start AND $end
        -			ORDER BY NULL
        -		";
        -
        -		foreach (DB()->fetch_rowset($sql) as $row) {
        -			$FILE = array(
        -				'name' => '',
        -				'type' => '',
        -				'size' => 0,
        -				'tmp_name' => BB_ROOT . $bb_cfg['avatar_path'] . '/' . basename($row['user_avatar']),
        -				'error' => 0,
        -			);
        -			$upload = new upload_common();
        -
        -			if ($upload->init($bb_cfg['avatars'], $FILE, false) AND $upload->store('avatar', $row)) {
        -				DB()->query("UPDATE " . BB_USERS . " SET avatar_ext_id = {$upload->file_ext_id} WHERE user_id = {$row['user_id']} LIMIT 1");
        -				$avatars_ok++;
        -			} else {
        -				echo "{$row['user_id']}: ", join("\n{$row['user_id']}: ", $upload->errors), "\n";
        -				$avatars_err++;
        -			}
        -		}
        -
        -		if ($end > $end_id) {
        -			break;
        -		}
        -		$start += $rows_per_cycle;
        -		sleep(1);
        -	}
        -
        -	echo "---------- База данных успешно обновлена. Аватары указанных выше пользователей перенесены не были. ----------\n";
        -
        -	DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar`");
        -	DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar_type`");
        -} else {
        -	$msg = '
        '; - $msg .= '

        Перед тем как нажать на кнопку, сделайте бекап базы данных! В ходе обновления базы данных, произойдет автоматическая конвертация имеющихся аватаров пользователей - по новому алгоритму. Для конвертации аватарка пользователя должна соответствовать текущим значениям из конфига: ширина не более ' . $bb_cfg['avatars']['max_width'] . ' пикселов, высота не более ' . $bb_cfg['avatars']['max_height'] . ' пикселов - и объем не более ' . $bb_cfg['avatars']['max_size'] . ' байт. Если эти условия не соблюдены - аватарка пользователя не будет конвертирована и пользователю придется залить ее заново! Если вы хотите поправить указанные - значения - ПЕРЕД обновлением базы данных сделайте это в config.php!


        '; - $msg .= ''; - $msg .= '
        '; - - bb_die($msg); -} \ No newline at end of file diff --git a/install/upgrade/r588-short_lang.php b/install/upgrade/r588-short_lang.php deleted file mode 100644 index df2eefdde..000000000 --- a/install/upgrade/r588-short_lang.php +++ /dev/null @@ -1,52 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); - -$confirm = request_var('confirm', ''); - -if ($confirm) { - DB()->query("UPDATE " . BB_CONFIG . " SET `config_value` = 'ru' WHERE `config_name` = 'default_lang'"); - DB()->query("ALTER TABLE " . BB_USERS . " ADD `user_twitter` varchar (15) NOT NULL DEFAULT '' AFTER `user_skype`"); - - $rows_per_cycle = 10000; - - $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); - $end_id = (int)$row['end_id']; - $start = 0; - - while (true) { - set_time_limit(600); - $end = $start + $rows_per_cycle - 1; - - DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'ru' WHERE user_lang = 'russian'"); - DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'en' WHERE user_lang = 'english'"); - - if ($end > $end_id) { - break; - } - $start += $rows_per_cycle; - sleep(1); - } - - bb_die("База данных успешно обновлена. Можно приступать к обновлению файлов. Не забудьте удалить этот файл."); -} else { - $msg = '
        '; - $msg .= '

        Перед тем как нажать на кнопку, сделайте бекап базы данных! В ходе обновления базы данных, произойдет автоматическая конвертация текущих языков интерфейса пользователей - на новое именование, а также будет добавлено поле в базу данных пользователей, для их Twitter-аккаунтов. После этого, вам можно будет приступать к обновлению файлов.


        '; - $msg .= ''; - $msg .= '
        '; - - bb_die($msg); -} \ No newline at end of file diff --git a/install/upgrade/r600-stable.php b/install/upgrade/r600-stable.php deleted file mode 100644 index 75c57424b..000000000 --- a/install/upgrade/r600-stable.php +++ /dev/null @@ -1,222 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); - -bb_die(' -

        Для обновления до стабильной ревизии R600, вам необходимо воспользоваться инструкцией, опубликованной в данной теме на нашем форуме. - Вы также можете заглянуть в исходный код этого скрипта, в нем опубликована схема изменений от ревизии 400, - до ревизии 600. Не забывайте про бекап базы данных перед обновлением!

        -'); - -/* - -Схема изенений r400->r600 для написания конвертера. - -Изменения в базе: - -INSERT INTO `bb_config` VALUES ('tor_comment', '1'); // добавлено 407 -ALTER TABLE `bb_posts` ADD `post_mod_comment` TEXT NOT NULL DEFAULT ''; // добавлено 458 -ALTER TABLE `bb_posts` ADD `post_mod_comment_type` TINYINT( 1 ) NOT NULL DEFAULT '0'; // добавлено 458 -ALTER TABLE `bb_posts` ADD `post_mc_mod_id` mediumint(8) NOT NULL; // добавлено 458 -ALTER TABLE `bb_posts` ADD `post_mc_mod_name` varchar(25) NOT NULL DEFAULT ''; // добавлено 458 - -// 496 - отдельный конвертер - -ALTER TABLE `bb_users` ADD `tpl_name` varchar(255) NOT NULL DEFAULT 'default'; // добавлено 507 -UPDATE `bb_config` SET `config_value` = '1' WHERE `config_name` = 'bt_unset_dltype_on_tor_unreg'; - // изменено 508 ↑ -ALTER TABLE `bb_users` DROP `ignore_srv_load`; // удалено 537 -UPDATE `bb_users` SET `username` = 'Guest' WHERE `user_id` = -1; // изменено 540 -DROP TABLE IF EXISTS `bb_bt_torrents_del`; // удалено 551 -DROP TABLE IF EXISTS `xbt_announce_log`; // удалено 551 -DROP TABLE IF EXISTS `xbt_config`; // удалено 551 -DROP TABLE IF EXISTS `xbt_deny_from_hosts`; // удалено 551 -DROP TABLE IF EXISTS `xbt_files_users`; // удалено 551 -DROP TABLE IF EXISTS `xbt_scrape_log`; // удалено 551 -ALTER TABLE `bb_bt_tracker` DROP `xbt_error`; // удалено 551 -DELETE FROM `bb_config` WHERE `config_name` = 'torrent_pass_private_key'; // удалено 551 -DELETE FROM `bb_config` WHERE `config_name` = 'board_email'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'board_email_form'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'board_email_sig'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'smtp_delivery'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'smtp_host'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'smtp_password'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'smtp_username'; // удалено 552 -DELETE FROM `bb_config` WHERE `config_name` = 'gallery_enabled'; // удалено 554 -DELETE FROM `bb_config` WHERE `config_name` = 'pic_dir'; // удалено 554 -DELETE FROM `bb_config` WHERE `config_name` = 'pic_max_size'; // удалено 554 -DELETE FROM `bb_config` WHERE `config_name` = 'auto_delete_posted_pics'; // удалено 554 -DELETE FROM `bb_config` WHERE `config_name` = 'allow_avatar_remote'; // удалено 555 -ALTER TABLE `bb_topics` DROP COLUMN `is_draft`; // удалено 558 -DELETE FROM `bb_config` WHERE `config_name` = 'bt_add_comment'; // удалено 565 -DELETE FROM `bb_config` WHERE `config_name` = 'bt_add_publisher'; // удалено 565 -DELETE FROM `bb_config` WHERE `config_name` = 'bt_gen_passkey_on_reg'; // удалено 565 -DROP TABLE IF EXISTS `sph_counter`; // удалено 571 - -// 571 - отдельный конвертер - -DELETE FROM `bb_config` WHERE `config_name` = 'max_inbox_privmsgs'; // удалено 573 -DELETE FROM `bb_config` WHERE `config_name` = 'max_savebox_privmsgs'; // удалено 573 -DELETE FROM `bb_config` WHERE `config_name` = 'max_sentbox_privmsgs'; // удалено 573 -DELETE FROM `bb_config` WHERE `config_name` = 'privmsg_disable'; // удалено 573 - -// 575 - отдельный конвертер - -DELETE FROM `bb_config` WHERE `config_name` = 'config_id'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'sendmail_fix'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'version'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_add_comments'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_auto_compile'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_auto_recompile'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_php'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_shownav'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_template_time'; // удалено 579 -DELETE FROM `bb_config` WHERE `config_name` = 'xs_version'; // удалено 579 -INSERT INTO `bb_cron` VALUES (22, 1, 'Attach maintenance', 'attach_maintenance.php', 'daily', NULL, '05:00:00', 40, '', '', NULL, 1, '', 0, 1, 0); - // добавлено 582 ↑ -DELETE FROM `bb_config` WHERE `config_name` = 'allow_avatar_local'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'allow_avatar_upload'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'avatar_filesize'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'avatar_gallery_path'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'avatar_max_height'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'avatar_max_width'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'avatar_path'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'require_activation'; // удалено 583 -DELETE FROM `bb_config` WHERE `config_name` = 'no_avatar'; // удалено 583 -UPDATE `bb_config` SET `config_value` = '0' WHERE `config_name` = 'show_mod_index'; // изменено 583 -DELETE FROM `bb_cron` WHERE `cron_script` = 'avatars_cleanup.php'; // удалено 583 -UPDATE `bb_cron` SET `cron_id` = '3' WHERE `cron_script` = 'attach_maintenance.php'; // изменено 583 - -// 583 - отдельный конвертер - -DROP TABLE IF EXISTS `bb_topic_templates`; // удалено 584 -ALTER TABLE `bb_forums` DROP `topic_tpl_id`; // удалено 584 -UPDATE `bb_config` SET `config_value` = 'http://ip-whois.net/ip_geos.php?ip=' WHERE `config_name` = 'whois_info'; - // обновлено 586 ↑ -UPDATE `bb_config` SET `config_value` = 'ru' WHERE `config_name` = 'default_lang'; // обновлено 588 - -// 588 - отдельный конвертер - -ALTER TABLE `bb_users` DROP `user_next_birthday_greeting`; // удалено 589 -ALTER TABLE `bb_posts` CHANGE `post_mod_comment` `mc_comment` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''; - // изменено 590 ↑ -ALTER TABLE `bb_posts` CHANGE `post_mod_comment_type` `mc_type` TINYINT(1) NOT NULL DEFAULT '0'; - // изменено 590 ↑ -ALTER TABLE `bb_posts` CHANGE `post_mc_mod_id` `mc_user_id` MEDIUMINT(8) NOT NULL DEFAULT '0'; - // изменено 590 ↑ -ALTER TABLE `bb_posts` DROP `post_mc_mod_name`; // удалено 590 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'allow_ftp_upload'; // удалено 592 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'ftp_server'; // удалено 592 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'ftp_path'; // удалено 592 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'download_path'; // удалено 592 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'ftp_user'; // удалено 592 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'ftp_pass'; // удалено 592 -DELETE FROM `bb_attachments_config` WHERE `config_name` = 'ftp_pasv_mode'; // удалено 592 -DELETE FROM `bb_extensions` WHERE `extension` = 'wma'; // удалено 592 -DELETE FROM `bb_extensions` WHERE `extension` = 'swf'; // удалено 592 -UPDATE `bb_extensions` SET `group_id` = '6' WHERE `extension` = 'torrent'; // изменено 592 -DELETE FROM `bb_extension_groups` WHERE `group_name` = 'Streams'; // удалено 592 -DELETE FROM `bb_extension_groups` WHERE `group_name` = 'Flash Files'; // удалено 592 -UPDATE `bb_extension_groups` SET `group_id` = '6' WHERE `group_id` = 8; // изменено 592 -INSERT INTO `bb_config` VALUES ('sitemap_time', ''); // добавлено 593 -INSERT INTO `bb_config` VALUES ('static_sitemap', ''); // добавлено 593 -INSERT INTO `bb_cron` VALUES (22, 1, 'Sitemap update', 'sitemap.php', 'daily', NULL, '06:00:00', 30, '', '', NULL, 0, '', 0, 0, 0); - // добавлено 593 ↑ -INSERT INTO `bb_cron` VALUES (23, 1, 'Update forums atom', 'update_forums_atom.php', 'interval', NULL, NULL, 255, '', '', '00:15:00', 0, '', 0, 0, 0); - // добавлено 595 ↑ -UPDATE `bb_attachments_config` SET `config_value` = 'old_files' WHERE `config_name` = 'upload_dir'; - // изменено 595 ↑ -DELETE FROM `bb_smilies` WHERE `code` = ':cd:'; // удалено 596 -ALTER TABLE `bb_groups` CHANGE `group_description` `group_description` text NOT NULL DEFAULT ''; - // изменено 598 ↑ -ALTER TABLE `bb_groups` ADD `avatar_ext_id` int(15) NOT NULL DEFAULT '0' AFTER `group_id`; - // добавлено 598 ↑ -ALTER TABLE `bb_groups` ADD `mod_time` INT(11) NOT NULL DEFAULT '0' AFTER `group_time`; - // добавлено 598 ↑ -ALTER TABLE `bb_groups` ADD `release_group` tinyint(4) NOT NULL DEFAULT '0' AFTER `group_type`; - // добавлено 598 ↑ -ALTER TABLE `bb_groups` ADD `group_signature` text NOT NULL DEFAULT '' AFTER `group_description`; - // добавлено 598 ↑ -ALTER TABLE `bb_posts` ADD `poster_rg_id` mediumint(8) NOT NULL DEFAULT '0' AFTER `poster_ip`; - // добавлено 598 ↑ -ALTER TABLE `bb_posts` ADD `attach_rg_sig` tinyint(4) NOT NULL DEFAULT '0' AFTER `poster_rg_id`; - // добавлено 598 ↑ -INSERT INTO `bb_config` VALUES ('terms', ''); // добавлено 599b - -Удаленные файлы/папки: - -admin/.htaccess -admin/admin_topic_templates.php -admin/admin_xs.php -admin/xs_cache.php -admin/xs_config.php -admin/xs_frameset.php -admin/xs_include.php -admin/xs_index.php -develop -images/avatars/bot.gif -images/logo/logo_big.png -images/smiles/cd.gif -images/smiles/smileys.pak -images/icon_disk.gif -images/icon_disk_gray.gif -includes/cron/jobs/avatars_cleanup.php -includes/topic_templates -includes/ucp/torrent_userprofile.php -includes/ucp/usercp_activate.php -includes/ucp/usercp_attachcp.php -includes/ucp/usercp_avatar.php -includes/ucp/usercp_bonus.php -includes/ucp/usercp_email.php -includes/ucp/usercp_register.php -includes/ucp/usercp_sendpasswd.php -includes/ucp/usercp_viewprofile.php -includes/sphinxapi.php -includes/topic_templates.php -language/lang_english -language/lang_russian -misc/html -misc/.htaccess -pictures -templates/admin/admin_topic_templates.tpl -templates/default/images/lang_english -templates/default/images/lang_russian -templates/default/images/index.html -templates/default/topic_templates -templates/default/agreement.tpl -templates/default/donate.tpl -templates/default/faq.tpl -templates/default/gallery.tpl -templates/default/posting_poll.tpl -templates/default/posting_tpl.tpl -templates/default/usercp_avatar_gallery.tpl -templates/default/viewonline.tpl -templates/xs_mod -templates/board_disabled_exit.php -templates/limit_load_exit.php -templates/topic_tpl_overall_header.html -templates/topic_tpl_rules_video.html -donate.php -download.php -faq.php -gallery.php -viewonline.php - -Прочие изменения: - -Все файлы перекодированы для использования окончаний строк LF. - - */ \ No newline at end of file diff --git a/internal_data/cache/.htaccess b/internal_data/cache/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/internal_data/cache/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/internal_data/captcha/.keep b/internal_data/cache/.keep similarity index 100% rename from internal_data/captcha/.keep rename to internal_data/cache/.keep diff --git a/internal_data/log/.htaccess b/internal_data/log/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/internal_data/log/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/internal_data/sitemap/.keep b/internal_data/log/.keep similarity index 100% rename from internal_data/sitemap/.keep rename to internal_data/log/.keep diff --git a/internal_data/log/cron/.htaccess b/internal_data/log/cron/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/internal_data/log/cron/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/internal_data/triggers/.htaccess b/internal_data/triggers/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/internal_data/triggers/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/library/Zend/Authentication/Adapter/AbstractAdapter.php b/library/Zend/Authentication/Adapter/AbstractAdapter.php deleted file mode 100755 index 2f394f9e9..000000000 --- a/library/Zend/Authentication/Adapter/AbstractAdapter.php +++ /dev/null @@ -1,71 +0,0 @@ -credential; - } - - /** - * Sets the credential for binding - * - * @param mixed $credential - * @return AbstractAdapter - */ - public function setCredential($credential) - { - $this->credential = $credential; - - return $this; - } - - /** - * Returns the identity of the account being authenticated, or - * NULL if none is set. - * - * @return mixed - */ - public function getIdentity() - { - return $this->identity; - } - - /** - * Sets the identity for binding - * - * @param mixed $identity - * @return AbstractAdapter - */ - public function setIdentity($identity) - { - $this->identity = $identity; - - return $this; - } -} diff --git a/library/Zend/Authentication/Adapter/AdapterInterface.php b/library/Zend/Authentication/Adapter/AdapterInterface.php deleted file mode 100755 index d23d07936..000000000 --- a/library/Zend/Authentication/Adapter/AdapterInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -zendDb = $zendDb; - - if (null !== $tableName) { - $this->setTableName($tableName); - } - - if (null !== $identityColumn) { - $this->setIdentityColumn($identityColumn); - } - - if (null !== $credentialColumn) { - $this->setCredentialColumn($credentialColumn); - } - } - - /** - * setTableName() - set the table name to be used in the select query - * - * @param string $tableName - * @return self Provides a fluent interface - */ - public function setTableName($tableName) - { - $this->tableName = $tableName; - return $this; - } - - /** - * setIdentityColumn() - set the column name to be used as the identity column - * - * @param string $identityColumn - * @return self Provides a fluent interface - */ - public function setIdentityColumn($identityColumn) - { - $this->identityColumn = $identityColumn; - return $this; - } - - /** - * setCredentialColumn() - set the column name to be used as the credential column - * - * @param string $credentialColumn - * @return self Provides a fluent interface - */ - public function setCredentialColumn($credentialColumn) - { - $this->credentialColumn = $credentialColumn; - return $this; - } - - /** - * setAmbiguityIdentity() - sets a flag for usage of identical identities - * with unique credentials. It accepts integers (0, 1) or boolean (true, - * false) parameters. Default is false. - * - * @param int|bool $flag - * @return self Provides a fluent interface - */ - public function setAmbiguityIdentity($flag) - { - if (is_int($flag)) { - $this->ambiguityIdentity = (1 === $flag ? true : false); - } elseif (is_bool($flag)) { - $this->ambiguityIdentity = $flag; - } - return $this; - } - - /** - * getAmbiguityIdentity() - returns TRUE for usage of multiple identical - * identities with different credentials, FALSE if not used. - * - * @return bool - */ - public function getAmbiguityIdentity() - { - return $this->ambiguityIdentity; - } - - /** - * getDbSelect() - Return the preauthentication Db Select object for userland select query modification - * - * @return Sql\Select - */ - public function getDbSelect() - { - if ($this->dbSelect == null) { - $this->dbSelect = new Sql\Select(); - } - return $this->dbSelect; - } - - /** - * getResultRowObject() - Returns the result row as a stdClass object - * - * @param string|array $returnColumns - * @param string|array $omitColumns - * @return stdClass|bool - */ - public function getResultRowObject($returnColumns = null, $omitColumns = null) - { - if (!$this->resultRow) { - return false; - } - - $returnObject = new stdClass(); - - if (null !== $returnColumns) { - $availableColumns = array_keys($this->resultRow); - foreach ((array) $returnColumns as $returnColumn) { - if (in_array($returnColumn, $availableColumns)) { - $returnObject->{$returnColumn} = $this->resultRow[$returnColumn]; - } - } - return $returnObject; - } elseif (null !== $omitColumns) { - $omitColumns = (array) $omitColumns; - foreach ($this->resultRow as $resultColumn => $resultValue) { - if (!in_array($resultColumn, $omitColumns)) { - $returnObject->{$resultColumn} = $resultValue; - } - } - return $returnObject; - } - - foreach ($this->resultRow as $resultColumn => $resultValue) { - $returnObject->{$resultColumn} = $resultValue; - } - return $returnObject; - } - - /** - * This method is called to attempt an authentication. Previous to this - * call, this adapter would have already been configured with all - * necessary information to successfully connect to a database table and - * attempt to find a record matching the provided identity. - * - * @throws Exception\RuntimeException if answering the authentication query is impossible - * @return AuthenticationResult - */ - public function authenticate() - { - $this->authenticateSetup(); - $dbSelect = $this->authenticateCreateSelect(); - $resultIdentities = $this->authenticateQuerySelect($dbSelect); - - if (($authResult = $this->authenticateValidateResultSet($resultIdentities)) instanceof AuthenticationResult) { - return $authResult; - } - - // At this point, ambiguity is already done. Loop, check and break on success. - foreach ($resultIdentities as $identity) { - $authResult = $this->authenticateValidateResult($identity); - if ($authResult->isValid()) { - break; - } - } - - return $authResult; - } - - /** - * _authenticateValidateResult() - This method attempts to validate that - * the record in the resultset is indeed a record that matched the - * identity provided to this adapter. - * - * @param array $resultIdentity - * @return AuthenticationResult - */ - abstract protected function authenticateValidateResult($resultIdentity); - - /** - * _authenticateCreateSelect() - This method creates a Zend\Db\Sql\Select object that - * is completely configured to be queried against the database. - * - * @return Sql\Select - */ - abstract protected function authenticateCreateSelect(); - - /** - * _authenticateSetup() - This method abstracts the steps involved with - * making sure that this adapter was indeed setup properly with all - * required pieces of information. - * - * @throws Exception\RuntimeException in the event that setup was not done properly - * @return bool - */ - protected function authenticateSetup() - { - $exception = null; - - if ($this->tableName == '') { - $exception = 'A table must be supplied for the DbTable authentication adapter.'; - } elseif ($this->identityColumn == '') { - $exception = 'An identity column must be supplied for the DbTable authentication adapter.'; - } elseif ($this->credentialColumn == '') { - $exception = 'A credential column must be supplied for the DbTable authentication adapter.'; - } elseif ($this->identity == '') { - $exception = 'A value for the identity was not provided prior to authentication with DbTable.'; - } elseif ($this->credential === null) { - $exception = 'A credential value was not provided prior to authentication with DbTable.'; - } - - if (null !== $exception) { - throw new Exception\RuntimeException($exception); - } - - $this->authenticateResultInfo = array( - 'code' => AuthenticationResult::FAILURE, - 'identity' => $this->identity, - 'messages' => array() - ); - - return true; - } - - /** - * _authenticateQuerySelect() - This method accepts a Zend\Db\Sql\Select object and - * performs a query against the database with that object. - * - * @param Sql\Select $dbSelect - * @throws Exception\RuntimeException when an invalid select object is encountered - * @return array - */ - protected function authenticateQuerySelect(Sql\Select $dbSelect) - { - $sql = new Sql\Sql($this->zendDb); - $statement = $sql->prepareStatementForSqlObject($dbSelect); - try { - $result = $statement->execute(); - $resultIdentities = array(); - // iterate result, most cross platform way - foreach ($result as $row) { - // ZF-6428 - account for db engines that by default return uppercase column names - if (isset($row['ZEND_AUTH_CREDENTIAL_MATCH'])) { - $row['zend_auth_credential_match'] = $row['ZEND_AUTH_CREDENTIAL_MATCH']; - unset($row['ZEND_AUTH_CREDENTIAL_MATCH']); - } - $resultIdentities[] = $row; - } - } catch (\Exception $e) { - throw new Exception\RuntimeException( - 'The supplied parameters to DbTable failed to ' - . 'produce a valid sql statement, please check table and column names ' - . 'for validity.', - 0, - $e - ); - } - return $resultIdentities; - } - - /** - * _authenticateValidateResultSet() - This method attempts to make - * certain that only one record was returned in the resultset - * - * @param array $resultIdentities - * @return bool|\Zend\Authentication\Result - */ - protected function authenticateValidateResultSet(array $resultIdentities) - { - if (count($resultIdentities) < 1) { - $this->authenticateResultInfo['code'] = AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND; - $this->authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.'; - return $this->authenticateCreateAuthResult(); - } elseif (count($resultIdentities) > 1 && false === $this->getAmbiguityIdentity()) { - $this->authenticateResultInfo['code'] = AuthenticationResult::FAILURE_IDENTITY_AMBIGUOUS; - $this->authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.'; - return $this->authenticateCreateAuthResult(); - } - - return true; - } - - /** - * Creates a Zend\Authentication\Result object from the information that - * has been collected during the authenticate() attempt. - * - * @return AuthenticationResult - */ - protected function authenticateCreateAuthResult() - { - return new AuthenticationResult( - $this->authenticateResultInfo['code'], - $this->authenticateResultInfo['identity'], - $this->authenticateResultInfo['messages'] - ); - } -} diff --git a/library/Zend/Authentication/Adapter/DbTable/CallbackCheckAdapter.php b/library/Zend/Authentication/Adapter/DbTable/CallbackCheckAdapter.php deleted file mode 100755 index d585e353e..000000000 --- a/library/Zend/Authentication/Adapter/DbTable/CallbackCheckAdapter.php +++ /dev/null @@ -1,117 +0,0 @@ -setCredentialValidationCallback($credentialValidationCallback); - } else { - $this->setCredentialValidationCallback(function ($a, $b) { - return $a === $b; - }); - } - } - - /** - * setCredentialValidationCallback() - allows the developer to use a callback as a way of checking the - * credential. - * - * @param callable $validationCallback - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setCredentialValidationCallback($validationCallback) - { - if (!is_callable($validationCallback)) { - throw new Exception\InvalidArgumentException('Invalid callback provided'); - } - $this->credentialValidationCallback = $validationCallback; - return $this; - } - - /** - * _authenticateCreateSelect() - This method creates a Zend\Db\Sql\Select object that - * is completely configured to be queried against the database. - * - * @return Sql\Select - */ - protected function authenticateCreateSelect() - { - // get select - $dbSelect = clone $this->getDbSelect(); - $dbSelect->from($this->tableName) - ->columns(array(Sql\Select::SQL_STAR)) - ->where(new SqlOp($this->identityColumn, '=', $this->identity)); - - return $dbSelect; - } - - /** - * _authenticateValidateResult() - This method attempts to validate that - * the record in the resultset is indeed a record that matched the - * identity provided to this adapter. - * - * @param array $resultIdentity - * @return AuthenticationResult - */ - protected function authenticateValidateResult($resultIdentity) - { - try { - $callbackResult = call_user_func($this->credentialValidationCallback, $resultIdentity[$this->credentialColumn], $this->credential); - } catch (\Exception $e) { - $this->authenticateResultInfo['code'] = AuthenticationResult::FAILURE_UNCATEGORIZED; - $this->authenticateResultInfo['messages'][] = $e->getMessage(); - return $this->authenticateCreateAuthResult(); - } - if ($callbackResult !== true) { - $this->authenticateResultInfo['code'] = AuthenticationResult::FAILURE_CREDENTIAL_INVALID; - $this->authenticateResultInfo['messages'][] = 'Supplied credential is invalid.'; - return $this->authenticateCreateAuthResult(); - } - - $this->resultRow = $resultIdentity; - - $this->authenticateResultInfo['code'] = AuthenticationResult::SUCCESS; - $this->authenticateResultInfo['messages'][] = 'Authentication successful.'; - return $this->authenticateCreateAuthResult(); - } -} diff --git a/library/Zend/Authentication/Adapter/DbTable/CredentialTreatmentAdapter.php b/library/Zend/Authentication/Adapter/DbTable/CredentialTreatmentAdapter.php deleted file mode 100755 index b31cc5f74..000000000 --- a/library/Zend/Authentication/Adapter/DbTable/CredentialTreatmentAdapter.php +++ /dev/null @@ -1,124 +0,0 @@ -setCredentialTreatment($credentialTreatment); - } - } - - /** - * setCredentialTreatment() - allows the developer to pass a parametrized string that is - * used to transform or treat the input credential data. - * - * In many cases, passwords and other sensitive data are encrypted, hashed, encoded, - * obscured, or otherwise treated through some function or algorithm. By specifying a - * parametrized treatment string with this method, a developer may apply arbitrary SQL - * upon input credential data. - * - * Examples: - * - * 'PASSWORD(?)' - * 'MD5(?)' - * - * @param string $treatment - * @return self Provides a fluent interface - */ - public function setCredentialTreatment($treatment) - { - $this->credentialTreatment = $treatment; - return $this; - } - - /** - * _authenticateCreateSelect() - This method creates a Zend\Db\Sql\Select object that - * is completely configured to be queried against the database. - * - * @return Sql\Select - */ - protected function authenticateCreateSelect() - { - // build credential expression - if (empty($this->credentialTreatment) || (strpos($this->credentialTreatment, '?') === false)) { - $this->credentialTreatment = '?'; - } - - $credentialExpression = new SqlExpr( - '(CASE WHEN ?' . ' = ' . $this->credentialTreatment . ' THEN 1 ELSE 0 END) AS ?', - array($this->credentialColumn, $this->credential, 'zend_auth_credential_match'), - array(SqlExpr::TYPE_IDENTIFIER, SqlExpr::TYPE_VALUE, SqlExpr::TYPE_IDENTIFIER) - ); - - // get select - $dbSelect = clone $this->getDbSelect(); - $dbSelect->from($this->tableName) - ->columns(array('*', $credentialExpression)) - ->where(new SqlOp($this->identityColumn, '=', $this->identity)); - - return $dbSelect; - } - - /** - * _authenticateValidateResult() - This method attempts to validate that - * the record in the resultset is indeed a record that matched the - * identity provided to this adapter. - * - * @param array $resultIdentity - * @return AuthenticationResult - */ - protected function authenticateValidateResult($resultIdentity) - { - if ($resultIdentity['zend_auth_credential_match'] != '1') { - $this->authenticateResultInfo['code'] = AuthenticationResult::FAILURE_CREDENTIAL_INVALID; - $this->authenticateResultInfo['messages'][] = 'Supplied credential is invalid.'; - return $this->authenticateCreateAuthResult(); - } - - unset($resultIdentity['zend_auth_credential_match']); - $this->resultRow = $resultIdentity; - - $this->authenticateResultInfo['code'] = AuthenticationResult::SUCCESS; - $this->authenticateResultInfo['messages'][] = 'Authentication successful.'; - return $this->authenticateCreateAuthResult(); - } -} diff --git a/library/Zend/Authentication/Adapter/DbTable/Exception/ExceptionInterface.php b/library/Zend/Authentication/Adapter/DbTable/Exception/ExceptionInterface.php deleted file mode 100755 index 5365808fc..000000000 --- a/library/Zend/Authentication/Adapter/DbTable/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -setFilename($filename); - } - if ($realm !== null) { - $this->setRealm($realm); - } - if ($identity !== null) { - $this->setIdentity($identity); - } - if ($credential !== null) { - $this->setCredential($credential); - } - } - - /** - * Returns the filename option value or null if it has not yet been set - * - * @return string|null - */ - public function getFilename() - { - return $this->filename; - } - - /** - * Sets the filename option value - * - * @param mixed $filename - * @return Digest Provides a fluent interface - */ - public function setFilename($filename) - { - $this->filename = (string) $filename; - return $this; - } - - /** - * Returns the realm option value or null if it has not yet been set - * - * @return string|null - */ - public function getRealm() - { - return $this->realm; - } - - /** - * Sets the realm option value - * - * @param mixed $realm - * @return Digest Provides a fluent interface - */ - public function setRealm($realm) - { - $this->realm = (string) $realm; - return $this; - } - - /** - * Returns the username option value or null if it has not yet been set - * - * @return string|null - */ - public function getUsername() - { - return $this->getIdentity(); - } - - /** - * Sets the username option value - * - * @param mixed $username - * @return Digest Provides a fluent interface - */ - public function setUsername($username) - { - return $this->setIdentity($username); - } - - /** - * Returns the password option value or null if it has not yet been set - * - * @return string|null - */ - public function getPassword() - { - return $this->getCredential(); - } - - /** - * Sets the password option value - * - * @param mixed $password - * @return Digest Provides a fluent interface - */ - public function setPassword($password) - { - return $this->setCredential($password); - } - - /** - * Defined by Zend\Authentication\Adapter\AdapterInterface - * - * @throws Exception\ExceptionInterface - * @return AuthenticationResult - */ - public function authenticate() - { - $optionsRequired = array('filename', 'realm', 'identity', 'credential'); - foreach ($optionsRequired as $optionRequired) { - if (null === $this->$optionRequired) { - throw new Exception\RuntimeException("Option '$optionRequired' must be set before authentication"); - } - } - - ErrorHandler::start(E_WARNING); - $fileHandle = fopen($this->filename, 'r'); - $error = ErrorHandler::stop(); - if (false === $fileHandle) { - throw new Exception\UnexpectedValueException("Cannot open '$this->filename' for reading", 0, $error); - } - - $id = "$this->identity:$this->realm"; - $idLength = strlen($id); - - $result = array( - 'code' => AuthenticationResult::FAILURE, - 'identity' => array( - 'realm' => $this->realm, - 'username' => $this->identity, - ), - 'messages' => array() - ); - - while (($line = fgets($fileHandle)) !== false) { - $line = trim($line); - if (empty($line)) { - break; - } - if (substr($line, 0, $idLength) === $id) { - if (CryptUtils::compareStrings(substr($line, -32), md5("$this->identity:$this->realm:$this->credential"))) { - return new AuthenticationResult(AuthenticationResult::SUCCESS, $result['identity'], $result['messages']); - } - $result['messages'][] = 'Password incorrect'; - return new AuthenticationResult(AuthenticationResult::FAILURE_CREDENTIAL_INVALID, $result['identity'], $result['messages']); - } - } - - $result['messages'][] = "Username '$this->identity' and realm '$this->realm' combination not found"; - return new AuthenticationResult(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND, $result['identity'], $result['messages']); - } -} diff --git a/library/Zend/Authentication/Adapter/Exception/ExceptionInterface.php b/library/Zend/Authentication/Adapter/Exception/ExceptionInterface.php deleted file mode 100755 index 4c9b9d4be..000000000 --- a/library/Zend/Authentication/Adapter/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - 'basic'|'digest'|'basic digest' - * 'realm' => - * 'digest_domains' => Space-delimited list of URIs - * 'nonce_timeout' => - * 'use_opaque' => Whether to send the opaque value in the header - * 'algorithm' => See $supportedAlgos. Default: MD5 - * 'proxy_auth' => Whether to do authentication as a Proxy - * @throws Exception\InvalidArgumentException - */ - public function __construct(array $config) - { - $this->request = null; - $this->response = null; - $this->ieNoOpaque = false; - - if (empty($config['accept_schemes'])) { - throw new Exception\InvalidArgumentException('Config key "accept_schemes" is required'); - } - - $schemes = explode(' ', $config['accept_schemes']); - $this->acceptSchemes = array_intersect($schemes, $this->supportedSchemes); - if (empty($this->acceptSchemes)) { - throw new Exception\InvalidArgumentException(sprintf( - 'No supported schemes given in "accept_schemes". Valid values: %s', - implode(', ', $this->supportedSchemes) - )); - } - - // Double-quotes are used to delimit the realm string in the HTTP header, - // and colons are field delimiters in the password file. - if (empty($config['realm']) || - !ctype_print($config['realm']) || - strpos($config['realm'], ':') !== false || - strpos($config['realm'], '"') !== false) { - throw new Exception\InvalidArgumentException( - 'Config key \'realm\' is required, and must contain only printable characters,' - . 'excluding quotation marks and colons' - ); - } else { - $this->realm = $config['realm']; - } - - if (in_array('digest', $this->acceptSchemes)) { - if (empty($config['digest_domains']) || - !ctype_print($config['digest_domains']) || - strpos($config['digest_domains'], '"') !== false) { - throw new Exception\InvalidArgumentException( - 'Config key \'digest_domains\' is required, and must contain ' - . 'only printable characters, excluding quotation marks' - ); - } else { - $this->domains = $config['digest_domains']; - } - - if (empty($config['nonce_timeout']) || - !is_numeric($config['nonce_timeout'])) { - throw new Exception\InvalidArgumentException( - 'Config key \'nonce_timeout\' is required, and must be an integer' - ); - } else { - $this->nonceTimeout = (int) $config['nonce_timeout']; - } - - // We use the opaque value unless explicitly told not to - if (isset($config['use_opaque']) && false == (bool) $config['use_opaque']) { - $this->useOpaque = false; - } else { - $this->useOpaque = true; - } - - if (isset($config['algorithm']) && in_array($config['algorithm'], $this->supportedAlgos)) { - $this->algo = $config['algorithm']; - } else { - $this->algo = 'MD5'; - } - } - - // Don't be a proxy unless explicitly told to do so - if (isset($config['proxy_auth']) && true == (bool) $config['proxy_auth']) { - $this->imaProxy = true; // I'm a Proxy - } else { - $this->imaProxy = false; - } - } - - /** - * Setter for the basicResolver property - * - * @param Http\ResolverInterface $resolver - * @return Http Provides a fluent interface - */ - public function setBasicResolver(Http\ResolverInterface $resolver) - { - $this->basicResolver = $resolver; - - return $this; - } - - /** - * Getter for the basicResolver property - * - * @return Http\ResolverInterface - */ - public function getBasicResolver() - { - return $this->basicResolver; - } - - /** - * Setter for the digestResolver property - * - * @param Http\ResolverInterface $resolver - * @return Http Provides a fluent interface - */ - public function setDigestResolver(Http\ResolverInterface $resolver) - { - $this->digestResolver = $resolver; - - return $this; - } - - /** - * Getter for the digestResolver property - * - * @return Http\ResolverInterface - */ - public function getDigestResolver() - { - return $this->digestResolver; - } - - /** - * Setter for the Request object - * - * @param HTTPRequest $request - * @return Http Provides a fluent interface - */ - public function setRequest(HTTPRequest $request) - { - $this->request = $request; - - return $this; - } - - /** - * Getter for the Request object - * - * @return HTTPRequest - */ - public function getRequest() - { - return $this->request; - } - - /** - * Setter for the Response object - * - * @param HTTPResponse $response - * @return Http Provides a fluent interface - */ - public function setResponse(HTTPResponse $response) - { - $this->response = $response; - - return $this; - } - - /** - * Getter for the Response object - * - * @return HTTPResponse - */ - public function getResponse() - { - return $this->response; - } - - /** - * Authenticate - * - * @throws Exception\RuntimeException - * @return Authentication\Result - */ - public function authenticate() - { - if (empty($this->request) || empty($this->response)) { - throw new Exception\RuntimeException( - 'Request and Response objects must be set before calling authenticate()' - ); - } - - if ($this->imaProxy) { - $getHeader = 'Proxy-Authorization'; - } else { - $getHeader = 'Authorization'; - } - - $headers = $this->request->getHeaders(); - if (!$headers->has($getHeader)) { - return $this->challengeClient(); - } - $authHeader = $headers->get($getHeader)->getFieldValue(); - if (!$authHeader) { - return $this->challengeClient(); - } - - list($clientScheme) = explode(' ', $authHeader); - $clientScheme = strtolower($clientScheme); - - // The server can issue multiple challenges, but the client should - // answer with only the selected auth scheme. - if (!in_array($clientScheme, $this->supportedSchemes)) { - $this->response->setStatusCode(400); - return new Authentication\Result( - Authentication\Result::FAILURE_UNCATEGORIZED, - array(), - array('Client requested an incorrect or unsupported authentication scheme') - ); - } - - // client sent a scheme that is not the one required - if (!in_array($clientScheme, $this->acceptSchemes)) { - // challenge again the client - return $this->challengeClient(); - } - - switch ($clientScheme) { - case 'basic': - $result = $this->_basicAuth($authHeader); - break; - case 'digest': - $result = $this->_digestAuth($authHeader); - break; - default: - throw new Exception\RuntimeException('Unsupported authentication scheme: ' . $clientScheme); - } - - return $result; - } - - /** - * @deprecated - * @see Http::challengeClient() - * @return Authentication\Result Always returns a non-identity Auth result - */ - protected function _challengeClient() - { - trigger_error(sprintf( - 'The method "%s" is deprecated and will be removed in the future; ' - . 'please use the public method "%s::challengeClient()" instead', - __METHOD__, - __CLASS__ - ), E_USER_DEPRECATED); - - return $this->challengeClient(); - } - - /** - * Challenge Client - * - * Sets a 401 or 407 Unauthorized response code, and creates the - * appropriate Authenticate header(s) to prompt for credentials. - * - * @return Authentication\Result Always returns a non-identity Auth result - */ - public function challengeClient() - { - if ($this->imaProxy) { - $statusCode = 407; - $headerName = 'Proxy-Authenticate'; - } else { - $statusCode = 401; - $headerName = 'WWW-Authenticate'; - } - - $this->response->setStatusCode($statusCode); - - // Send a challenge in each acceptable authentication scheme - $headers = $this->response->getHeaders(); - if (in_array('basic', $this->acceptSchemes)) { - $headers->addHeaderLine($headerName, $this->_basicHeader()); - } - if (in_array('digest', $this->acceptSchemes)) { - $headers->addHeaderLine($headerName, $this->_digestHeader()); - } - return new Authentication\Result( - Authentication\Result::FAILURE_CREDENTIAL_INVALID, - array(), - array('Invalid or absent credentials; challenging client') - ); - } - - /** - * Basic Header - * - * Generates a Proxy- or WWW-Authenticate header value in the Basic - * authentication scheme. - * - * @return string Authenticate header value - */ - protected function _basicHeader() - { - return 'Basic realm="' . $this->realm . '"'; - } - - /** - * Digest Header - * - * Generates a Proxy- or WWW-Authenticate header value in the Digest - * authentication scheme. - * - * @return string Authenticate header value - */ - protected function _digestHeader() - { - $wwwauth = 'Digest realm="' . $this->realm . '", ' - . 'domain="' . $this->domains . '", ' - . 'nonce="' . $this->_calcNonce() . '", ' - . ($this->useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '') - . 'algorithm="' . $this->algo . '", ' - . 'qop="' . implode(',', $this->supportedQops) . '"'; - - return $wwwauth; - } - - /** - * Basic Authentication - * - * @param string $header Client's Authorization header - * @throws Exception\ExceptionInterface - * @return Authentication\Result - */ - protected function _basicAuth($header) - { - if (empty($header)) { - throw new Exception\RuntimeException('The value of the client Authorization header is required'); - } - if (empty($this->basicResolver)) { - throw new Exception\RuntimeException( - 'A basicResolver object must be set before doing Basic authentication' - ); - } - - // Decode the Authorization header - $auth = substr($header, strlen('Basic ')); - $auth = base64_decode($auth); - if (!$auth) { - throw new Exception\RuntimeException('Unable to base64_decode Authorization header value'); - } - - // See ZF-1253. Validate the credentials the same way the digest - // implementation does. If invalid credentials are detected, - // re-challenge the client. - if (!ctype_print($auth)) { - return $this->challengeClient(); - } - // Fix for ZF-1515: Now re-challenges on empty username or password - $creds = array_filter(explode(':', $auth)); - if (count($creds) != 2) { - return $this->challengeClient(); - } - - $result = $this->basicResolver->resolve($creds[0], $this->realm, $creds[1]); - - if ($result instanceof Authentication\Result && $result->isValid()) { - return $result; - } - - if (!$result instanceof Authentication\Result - && !is_array($result) - && CryptUtils::compareStrings($result, $creds[1]) - ) { - $identity = array('username' => $creds[0], 'realm' => $this->realm); - return new Authentication\Result(Authentication\Result::SUCCESS, $identity); - } elseif (is_array($result)) { - return new Authentication\Result(Authentication\Result::SUCCESS, $result); - } - - return $this->challengeClient(); - } - - /** - * Digest Authentication - * - * @param string $header Client's Authorization header - * @throws Exception\ExceptionInterface - * @return Authentication\Result Valid auth result only on successful auth - */ - protected function _digestAuth($header) - { - if (empty($header)) { - throw new Exception\RuntimeException('The value of the client Authorization header is required'); - } - if (empty($this->digestResolver)) { - throw new Exception\RuntimeException('A digestResolver object must be set before doing Digest authentication'); - } - - $data = $this->_parseDigestAuth($header); - if ($data === false) { - $this->response->setStatusCode(400); - return new Authentication\Result( - Authentication\Result::FAILURE_UNCATEGORIZED, - array(), - array('Invalid Authorization header format') - ); - } - - // See ZF-1052. This code was a bit too unforgiving of invalid - // usernames. Now, if the username is bad, we re-challenge the client. - if ('::invalid::' == $data['username']) { - return $this->challengeClient(); - } - - // Verify that the client sent back the same nonce - if ($this->_calcNonce() != $data['nonce']) { - return $this->challengeClient(); - } - // The opaque value is also required to match, but of course IE doesn't - // play ball. - if (!$this->ieNoOpaque && $this->_calcOpaque() != $data['opaque']) { - return $this->challengeClient(); - } - - // Look up the user's password hash. If not found, deny access. - // This makes no assumptions about how the password hash was - // constructed beyond that it must have been built in such a way as - // to be recreatable with the current settings of this object. - $ha1 = $this->digestResolver->resolve($data['username'], $data['realm']); - if ($ha1 === false) { - return $this->challengeClient(); - } - - // If MD5-sess is used, a1 value is made of the user's password - // hash with the server and client nonce appended, separated by - // colons. - if ($this->algo == 'MD5-sess') { - $ha1 = hash('md5', $ha1 . ':' . $data['nonce'] . ':' . $data['cnonce']); - } - - // Calculate h(a2). The value of this hash depends on the qop - // option selected by the client and the supported hash functions - switch ($data['qop']) { - case 'auth': - $a2 = $this->request->getMethod() . ':' . $data['uri']; - break; - case 'auth-int': - // Should be REQUEST_METHOD . ':' . uri . ':' . hash(entity-body), - // but this isn't supported yet, so fall through to default case - default: - throw new Exception\RuntimeException('Client requested an unsupported qop option'); - } - // Using hash() should make parameterizing the hash algorithm - // easier - $ha2 = hash('md5', $a2); - - // Calculate the server's version of the request-digest. This must - // match $data['response']. See RFC 2617, section 3.2.2.1 - $message = $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $ha2; - $digest = hash('md5', $ha1 . ':' . $message); - - // If our digest matches the client's let them in, otherwise return - // a 401 code and exit to prevent access to the protected resource. - if (CryptUtils::compareStrings($digest, $data['response'])) { - $identity = array('username' => $data['username'], 'realm' => $data['realm']); - return new Authentication\Result(Authentication\Result::SUCCESS, $identity); - } - - return $this->challengeClient(); - } - - /** - * Calculate Nonce - * - * @return string The nonce value - */ - protected function _calcNonce() - { - // Once subtle consequence of this timeout calculation is that it - // actually divides all of time into nonceTimeout-sized sections, such - // that the value of timeout is the point in time of the next - // approaching "boundary" of a section. This allows the server to - // consistently generate the same timeout (and hence the same nonce - // value) across requests, but only as long as one of those - // "boundaries" is not crossed between requests. If that happens, the - // nonce will change on its own, and effectively log the user out. This - // would be surprising if the user just logged in. - $timeout = ceil(time() / $this->nonceTimeout) * $this->nonceTimeout; - - $userAgentHeader = $this->request->getHeaders()->get('User-Agent'); - if ($userAgentHeader) { - $userAgent = $userAgentHeader->getFieldValue(); - } elseif (isset($_SERVER['HTTP_USER_AGENT'])) { - $userAgent = $_SERVER['HTTP_USER_AGENT']; - } else { - $userAgent = 'Zend_Authenticaion'; - } - $nonce = hash('md5', $timeout . ':' . $userAgent . ':' . __CLASS__); - return $nonce; - } - - /** - * Calculate Opaque - * - * The opaque string can be anything; the client must return it exactly as - * it was sent. It may be useful to store data in this string in some - * applications. Ideally, a new value for this would be generated each time - * a WWW-Authenticate header is sent (in order to reduce predictability), - * but we would have to be able to create the same exact value across at - * least two separate requests from the same client. - * - * @return string The opaque value - */ - protected function _calcOpaque() - { - return hash('md5', 'Opaque Data:' . __CLASS__); - } - - /** - * Parse Digest Authorization header - * - * @param string $header Client's Authorization: HTTP header - * @return array|bool Data elements from header, or false if any part of - * the header is invalid - */ - protected function _parseDigestAuth($header) - { - $temp = null; - $data = array(); - - // See ZF-1052. Detect invalid usernames instead of just returning a - // 400 code. - $ret = preg_match('/username="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1]) - || !ctype_print($temp[1]) - || strpos($temp[1], ':') !== false) { - $data['username'] = '::invalid::'; - } else { - $data['username'] = $temp[1]; - } - $temp = null; - - $ret = preg_match('/realm="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) { - return false; - } else { - $data['realm'] = $temp[1]; - } - $temp = null; - - $ret = preg_match('/nonce="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!ctype_xdigit($temp[1])) { - return false; - } - - $data['nonce'] = $temp[1]; - $temp = null; - - $ret = preg_match('/uri="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - // Section 3.2.2.5 in RFC 2617 says the authenticating server must - // verify that the URI field in the Authorization header is for the - // same resource requested in the Request Line. - $rUri = $this->request->getUri(); - $cUri = UriFactory::factory($temp[1]); - - // Make sure the path portion of both URIs is the same - if ($rUri->getPath() != $cUri->getPath()) { - return false; - } - - // Section 3.2.2.5 seems to suggest that the value of the URI - // Authorization field should be made into an absolute URI if the - // Request URI is absolute, but it's vague, and that's a bunch of - // code I don't want to write right now. - $data['uri'] = $temp[1]; - $temp = null; - - $ret = preg_match('/response="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { - return false; - } - - $data['response'] = $temp[1]; - $temp = null; - - // The spec says this should default to MD5 if omitted. OK, so how does - // that square with the algo we send out in the WWW-Authenticate header, - // if it can easily be overridden by the client? - $ret = preg_match('/algorithm="?(' . $this->algo . ')"?/', $header, $temp); - if ($ret && !empty($temp[1]) - && in_array($temp[1], $this->supportedAlgos)) { - $data['algorithm'] = $temp[1]; - } else { - $data['algorithm'] = 'MD5'; // = $this->algo; ? - } - $temp = null; - - // Not optional in this implementation - $ret = preg_match('/cnonce="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!ctype_print($temp[1])) { - return false; - } - - $data['cnonce'] = $temp[1]; - $temp = null; - - // If the server sent an opaque value, the client must send it back - if ($this->useOpaque) { - $ret = preg_match('/opaque="([^"]+)"/', $header, $temp); - if (!$ret || empty($temp[1])) { - // Big surprise: IE isn't RFC 2617-compliant. - $headers = $this->request->getHeaders(); - if (!$headers->has('User-Agent')) { - return false; - } - $userAgent = $headers->get('User-Agent')->getFieldValue(); - if (false === strpos($userAgent, 'MSIE')) { - return false; - } - - $temp[1] = ''; - $this->ieNoOpaque = true; - } - - // This implementation only sends MD5 hex strings in the opaque value - if (!$this->ieNoOpaque && - (32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) { - return false; - } - - $data['opaque'] = $temp[1]; - $temp = null; - } - - // Not optional in this implementation, but must be one of the supported - // qop types - $ret = preg_match('/qop="?(' . implode('|', $this->supportedQops) . ')"?/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (!in_array($temp[1], $this->supportedQops)) { - return false; - } - - $data['qop'] = $temp[1]; - $temp = null; - - // Not optional in this implementation. The spec says this value - // shouldn't be a quoted string, but apparently some implementations - // quote it anyway. See ZF-1544. - $ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp); - if (!$ret || empty($temp[1])) { - return false; - } - if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { - return false; - } - - $data['nc'] = $temp[1]; - $temp = null; - - return $data; - } -} diff --git a/library/Zend/Authentication/Adapter/Http/ApacheResolver.php b/library/Zend/Authentication/Adapter/Http/ApacheResolver.php deleted file mode 100755 index a7b8b3d6d..000000000 --- a/library/Zend/Authentication/Adapter/Http/ApacheResolver.php +++ /dev/null @@ -1,171 +0,0 @@ -setFile($path); - } - } - - /** - * Set the path to the credentials file - * - * @param string $path - * @return self Provides a fluent interface - * @throws Exception\InvalidArgumentException if path is not readable - */ - public function setFile($path) - { - if (empty($path) || !is_readable($path)) { - throw new Exception\InvalidArgumentException('Path not readable: ' . $path); - } - $this->file = $path; - - return $this; - } - - /** - * Returns the path to the credentials file - * - * @return string - */ - public function getFile() - { - return $this->file; - } - - /** - * Returns the Apache Password object - * - * @return ApachePassword - */ - protected function getApachePassword() - { - if (empty($this->apachePassword)) { - $this->apachePassword = new ApachePassword(); - } - return $this->apachePassword; - } - - /** - * Resolve credentials - * - * - * - * @param string $username Username - * @param string $realm Authentication Realm - * @param string $password The password to authenticate - * @return AuthResult - * @throws Exception\ExceptionInterface - */ - public function resolve($username, $realm, $password = null) - { - if (empty($username)) { - throw new Exception\InvalidArgumentException('Username is required'); - } - - if (!ctype_print($username) || strpos($username, ':') !== false) { - throw new Exception\InvalidArgumentException( - 'Username must consist only of printable characters, excluding the colon' - ); - } - - if (!empty($realm) && (!ctype_print($realm) || strpos($realm, ':') !== false)) { - throw new Exception\InvalidArgumentException( - 'Realm must consist only of printable characters, excluding the colon' - ); - } - - if (empty($password)) { - throw new Exception\InvalidArgumentException('Password is required'); - } - - // Open file, read through looking for matching credentials - ErrorHandler::start(E_WARNING); - $fp = fopen($this->file, 'r'); - $error = ErrorHandler::stop(); - if (!$fp) { - throw new Exception\RuntimeException('Unable to open password file: ' . $this->file, 0, $error); - } - - // No real validation is done on the contents of the password file. The - // assumption is that we trust the administrators to keep it secure. - while (($line = fgetcsv($fp, 512, ':')) !== false) { - if ($line[0] != $username) { - continue; - } - - if (isset($line[2])) { - if ($line[1] == $realm) { - $matchedHash = $line[2]; - break; - } - continue; - } - - $matchedHash = $line[1]; - break; - } - fclose($fp); - - if (!isset($matchedHash)) { - return new AuthResult(AuthResult::FAILURE_IDENTITY_NOT_FOUND, null, array('Username not found in provided htpasswd file')); - } - - // Plaintext password - if ($matchedHash === $password) { - return new AuthResult(AuthResult::SUCCESS, $username); - } - - $apache = $this->getApachePassword(); - $apache->setUserName($username); - if (!empty($realm)) { - $apache->setAuthName($realm); - } - - if ($apache->verify($password, $matchedHash)) { - return new AuthResult(AuthResult::SUCCESS, $username); - } - - return new AuthResult(AuthResult::FAILURE_CREDENTIAL_INVALID, null, array('Passwords did not match.')); - } -} diff --git a/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php b/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php deleted file mode 100755 index 4ec6a3f7c..000000000 --- a/library/Zend/Authentication/Adapter/Http/Exception/ExceptionInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -setFile($path); - } - } - - /** - * Set the path to the credentials file - * - * @param string $path - * @return FileResolver Provides a fluent interface - * @throws Exception\InvalidArgumentException if path is not readable - */ - public function setFile($path) - { - if (empty($path) || !is_readable($path)) { - throw new Exception\InvalidArgumentException('Path not readable: ' . $path); - } - $this->file = $path; - - return $this; - } - - /** - * Returns the path to the credentials file - * - * @return string - */ - public function getFile() - { - return $this->file; - } - - /** - * Resolve credentials - * - * Only the first matching username/realm combination in the file is - * returned. If the file contains credentials for Digest authentication, - * the returned string is the password hash, or h(a1) from RFC 2617. The - * returned string is the plain-text password for Basic authentication. - * - * The expected format of the file is: - * username:realm:sharedSecret - * - * That is, each line consists of the user's username, the applicable - * authentication realm, and the password or hash, each delimited by - * colons. - * - * @param string $username Username - * @param string $realm Authentication Realm - * @return string|false User's shared secret, if the user is found in the - * realm, false otherwise. - * @throws Exception\ExceptionInterface - */ - public function resolve($username, $realm, $password = null) - { - if (empty($username)) { - throw new Exception\InvalidArgumentException('Username is required'); - } elseif (!ctype_print($username) || strpos($username, ':') !== false) { - throw new Exception\InvalidArgumentException( - 'Username must consist only of printable characters, excluding the colon' - ); - } - if (empty($realm)) { - throw new Exception\InvalidArgumentException('Realm is required'); - } elseif (!ctype_print($realm) || strpos($realm, ':') !== false) { - throw new Exception\InvalidArgumentException( - 'Realm must consist only of printable characters, excluding the colon.' - ); - } - - // Open file, read through looking for matching credentials - ErrorHandler::start(E_WARNING); - $fp = fopen($this->file, 'r'); - $error = ErrorHandler::stop(); - if (!$fp) { - throw new Exception\RuntimeException('Unable to open password file: ' . $this->file, 0, $error); - } - - // No real validation is done on the contents of the password file. The - // assumption is that we trust the administrators to keep it secure. - while (($line = fgetcsv($fp, 512, ':')) !== false) { - if ($line[0] == $username && $line[1] == $realm) { - $password = $line[2]; - fclose($fp); - return $password; - } - } - - fclose($fp); - return false; - } -} diff --git a/library/Zend/Authentication/Adapter/Http/ResolverInterface.php b/library/Zend/Authentication/Adapter/Http/ResolverInterface.php deleted file mode 100755 index b236f8458..000000000 --- a/library/Zend/Authentication/Adapter/Http/ResolverInterface.php +++ /dev/null @@ -1,30 +0,0 @@ -setOptions($options); - if ($identity !== null) { - $this->setIdentity($identity); - } - if ($credential !== null) { - $this->setCredential($credential); - } - } - - /** - * Returns the array of arrays of Zend\Ldap\Ldap options of this adapter. - * - * @return array|null - */ - public function getOptions() - { - return $this->options; - } - - /** - * Sets the array of arrays of Zend\Ldap\Ldap options to be used by - * this adapter. - * - * @param array $options The array of arrays of Zend\Ldap\Ldap options - * @return Ldap Provides a fluent interface - */ - public function setOptions($options) - { - $this->options = is_array($options) ? $options : array(); - if (array_key_exists('identity', $this->options)) { - $this->options['username'] = $this->options['identity']; - } - if (array_key_exists('credential', $this->options)) { - $this->options['password'] = $this->options['credential']; - } - return $this; - } - - /** - * Returns the username of the account being authenticated, or - * NULL if none is set. - * - * @return string|null - */ - public function getUsername() - { - return $this->getIdentity(); - } - - /** - * Sets the username for binding - * - * @param string $username The username for binding - * @return Ldap Provides a fluent interface - */ - public function setUsername($username) - { - return $this->setIdentity($username); - } - - /** - * Returns the password of the account being authenticated, or - * NULL if none is set. - * - * @return string|null - */ - public function getPassword() - { - return $this->getCredential(); - } - - /** - * Sets the password for the account - * - * @param string $password The password of the account being authenticated - * @return Ldap Provides a fluent interface - */ - public function setPassword($password) - { - return $this->setCredential($password); - } - - /** - * Returns the LDAP Object - * - * @return ZendLdap\Ldap The Zend\Ldap\Ldap object used to authenticate the credentials - */ - public function getLdap() - { - if ($this->ldap === null) { - $this->ldap = new ZendLdap\Ldap(); - } - - return $this->ldap; - } - - /** - * Set an Ldap connection - * - * @param ZendLdap\Ldap $ldap An existing Ldap object - * @return Ldap Provides a fluent interface - */ - public function setLdap(ZendLdap\Ldap $ldap) - { - $this->ldap = $ldap; - - $this->setOptions(array($ldap->getOptions())); - - return $this; - } - - /** - * Returns a domain name for the current LDAP options. This is used - * for skipping redundant operations (e.g. authentications). - * - * @return string - */ - protected function getAuthorityName() - { - $options = $this->getLdap()->getOptions(); - $name = $options['accountDomainName']; - if (!$name) { - $name = $options['accountDomainNameShort']; - } - - return $name ? $name : ''; - } - - /** - * Authenticate the user - * - * @return AuthenticationResult - * @throws Exception\ExceptionInterface - */ - public function authenticate() - { - $messages = array(); - $messages[0] = ''; // reserved - $messages[1] = ''; // reserved - - $username = $this->identity; - $password = $this->credential; - - if (!$username) { - $code = AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND; - $messages[0] = 'A username is required'; - return new AuthenticationResult($code, '', $messages); - } - if (!$password) { - /* A password is required because some servers will - * treat an empty password as an anonymous bind. - */ - $code = AuthenticationResult::FAILURE_CREDENTIAL_INVALID; - $messages[0] = 'A password is required'; - return new AuthenticationResult($code, '', $messages); - } - - $ldap = $this->getLdap(); - - $code = AuthenticationResult::FAILURE; - $messages[0] = "Authority not found: $username"; - $failedAuthorities = array(); - - /* Iterate through each server and try to authenticate the supplied - * credentials against it. - */ - foreach ($this->options as $options) { - if (!is_array($options)) { - throw new Exception\InvalidArgumentException('Adapter options array not an array'); - } - $adapterOptions = $this->prepareOptions($ldap, $options); - $dname = ''; - - try { - if ($messages[1]) { - $messages[] = $messages[1]; - } - - $messages[1] = ''; - $messages[] = $this->optionsToString($options); - - $dname = $this->getAuthorityName(); - if (isset($failedAuthorities[$dname])) { - /* If multiple sets of server options for the same domain - * are supplied, we want to skip redundant authentications - * where the identity or credentials where found to be - * invalid with another server for the same domain. The - * $failedAuthorities array tracks this condition (and also - * serves to supply the original error message). - * This fixes issue ZF-4093. - */ - $messages[1] = $failedAuthorities[$dname]; - $messages[] = "Skipping previously failed authority: $dname"; - continue; - } - - $canonicalName = $ldap->getCanonicalAccountName($username); - $ldap->bind($canonicalName, $password); - /* - * Fixes problem when authenticated user is not allowed to retrieve - * group-membership information or own account. - * This requires that the user specified with "username" and optionally - * "password" in the Zend\Ldap\Ldap options is able to retrieve the required - * information. - */ - $requireRebind = false; - if (isset($options['username'])) { - $ldap->bind(); - $requireRebind = true; - } - $dn = $ldap->getCanonicalAccountName($canonicalName, ZendLdap\Ldap::ACCTNAME_FORM_DN); - - $groupResult = $this->checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions); - if ($groupResult === true) { - $this->authenticatedDn = $dn; - $messages[0] = ''; - $messages[1] = ''; - $messages[] = "$canonicalName authentication successful"; - if ($requireRebind === true) { - // rebinding with authenticated user - $ldap->bind($dn, $password); - } - return new AuthenticationResult(AuthenticationResult::SUCCESS, $canonicalName, $messages); - } else { - $messages[0] = 'Account is not a member of the specified group'; - $messages[1] = $groupResult; - $failedAuthorities[$dname] = $groupResult; - } - } catch (LdapException $zle) { - /* LDAP based authentication is notoriously difficult to diagnose. Therefore - * we bend over backwards to capture and record every possible bit of - * information when something goes wrong. - */ - - $err = $zle->getCode(); - - if ($err == LdapException::LDAP_X_DOMAIN_MISMATCH) { - /* This error indicates that the domain supplied in the - * username did not match the domains in the server options - * and therefore we should just skip to the next set of - * server options. - */ - continue; - } elseif ($err == LdapException::LDAP_NO_SUCH_OBJECT) { - $code = AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND; - $messages[0] = "Account not found: $username"; - $failedAuthorities[$dname] = $zle->getMessage(); - } elseif ($err == LdapException::LDAP_INVALID_CREDENTIALS) { - $code = AuthenticationResult::FAILURE_CREDENTIAL_INVALID; - $messages[0] = 'Invalid credentials'; - $failedAuthorities[$dname] = $zle->getMessage(); - } else { - $line = $zle->getLine(); - $messages[] = $zle->getFile() . "($line): " . $zle->getMessage(); - $messages[] = preg_replace( - '/\b'.preg_quote(substr($password, 0, 15), '/').'\b/', - '*****', - $zle->getTraceAsString() - ); - $messages[0] = 'An unexpected failure occurred'; - } - $messages[1] = $zle->getMessage(); - } - } - - $msg = isset($messages[1]) ? $messages[1] : $messages[0]; - $messages[] = "$username authentication failed: $msg"; - - return new AuthenticationResult($code, $username, $messages); - } - - /** - * Sets the LDAP specific options on the Zend\Ldap\Ldap instance - * - * @param ZendLdap\Ldap $ldap - * @param array $options - * @return array of auth-adapter specific options - */ - protected function prepareOptions(ZendLdap\Ldap $ldap, array $options) - { - $adapterOptions = array( - 'group' => null, - 'groupDn' => $ldap->getBaseDn(), - 'groupScope' => ZendLdap\Ldap::SEARCH_SCOPE_SUB, - 'groupAttr' => 'cn', - 'groupFilter' => 'objectClass=groupOfUniqueNames', - 'memberAttr' => 'uniqueMember', - 'memberIsDn' => true - ); - foreach ($adapterOptions as $key => $value) { - if (array_key_exists($key, $options)) { - $value = $options[$key]; - unset($options[$key]); - switch ($key) { - case 'groupScope': - $value = (int) $value; - if (in_array( - $value, - array( - ZendLdap\Ldap::SEARCH_SCOPE_BASE, - ZendLdap\Ldap::SEARCH_SCOPE_ONE, - ZendLdap\Ldap::SEARCH_SCOPE_SUB, - ), - true - )) { - $adapterOptions[$key] = $value; - } - break; - case 'memberIsDn': - $adapterOptions[$key] = ($value === true || - $value === '1' || strcasecmp($value, 'true') == 0); - break; - default: - $adapterOptions[$key] = trim($value); - break; - } - } - } - $ldap->setOptions($options); - return $adapterOptions; - } - - /** - * Checks the group membership of the bound user - * - * @param ZendLdap\Ldap $ldap - * @param string $canonicalName - * @param string $dn - * @param array $adapterOptions - * @return string|true - */ - protected function checkGroupMembership(ZendLdap\Ldap $ldap, $canonicalName, $dn, array $adapterOptions) - { - if ($adapterOptions['group'] === null) { - return true; - } - - if ($adapterOptions['memberIsDn'] === false) { - $user = $canonicalName; - } else { - $user = $dn; - } - - $groupName = ZendLdap\Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']); - $membership = ZendLdap\Filter::equals($adapterOptions['memberAttr'], $user); - $group = ZendLdap\Filter::andFilter($groupName, $membership); - $groupFilter = $adapterOptions['groupFilter']; - if (!empty($groupFilter)) { - $group = $group->addAnd($groupFilter); - } - - $result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']); - - if ($result === 1) { - return true; - } - - return 'Failed to verify group membership with ' . $group->toString(); - } - - /** - * getAccountObject() - Returns the result entry as a stdClass object - * - * This resembles the feature {@see Zend\Authentication\Adapter\DbTable::getResultRowObject()}. - * Closes ZF-6813 - * - * @param array $returnAttribs - * @param array $omitAttribs - * @return stdClass|bool - */ - public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array()) - { - if (!$this->authenticatedDn) { - return false; - } - - $returnObject = new stdClass(); - - $returnAttribs = array_map('strtolower', $returnAttribs); - $omitAttribs = array_map('strtolower', $omitAttribs); - $returnAttribs = array_diff($returnAttribs, $omitAttribs); - - $entry = $this->getLdap()->getEntry($this->authenticatedDn, $returnAttribs, true); - foreach ($entry as $attr => $value) { - if (in_array($attr, $omitAttribs)) { - // skip attributes marked to be omitted - continue; - } - if (is_array($value)) { - $returnObject->$attr = (count($value) > 1) ? $value : $value[0]; - } else { - $returnObject->$attr = $value; - } - } - return $returnObject; - } - - /** - * Converts options to string - * - * @param array $options - * @return string - */ - private function optionsToString(array $options) - { - $str = ''; - foreach ($options as $key => $val) { - if ($key === 'password' || $key === 'credential') { - $val = '*****'; - } - if ($str) { - $str .= ','; - } - $str .= $key . '=' . $val; - } - return $str; - } -} diff --git a/library/Zend/Authentication/Adapter/ValidatableAdapterInterface.php b/library/Zend/Authentication/Adapter/ValidatableAdapterInterface.php deleted file mode 100755 index 3c4f01b2c..000000000 --- a/library/Zend/Authentication/Adapter/ValidatableAdapterInterface.php +++ /dev/null @@ -1,45 +0,0 @@ -setStorage($storage); - } - if (null !== $adapter) { - $this->setAdapter($adapter); - } - } - - /** - * Returns the authentication adapter - * - * The adapter does not have a default if the storage adapter has not been set. - * - * @return Adapter\AdapterInterface|null - */ - public function getAdapter() - { - return $this->adapter; - } - - /** - * Sets the authentication adapter - * - * @param Adapter\AdapterInterface $adapter - * @return AuthenticationService Provides a fluent interface - */ - public function setAdapter(Adapter\AdapterInterface $adapter) - { - $this->adapter = $adapter; - return $this; - } - - /** - * Returns the persistent storage handler - * - * Session storage is used by default unless a different storage adapter has been set. - * - * @return Storage\StorageInterface - */ - public function getStorage() - { - if (null === $this->storage) { - $this->setStorage(new Storage\Session()); - } - - return $this->storage; - } - - /** - * Sets the persistent storage handler - * - * @param Storage\StorageInterface $storage - * @return AuthenticationService Provides a fluent interface - */ - public function setStorage(Storage\StorageInterface $storage) - { - $this->storage = $storage; - return $this; - } - - /** - * Authenticates against the supplied adapter - * - * @param Adapter\AdapterInterface $adapter - * @return Result - * @throws Exception\RuntimeException - */ - public function authenticate(Adapter\AdapterInterface $adapter = null) - { - if (!$adapter) { - if (!$adapter = $this->getAdapter()) { - throw new Exception\RuntimeException('An adapter must be set or passed prior to calling authenticate()'); - } - } - $result = $adapter->authenticate(); - - /** - * ZF-7546 - prevent multiple successive calls from storing inconsistent results - * Ensure storage has clean state - */ - if ($this->hasIdentity()) { - $this->clearIdentity(); - } - - if ($result->isValid()) { - $this->getStorage()->write($result->getIdentity()); - } - - return $result; - } - - /** - * Returns true if and only if an identity is available from storage - * - * @return bool - */ - public function hasIdentity() - { - return !$this->getStorage()->isEmpty(); - } - - /** - * Returns the identity from storage or null if no identity is available - * - * @return mixed|null - */ - public function getIdentity() - { - $storage = $this->getStorage(); - - if ($storage->isEmpty()) { - return null; - } - - return $storage->read(); - } - - /** - * Clears the identity from persistent storage - * - * @return void - */ - public function clearIdentity() - { - $this->getStorage()->clear(); - } -} diff --git a/library/Zend/Authentication/AuthenticationServiceInterface.php b/library/Zend/Authentication/AuthenticationServiceInterface.php deleted file mode 100755 index fcf74ea17..000000000 --- a/library/Zend/Authentication/AuthenticationServiceInterface.php +++ /dev/null @@ -1,44 +0,0 @@ -code = (int) $code; - $this->identity = $identity; - $this->messages = $messages; - } - - /** - * Returns whether the result represents a successful authentication attempt - * - * @return bool - */ - public function isValid() - { - return ($this->code > 0) ? true : false; - } - - /** - * getCode() - Get the result code for this authentication attempt - * - * @return int - */ - public function getCode() - { - return $this->code; - } - - /** - * Returns the identity used in the authentication attempt - * - * @return mixed - */ - public function getIdentity() - { - return $this->identity; - } - - /** - * Returns an array of string reasons why the authentication attempt was unsuccessful - * - * If authentication was successful, this method returns an empty array. - * - * @return array - */ - public function getMessages() - { - return $this->messages; - } -} diff --git a/library/Zend/Authentication/Storage/Chain.php b/library/Zend/Authentication/Storage/Chain.php deleted file mode 100755 index 8d995a2c0..000000000 --- a/library/Zend/Authentication/Storage/Chain.php +++ /dev/null @@ -1,109 +0,0 @@ -storageChain = new PriorityQueue(); - } - - /** - * @param StorageInterface $storage - * @param int $priority - */ - public function add(StorageInterface $storage, $priority = 1) - { - $this->storageChain->insert($storage, $priority); - } - - /** - * Loop over the queue of storage until a storage is found that is non-empty. If such - * storage is not found, then this chain storage itself is empty. - * - * In case a non-empty storage is found then this chain storage is also non-empty. Report - * that, but also make sure that all storage with higher priorty that are empty - * are filled. - * - * @see StorageInterface::isEmpty() - */ - public function isEmpty() - { - $storageWithHigherPriority = array(); - - // Loop invariant: $storageWithHigherPriority contains all storage with higher priorty - // than the current one. - foreach ($this->storageChain as $storage) { - if ($storage->isEmpty()) { - $storageWithHigherPriority[] = $storage; - continue; - } - - $storageValue = $storage->read(); - foreach ($storageWithHigherPriority as $higherPriorityStorage) { - $higherPriorityStorage->write($storageValue); - } - - return false; - } - - return true; - } - - /** - * If the chain is non-empty then the storage with the top priority is guaranteed to be - * filled. Return its value. - * - * @see StorageInterface::read() - */ - public function read() - { - return $this->storageChain->top()->read(); - } - - /** - * Write the new $contents to all storage in the chain. - * - * @see StorageInterface::write() - */ - public function write($contents) - { - foreach ($this->storageChain as $storage) { - $storage->write($contents); - } - } - - /** - * Clear all storage in the chain. - * - * @see StorageInterface::clear() - */ - public function clear() - { - foreach ($this->storageChain as $storage) { - $storage->clear(); - } - } -} diff --git a/library/Zend/Authentication/Storage/NonPersistent.php b/library/Zend/Authentication/Storage/NonPersistent.php deleted file mode 100755 index 8d1204939..000000000 --- a/library/Zend/Authentication/Storage/NonPersistent.php +++ /dev/null @@ -1,67 +0,0 @@ -data); - } - - /** - * Returns the contents of storage - * Behavior is undefined when storage is empty. - * - * @return mixed - */ - public function read() - { - return $this->data; - } - - /** - * Writes $contents to storage - * - * @param mixed $contents - * @return void - */ - public function write($contents) - { - $this->data = $contents; - } - - /** - * Clears contents from storage - * - * @return void - */ - public function clear() - { - $this->data = null; - } -} diff --git a/library/Zend/Authentication/Storage/Session.php b/library/Zend/Authentication/Storage/Session.php deleted file mode 100755 index 6c66bec8f..000000000 --- a/library/Zend/Authentication/Storage/Session.php +++ /dev/null @@ -1,126 +0,0 @@ -namespace = $namespace; - } - if ($member !== null) { - $this->member = $member; - } - $this->session = new SessionContainer($this->namespace, $manager); - } - - /** - * Returns the session namespace - * - * @return string - */ - public function getNamespace() - { - return $this->namespace; - } - - /** - * Returns the name of the session object member - * - * @return string - */ - public function getMember() - { - return $this->member; - } - - /** - * Defined by Zend\Authentication\Storage\StorageInterface - * - * @return bool - */ - public function isEmpty() - { - return !isset($this->session->{$this->member}); - } - - /** - * Defined by Zend\Authentication\Storage\StorageInterface - * - * @return mixed - */ - public function read() - { - return $this->session->{$this->member}; - } - - /** - * Defined by Zend\Authentication\Storage\StorageInterface - * - * @param mixed $contents - * @return void - */ - public function write($contents) - { - $this->session->{$this->member} = $contents; - } - - /** - * Defined by Zend\Authentication\Storage\StorageInterface - * - * @return void - */ - public function clear() - { - unset($this->session->{$this->member}); - } -} diff --git a/library/Zend/Authentication/Storage/StorageInterface.php b/library/Zend/Authentication/Storage/StorageInterface.php deleted file mode 100755 index 4a9d41b9e..000000000 --- a/library/Zend/Authentication/Storage/StorageInterface.php +++ /dev/null @@ -1,48 +0,0 @@ - 'Invalid identity', - self::IDENTITY_AMBIGUOUS => 'Identity is ambiguous', - self::CREDENTIAL_INVALID => 'Invalid password', - self::UNCATEGORIZED => 'Authentication failed', - self::GENERAL => 'Authentication failed', - ); - - /** - * Authentication Adapter - * @var ValidatableAdapterInterface - */ - protected $adapter; - - /** - * Identity (or field) - * @var string - */ - protected $identity; - - /** - * Credential (or field) - * @var string - */ - protected $credential; - - /** - * Authentication Service - * @var AuthenticationService - */ - protected $service; - - /** - * Sets validator options - * - * @param mixed $options - */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (is_array($options)) { - if (array_key_exists('adapter', $options)) { - $this->setAdapter($options['adapter']); - } - if (array_key_exists('identity', $options)) { - $this->setIdentity($options['identity']); - } - if (array_key_exists('credential', $options)) { - $this->setCredential($options['credential']); - } - if (array_key_exists('service', $options)) { - $this->setService($options['service']); - } - } - parent::__construct($options); - } - - /** - * Get Adapter - * - * @return ValidatableAdapterInterface - */ - public function getAdapter() - { - return $this->adapter; - } - - /** - * Set Adapter - * - * @param ValidatableAdapterInterface $adapter - * @return Authentication - */ - public function setAdapter(ValidatableAdapterInterface $adapter) - { - $this->adapter = $adapter; - - return $this; - } - - /** - * Get Identity - * - * @return mixed - */ - public function getIdentity() - { - return $this->identity; - } - - /** - * Set Identity - * - * @param mixed $identity - * @return Authentication - */ - public function setIdentity($identity) - { - $this->identity = $identity; - - return $this; - } - - /** - * Get Credential - * - * @return mixed - */ - public function getCredential() - { - return $this->credential; - } - - /** - * Set Credential - * - * @param mixed $credential - * @return Authentication - */ - public function setCredential($credential) - { - $this->credential = $credential; - - return $this; - } - - /** - * Get Service - * - * @return AuthenticationService - */ - public function getService() - { - return $this->service; - } - - /** - * Set Service - * - * @param AuthenticationService $service - * @return Authentication - */ - public function setService(AuthenticationService $service) - { - $this->service = $service; - - return $this; - } - - /** - * Is Valid - * - * @param mixed $value - * @param array $context - * @return bool - */ - public function isValid($value = null, $context = null) - { - if ($value !== null) { - $this->setCredential($value); - } - - if (($context !== null) && array_key_exists($this->identity, $context)) { - $identity = $context[$this->identity]; - } else { - $identity = $this->identity; - } - if (!$this->identity) { - throw new Exception\RuntimeException('Identity must be set prior to validation'); - } - - if (($context !== null) && array_key_exists($this->credential, $context)) { - $credential = $context[$this->credential]; - } else { - $credential = $this->credential; - } - - if (!$this->adapter) { - throw new Exception\RuntimeException('Adapter must be set prior to validation'); - } - $this->adapter->setIdentity($identity); - $this->adapter->setCredential($credential); - - if (!$this->service) { - throw new Exception\RuntimeException('AuthenticationService must be set prior to validation'); - } - $result = $this->service->authenticate($this->adapter); - - if ($result->getCode() != Result::SUCCESS) { - switch ($result->getCode()) { - case Result::FAILURE_IDENTITY_NOT_FOUND: - $this->error(self::IDENTITY_NOT_FOUND); - break; - case Result::FAILURE_CREDENTIAL_INVALID: - $this->error(self::CREDENTIAL_INVALID); - break; - case Result::FAILURE_IDENTITY_AMBIGUOUS: - $this->error(self::IDENTITY_AMBIGUOUS); - break; - case Result::FAILURE_UNCATEGORIZED: - $this->error(self::UNCATEGORIZED); - break; - default: - $this->error(self::GENERAL); - } - - return false; - } - - return true; - } -} diff --git a/library/Zend/Authentication/composer.json b/library/Zend/Authentication/composer.json deleted file mode 100755 index fd6d242b9..000000000 --- a/library/Zend/Authentication/composer.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "zendframework/zend-authentication", - "description": "provides an API for authentication and includes concrete authentication adapters for common use case scenarios", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "authentication" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Authentication\\": "" - } - }, - "target-dir": "Zend/Authentication", - "require": { - "php": ">=5.3.23", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-db": "self.version", - "zendframework/zend-crypt": "self.version", - "zendframework/zend-http": "self.version", - "zendframework/zend-ldap": "self.version", - "zendframework/zend-session": "self.version", - "zendframework/zend-validator": "self.version", - "zendframework/zend-uri": "self.version" - }, - "suggest": { - "zendframework/zend-db": "Zend\\Db component", - "zendframework/zend-crypt": "Zend\\Crypt component", - "zendframework/zend-http": "Zend\\Http component", - "zendframework/zend-ldap": "Zend\\Ldap component", - "zendframework/zend-session": "Zend\\Session component", - "zendframework/zend-uri": "Zend\\Uri component", - "zendframework/zend-validator": "Zend\\Validator component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Barcode/Barcode.php b/library/Zend/Barcode/Barcode.php deleted file mode 100755 index b2176b478..000000000 --- a/library/Zend/Barcode/Barcode.php +++ /dev/null @@ -1,304 +0,0 @@ - $e->getMessage())); - $renderer = static::makeRenderer($renderer, array()); - } else { - throw $e; - } - } - - $renderer->setAutomaticRenderError($automaticRenderError); - return $renderer->setBarcode($barcode); - } - - /** - * Barcode Constructor - * - * @param mixed $barcode String name of barcode class, or Traversable object, or barcode object. - * @param mixed $barcodeConfig OPTIONAL; an array or Traversable object with barcode parameters. - * @throws Exception\InvalidArgumentException - * @return Object - */ - public static function makeBarcode($barcode, $barcodeConfig = array()) - { - if ($barcode instanceof Object\ObjectInterface) { - return $barcode; - } - - /* - * Convert Traversable argument to plain string - * barcode name and separate configuration. - */ - if ($barcode instanceof Traversable) { - $barcode = ArrayUtils::iteratorToArray($barcode); - if (isset($barcode['barcodeParams']) && is_array($barcode['barcodeParams'])) { - $barcodeConfig = $barcode['barcodeParams']; - } - if (isset($barcode['barcode'])) { - $barcode = (string) $barcode['barcode']; - } else { - $barcode = null; - } - } - if ($barcodeConfig instanceof Traversable) { - $barcodeConfig = ArrayUtils::iteratorToArray($barcodeConfig); - } - - /* - * Verify that barcode parameters are in an array. - */ - if (!is_array($barcodeConfig)) { - throw new Exception\InvalidArgumentException( - 'Barcode parameters must be in an array or a Traversable object' - ); - } - - /* - * Verify that a barcode name has been specified. - */ - if (!is_string($barcode) || empty($barcode)) { - throw new Exception\InvalidArgumentException( - 'Barcode name must be specified in a string' - ); - } - - return static::getObjectPluginManager()->get($barcode, $barcodeConfig); - } - - /** - * Renderer Constructor - * - * @param mixed $renderer String name of renderer class, or Traversable object. - * @param mixed $rendererConfig OPTIONAL; an array or Traversable object with renderer parameters. - * @throws Exception\RendererCreationException - * @return Renderer\RendererInterface - */ - public static function makeRenderer($renderer = 'image', $rendererConfig = array()) - { - if ($renderer instanceof Renderer\RendererInterface) { - return $renderer; - } - - /* - * Convert Traversable argument to plain string - * barcode name and separate config object. - */ - if ($renderer instanceof Traversable) { - $renderer = ArrayUtils::iteratorToArray($renderer); - if (isset($renderer['rendererParams'])) { - $rendererConfig = $renderer['rendererParams']; - } - if (isset($renderer['renderer'])) { - $renderer = (string) $renderer['renderer']; - } - } - if ($rendererConfig instanceof Traversable) { - $rendererConfig = ArrayUtils::iteratorToArray($rendererConfig); - } - - /* - * Verify that barcode parameters are in an array. - */ - if (!is_array($rendererConfig)) { - throw new Exception\RendererCreationException( - 'Barcode parameters must be in an array or a Traversable object' - ); - } - - /* - * Verify that a barcode name has been specified. - */ - if (!is_string($renderer) || empty($renderer)) { - throw new Exception\RendererCreationException( - 'Renderer name must be specified in a string' - ); - } - - return static::getRendererPluginManager()->get($renderer, $rendererConfig); - } - - /** - * Proxy to renderer render() method - * - * @param string | Object\ObjectInterface | array | Traversable $barcode - * @param string | Renderer\RendererInterface $renderer - * @param array | Traversable $barcodeConfig - * @param array | Traversable $rendererConfig - */ - public static function render( - $barcode, - $renderer, - $barcodeConfig = array(), - $rendererConfig = array() - ) { - static::factory($barcode, $renderer, $barcodeConfig, $rendererConfig)->render(); - } - - /** - * Proxy to renderer draw() method - * - * @param string | Object\ObjectInterface | array | Traversable $barcode - * @param string | Renderer\RendererInterface $renderer - * @param array | Traversable $barcodeConfig - * @param array | Traversable $rendererConfig - * @return mixed - */ - public static function draw( - $barcode, - $renderer, - $barcodeConfig = array(), - $rendererConfig = array() - ) { - return static::factory($barcode, $renderer, $barcodeConfig, $rendererConfig)->draw(); - } - - /** - * Set the default font for new instances of barcode - * - * @param string $font - * @return void - */ - public static function setBarcodeFont($font) - { - static::$staticFont = $font; - } - - /** - * Get current default font - * - * @return string - */ - public static function getBarcodeFont() - { - return static::$staticFont; - } -} diff --git a/library/Zend/Barcode/CONTRIBUTING.md b/library/Zend/Barcode/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Barcode/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Barcode/Exception/ExceptionInterface.php b/library/Zend/Barcode/Exception/ExceptionInterface.php deleted file mode 100755 index f421ceb94..000000000 --- a/library/Zend/Barcode/Exception/ExceptionInterface.php +++ /dev/null @@ -1,17 +0,0 @@ -getDefaultOptions(); - $this->font = Barcode\Barcode::getBarcodeFont(); - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if (is_array($options)) { - $this->setOptions($options); - } - $this->type = strtolower(substr(get_class($this), strlen($this->barcodeNamespace) + 1)); - if ($this->mandatoryChecksum) { - $this->withChecksum = true; - $this->withChecksumInText = true; - } - } - - /** - * Set default options for particular object - * @return void - */ - protected function getDefaultOptions() - { - } - - /** - * Set barcode state from options array - * @param array $options - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setOptions($options) - { - foreach ($options as $key => $value) { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Set barcode namespace for autoloading - * - * @param string $namespace - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setBarcodeNamespace($namespace) - { - $this->barcodeNamespace = $namespace; - return $this; - } - - /** - * Retrieve barcode namespace - * - * @return string - */ - public function getBarcodeNamespace() - { - return $this->barcodeNamespace; - } - - /** - * Retrieve type of barcode - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Set height of the barcode bar - * @param int $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setBarHeight($value) - { - if (intval($value) <= 0) { - throw new Exception\OutOfRangeException( - 'Bar height must be greater than 0' - ); - } - $this->barHeight = intval($value); - return $this; - } - - /** - * Get height of the barcode bar - * @return int - */ - public function getBarHeight() - { - return $this->barHeight; - } - - /** - * Set thickness of thin bar - * @param int $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setBarThinWidth($value) - { - if (intval($value) <= 0) { - throw new Exception\OutOfRangeException( - 'Bar width must be greater than 0' - ); - } - $this->barThinWidth = intval($value); - return $this; - } - - /** - * Get thickness of thin bar - * @return int - */ - public function getBarThinWidth() - { - return $this->barThinWidth; - } - - /** - * Set thickness of thick bar - * @param int $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setBarThickWidth($value) - { - if (intval($value) <= 0) { - throw new Exception\OutOfRangeException( - 'Bar width must be greater than 0' - ); - } - $this->barThickWidth = intval($value); - return $this; - } - - /** - * Get thickness of thick bar - * @return int - */ - public function getBarThickWidth() - { - return $this->barThickWidth; - } - - /** - * Set factor applying to - * thinBarWidth - thickBarWidth - barHeight - fontSize - * @param float $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setFactor($value) - { - if (floatval($value) <= 0) { - throw new Exception\OutOfRangeException( - 'Factor must be greater than 0' - ); - } - $this->factor = floatval($value); - return $this; - } - - /** - * Get factor applying to - * thinBarWidth - thickBarWidth - barHeight - fontSize - * @return int - */ - public function getFactor() - { - return $this->factor; - } - - /** - * Set color of the barcode and text - * @param string $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setForeColor($value) - { - if (preg_match('`\#[0-9A-F]{6}`', $value)) { - $this->foreColor = hexdec($value); - } elseif (is_numeric($value) && $value >= 0 && $value <= 16777125) { - $this->foreColor = intval($value); - } else { - throw new Exception\InvalidArgumentException( - 'Text color must be set as #[0-9A-F]{6}' - ); - } - return $this; - } - - /** - * Retrieve color of the barcode and text - * @return int - */ - public function getForeColor() - { - return $this->foreColor; - } - - /** - * Set the color of the background - * @param int $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setBackgroundColor($value) - { - if (preg_match('`\#[0-9A-F]{6}`', $value)) { - $this->backgroundColor = hexdec($value); - } elseif (is_numeric($value) && $value >= 0 && $value <= 16777125) { - $this->backgroundColor = intval($value); - } else { - throw new Exception\InvalidArgumentException( - 'Background color must be set as #[0-9A-F]{6}' - ); - } - return $this; - } - - /** - * Retrieve background color of the image - * @return int - */ - public function getBackgroundColor() - { - return $this->backgroundColor; - } - - /** - * Activate/deactivate drawing of the bar - * @param bool $value - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setWithBorder($value) - { - $this->withBorder = (bool) $value; - return $this; - } - - /** - * Retrieve if border are draw or not - * @return bool - */ - public function getWithBorder() - { - return $this->withBorder; - } - - /** - * Activate/deactivate drawing of the quiet zones - * @param bool $value - * @return AbstractObject - */ - public function setWithQuietZones($value) - { - $this->withQuietZones = (bool) $value; - return $this; - } - - /** - * Retrieve if quiet zones are draw or not - * @return bool - */ - public function getWithQuietZones() - { - return $this->withQuietZones; - } - - /** - * Allow fast inversion of font/bars color and background color - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setReverseColor() - { - $tmp = $this->foreColor; - $this->foreColor = $this->backgroundColor; - $this->backgroundColor = $tmp; - return $this; - } - - /** - * Set orientation of barcode and text - * @param float $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setOrientation($value) - { - $this->orientation = floatval($value) - floor(floatval($value) / 360) * 360; - return $this; - } - - /** - * Retrieve orientation of barcode and text - * @return float - */ - public function getOrientation() - { - return $this->orientation; - } - - /** - * Set text to encode - * @param string $value - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setText($value) - { - $this->text = trim($value); - return $this; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - $text = $this->text; - if ($this->withChecksum) { - $text .= $this->getChecksum($this->text); - } - return $this->addLeadingZeros($text); - } - - /** - * Automatically add leading zeros if barcode length is fixed - * @param string $text - * @param bool $withoutChecksum - * @return string - */ - protected function addLeadingZeros($text, $withoutChecksum = false) - { - if ($this->barcodeLength && $this->addLeadingZeros) { - $omitChecksum = (int) ($this->withChecksum && $withoutChecksum); - if (is_int($this->barcodeLength)) { - $length = $this->barcodeLength - $omitChecksum; - if (strlen($text) < $length) { - $text = str_repeat('0', $length - strlen($text)) . $text; - } - } else { - if ($this->barcodeLength == 'even') { - $text = ((strlen($text) - $omitChecksum) % 2 ? '0' . $text : $text); - } - } - } - return $text; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getRawText() - { - return $this->text; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - if ($this->withChecksumInText) { - return $this->getText(); - } - - return $this->addLeadingZeros($this->text, true); - } - - /** - * Activate/deactivate drawing of text to encode - * @param bool $value - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setDrawText($value) - { - $this->drawText = (bool) $value; - return $this; - } - - /** - * Retrieve if drawing of text to encode is enabled - * @return bool - */ - public function getDrawText() - { - return $this->drawText; - } - - /** - * Activate/deactivate the adjustment of the position - * of the characters to the position of the bars - * @param bool $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setStretchText($value) - { - $this->stretchText = (bool) $value; - return $this; - } - - /** - * Retrieve if the adjustment of the position of the characters - * to the position of the bars is enabled - * @return bool - */ - public function getStretchText() - { - return $this->stretchText; - } - - /** - * Activate/deactivate the automatic generation - * of the checksum character - * added to the barcode text - * @param bool $value - * @return \Zend\Barcode\Object\ObjectInterface - */ - public function setWithChecksum($value) - { - if (!$this->mandatoryChecksum) { - $this->withChecksum = (bool) $value; - } - return $this; - } - - /** - * Retrieve if the checksum character is automatically - * added to the barcode text - * @return bool - */ - public function getWithChecksum() - { - return $this->withChecksum; - } - - /** - * Activate/deactivate the automatic generation - * of the checksum character - * added to the barcode text - * @param bool $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setWithChecksumInText($value) - { - if (!$this->mandatoryChecksum) { - $this->withChecksumInText = (bool) $value; - } - return $this; - } - - /** - * Retrieve if the checksum character is automatically - * added to the barcode text - * @return bool - */ - public function getWithChecksumInText() - { - return $this->withChecksumInText; - } - - /** - * Set the font: - * - if integer between 1 and 5, use gd built-in fonts - * - if string, $value is assumed to be the path to a TTF font - * @param int|string $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setFont($value) - { - if (is_int($value) && $value >= 1 && $value <= 5) { - if (!extension_loaded('gd')) { - throw new Exception\ExtensionNotLoadedException( - 'GD extension is required to use numeric font' - ); - } - - // Case of numeric font with GD - $this->font = $value; - - // In this case font size is given by: - $this->fontSize = imagefontheight($value); - } elseif (is_string($value)) { - $this->font = $value; - } else { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid font "%s" provided to setFont()', - $value - )); - } - return $this; - } - - /** - * Retrieve the font - * @return int|string - */ - public function getFont() - { - return $this->font; - } - - /** - * Set the size of the font in case of TTF - * @param float $value - * @return \Zend\Barcode\Object\ObjectInterface - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - public function setFontSize($value) - { - if (is_numeric($this->font)) { - // Case of numeric font with GD - return $this; - } - - if (!is_numeric($value)) { - throw new Exception\InvalidArgumentException( - 'Font size must be a numeric value' - ); - } - - $this->fontSize = $value; - return $this; - } - - /** - * Retrieve the size of the font in case of TTF - * @return float - */ - public function getFontSize() - { - return $this->fontSize; - } - - /** - * Quiet zone before first bar - * and after the last bar - * @return int - */ - public function getQuietZone() - { - if ($this->withQuietZones || $this->mandatoryQuietZones) { - return 10 * $this->barThinWidth * $this->factor; - } - - return 0; - } - - /** - * Add an instruction in the array of instructions - * @param array $instruction - */ - protected function addInstruction(array $instruction) - { - $this->instructions[] = $instruction; - } - - /** - * Retrieve the set of drawing instructions - * @return array - */ - public function getInstructions() - { - return $this->instructions; - } - - /** - * Add a polygon drawing instruction in the set of instructions - * @param array $points - * @param int $color - * @param bool $filled - */ - protected function addPolygon(array $points, $color = null, $filled = true) - { - if ($color === null) { - $color = $this->foreColor; - } - $this->addInstruction(array( - 'type' => 'polygon', - 'points' => $points, - 'color' => $color, - 'filled' => $filled, - )); - } - - /** - * Add a text drawing instruction in the set of instructions - * @param string $text - * @param float $size - * @param int[] $position - * @param string $font - * @param int $color - * @param string $alignment - * @param float $orientation - */ - protected function addText( - $text, - $size, - $position, - $font, - $color, - $alignment = 'center', - $orientation = 0 - ) { - if ($color === null) { - $color = $this->foreColor; - } - $this->addInstruction(array( - 'type' => 'text', - 'text' => $text, - 'size' => $size, - 'position' => $position, - 'font' => $font, - 'color' => $color, - 'alignment' => $alignment, - 'orientation' => $orientation, - )); - } - - /** - * Checking of parameters after all settings - * @return bool - */ - public function checkParams() - { - $this->checkText(); - $this->checkFontAndOrientation(); - $this->checkSpecificParams(); - return true; - } - - /** - * Check if a text is really provided to barcode - * @param string|null $value - * @return void - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - protected function checkText($value = null) - { - if ($value === null) { - $value = $this->text; - } - if (!strlen($value)) { - throw new Exception\RuntimeException( - 'A text must be provide to Barcode before drawing' - ); - } - $this->validateText($value); - } - - /** - * Check the ratio between the thick and the thin bar - * @param int $min - * @param int $max - * @return void - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - protected function checkRatio($min = 2, $max = 3) - { - $ratio = $this->barThickWidth / $this->barThinWidth; - if (!($ratio >= $min && $ratio <= $max)) { - throw new Exception\OutOfRangeException(sprintf( - 'Ratio thick/thin bar must be between %0.1f and %0.1f (actual %0.3f)', - $min, - $max, - $ratio - )); - } - } - - /** - * Drawing with an angle is just allow TTF font - * @return void - * @throws \Zend\Barcode\Object\Exception\ExceptionInterface - */ - protected function checkFontAndOrientation() - { - if (is_numeric($this->font) && $this->orientation != 0) { - throw new Exception\RuntimeException( - 'Only drawing with TTF font allow orientation of the barcode.' - ); - } - } - - /** - * Width of the result image - * (before any rotation) - * @return int - */ - protected function calculateWidth() - { - return (int) $this->withBorder - + $this->calculateBarcodeWidth() - + (int) $this->withBorder; - } - - /** - * Calculate the width of the barcode - * @return int - */ - abstract protected function calculateBarcodeWidth(); - - /** - * Height of the result object - * @return int - */ - protected function calculateHeight() - { - return (int) $this->withBorder * 2 - + $this->calculateBarcodeHeight() - + (int) $this->withBorder * 2; - } - - /** - * Height of the barcode - * @return int - */ - protected function calculateBarcodeHeight() - { - $textHeight = 0; - $extraHeight = 0; - if ($this->drawText) { - $textHeight += $this->fontSize; - $extraHeight = 2; - } - return ($this->barHeight + $textHeight) * $this->factor + $extraHeight; - } - - /** - * Get height of the result object - * @param bool $recalculate - * @return int - */ - public function getHeight($recalculate = false) - { - if ($this->height === null || $recalculate) { - $this->height = - abs($this->calculateHeight() * cos($this->orientation / 180 * pi())) - + abs($this->calculateWidth() * sin($this->orientation / 180 * pi())); - } - return $this->height; - } - - /** - * Get width of the result object - * @param bool $recalculate - * @return int - */ - public function getWidth($recalculate = false) - { - if ($this->width === null || $recalculate) { - $this->width = - abs($this->calculateWidth() * cos($this->orientation / 180 * pi())) - + abs($this->calculateHeight() * sin($this->orientation / 180 * pi())); - } - return $this->width; - } - - /** - * Calculate the offset from the left of the object - * if an orientation is activated - * @param bool $recalculate - * @return float - */ - public function getOffsetLeft($recalculate = false) - { - if ($this->offsetLeft === null || $recalculate) { - $this->offsetLeft = - min( - array( - 0 * cos($this->orientation / 180 * pi()) - 0 * sin($this->orientation / 180 * pi()), - 0 * cos($this->orientation / 180 * pi()) - $this->calculateBarcodeHeight() * sin($this->orientation / 180 * pi()), - $this->calculateBarcodeWidth() * cos($this->orientation / 180 * pi()) - $this->calculateBarcodeHeight() * sin($this->orientation / 180 * pi()), - $this->calculateBarcodeWidth() * cos($this->orientation / 180 * pi()) - 0 * sin($this->orientation / 180 * pi()), - ) - ); - } - return $this->offsetLeft; - } - - /** - * Calculate the offset from the top of the object - * if an orientation is activated - * @param bool $recalculate - * @return float - */ - public function getOffsetTop($recalculate = false) - { - if ($this->offsetTop === null || $recalculate) { - $this->offsetTop = - min( - array( - 0 * cos($this->orientation / 180 * pi()) + 0 * sin($this->orientation / 180 * pi()), - $this->calculateBarcodeHeight() * cos($this->orientation / 180 * pi()) + 0 * sin($this->orientation / 180 * pi()), - $this->calculateBarcodeHeight() * cos($this->orientation / 180 * pi()) + $this->calculateBarcodeWidth() * sin($this->orientation / 180 * pi()), - 0 * cos($this->orientation / 180 * pi()) + $this->calculateBarcodeWidth() * sin($this->orientation / 180 * pi()), - ) - ); - } - return $this->offsetTop; - } - - /** - * Apply rotation on a point in X/Y dimensions - * @param float $x1 x-position before rotation - * @param float $y1 y-position before rotation - * @return int[] Array of two elements corresponding to the new XY point - */ - protected function rotate($x1, $y1) - { - $x2 = $x1 * cos($this->orientation / 180 * pi()) - - $y1 * sin($this->orientation / 180 * pi()) - + $this->getOffsetLeft(); - $y2 = $y1 * cos($this->orientation / 180 * pi()) - + $x1 * sin($this->orientation / 180 * pi()) - + $this->getOffsetTop(); - return array(intval($x2), intval($y2)); - } - - /** - * Complete drawing of the barcode - * @return array Table of instructions - */ - public function draw() - { - $this->checkParams(); - $this->drawBarcode(); - $this->drawBorder(); - $this->drawText(); - return $this->getInstructions(); - } - - /** - * Draw the barcode - * @return void - */ - protected function drawBarcode() - { - $barcodeTable = $this->prepareBarcode(); - - $this->preDrawBarcode(); - - $xpos = (int) $this->withBorder; - $ypos = (int) $this->withBorder; - - $point1 = $this->rotate(0, 0); - $point2 = $this->rotate(0, $this->calculateHeight() - 1); - $point3 = $this->rotate( - $this->calculateWidth() - 1, - $this->calculateHeight() - 1 - ); - $point4 = $this->rotate($this->calculateWidth() - 1, 0); - - $this->addPolygon(array( - $point1, - $point2, - $point3, - $point4 - ), $this->backgroundColor); - - $xpos += $this->getQuietZone(); - $barLength = $this->barHeight * $this->factor; - - foreach ($barcodeTable as $bar) { - $width = $bar[1] * $this->factor; - if ($bar[0]) { - $point1 = $this->rotate($xpos, $ypos + $bar[2] * $barLength); - $point2 = $this->rotate($xpos, $ypos + $bar[3] * $barLength); - $point3 = $this->rotate( - $xpos + $width - 1, - $ypos + $bar[3] * $barLength - ); - $point4 = $this->rotate( - $xpos + $width - 1, - $ypos + $bar[2] * $barLength - ); - $this->addPolygon(array( - $point1, - $point2, - $point3, - $point4, - )); - } - $xpos += $width; - } - - $this->postDrawBarcode(); - } - - /** - * Partial function to draw border - * @return void - */ - protected function drawBorder() - { - if ($this->withBorder) { - $point1 = $this->rotate(0, 0); - $point2 = $this->rotate($this->calculateWidth() - 1, 0); - $point3 = $this->rotate( - $this->calculateWidth() - 1, - $this->calculateHeight() - 1 - ); - $point4 = $this->rotate(0, $this->calculateHeight() - 1); - $this->addPolygon(array( - $point1, - $point2, - $point3, - $point4, - $point1, - ), $this->foreColor, false); - } - } - - /** - * Partial function to draw text - * @return void - */ - protected function drawText() - { - if ($this->drawText) { - $text = $this->getTextToDisplay(); - if ($this->stretchText) { - $textLength = strlen($text); - $space = ($this->calculateWidth() - 2 * $this->getQuietZone()) / $textLength; - for ($i = 0; $i < $textLength; $i ++) { - $leftPosition = $this->getQuietZone() + $space * ($i + 0.5); - $this->addText( - $text{$i}, - $this->fontSize * $this->factor, - $this->rotate( - $leftPosition, - (int) $this->withBorder * 2 + $this->factor * ($this->barHeight + $this->fontSize) + 1 - ), - $this->font, - $this->foreColor, - 'center', - - $this->orientation - ); - } - } else { - $this->addText( - $text, - $this->fontSize * $this->factor, - $this->rotate( - $this->calculateWidth() / 2, - (int) $this->withBorder * 2 + $this->factor * ($this->barHeight + $this->fontSize) + 1 - ), - $this->font, - $this->foreColor, - 'center', - - $this->orientation - ); - } - } - } - - /** - * Check for invalid characters - * @param string $value Text to be checked - * @return void - */ - public function validateText($value) - { - $this->validateSpecificText($value); - } - - /** - * Standard validation for most of barcode objects - * @param string $value - * @param array $options - */ - protected function validateSpecificText($value, $options = array()) - { - $validatorName = (isset($options['validator'])) ? $options['validator'] : $this->getType(); - - $validator = new BarcodeValidator(array( - 'adapter' => $validatorName, - 'usechecksum' => false, - )); - - $checksumCharacter = ''; - $withChecksum = false; - if ($this->mandatoryChecksum) { - $checksumCharacter = $this->substituteChecksumCharacter; - $withChecksum = true; - } - - $value = $this->addLeadingZeros($value, $withChecksum) . $checksumCharacter; - - if (!$validator->isValid($value)) { - $message = implode("\n", $validator->getMessages()); - throw new Exception\BarcodeValidationException($message); - } - } - - /** - * Each child must prepare the barcode and return - * a table like array( - * 0 => array( - * 0 => int (visible(black) or not(white)) - * 1 => int (width of the bar) - * 2 => float (0->1 position from the top of the beginning of the bar in %) - * 3 => float (0->1 position from the top of the end of the bar in %) - * ), - * 1 => ... - * ) - * - * @return array - */ - abstract protected function prepareBarcode(); - - /** - * Checking of parameters after all settings - * - * @return void - */ - abstract protected function checkSpecificParams(); - - /** - * Allow each child to draw something else - * - * @return void - */ - protected function preDrawBarcode() - { - } - - /** - * Allow each child to draw something else - * (ex: bearer bars in interleaved 2 of 5 code) - * - * @return void - */ - protected function postDrawBarcode() - { - } -} diff --git a/library/Zend/Barcode/Object/Codabar.php b/library/Zend/Barcode/Object/Codabar.php deleted file mode 100755 index 71120c601..000000000 --- a/library/Zend/Barcode/Object/Codabar.php +++ /dev/null @@ -1,77 +0,0 @@ - "101010011", '1' => "101011001", '2' => "101001011", - '3' => "110010101", '4' => "101101001", '5' => "110101001", - '6' => "100101011", '7' => "100101101", '8' => "100110101", - '9' => "110100101", '-' => "101001101", '$' => "101100101", - ':' => "1101011011", '/' => "1101101011", '.' => "1101101101", - '+' => "1011011011", 'A' => "1011001001", 'B' => "1010010011", - 'C' => "1001001011", 'D' => "1010011001" - ); - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $encodedData = 0; - $barcodeChar = str_split($this->getText()); - if (count($barcodeChar) > 1) { - foreach ($barcodeChar as $c) { - $encodedData += ((strlen($this->codingMap[$c]) + 1) * $this->barThinWidth) * $this->factor; - } - } - $encodedData -= (1 * $this->barThinWidth * $this->factor); - return $quietZone + $encodedData + $quietZone; - } - - /** - * Partial check of Codabar barcode - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $text = str_split($this->getText()); - $barcodeTable = array(); - foreach ($text as $char) { - $barcodeChar = str_split($this->codingMap[$char]); - foreach ($barcodeChar as $c) { - // visible, width, top, length - $barcodeTable[] = array($c, $this->barThinWidth, 0, 1); - } - $barcodeTable[] = array(0, $this->barThinWidth); - } - return $barcodeTable; - } -} diff --git a/library/Zend/Barcode/Object/Code128.php b/library/Zend/Barcode/Object/Code128.php deleted file mode 100755 index 3bb0cc0c7..000000000 --- a/library/Zend/Barcode/Object/Code128.php +++ /dev/null @@ -1,311 +0,0 @@ - "11011001100", 1 => "11001101100", 2 => "11001100110", - 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", - 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", - 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", - 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", - 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", - 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", - 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", - 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", - 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", - 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", - 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", - 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", - 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", - 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", - 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", - 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", - 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", - 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", - 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", - 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", - 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", - 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", - 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", - 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", - 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", - 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", - 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", - 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", - 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", - 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", - 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", - 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", - 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", - 102 => "11110101110", - 103 => "11010000100", 104 => "11010010000", 105 => "11010011100", - 106 => "1100011101011"); - - /** - * Character sets ABC - * @var array - */ - protected $charSets = array( - 'A' => array( - ' ', '!', '"', '#', '$', '%', '&', "'", - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, - 'FNC3', 'FNC2', 'SHIFT', 'Code C', 'Code B', 'FNC4', 'FNC1', - 'START A', 'START B', 'START C', 'STOP'), - 'B' => array( - ' ', '!', '"', '#', '$', '%', '&', "'", - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', - 'x', 'y', 'z', '{', '|', '}', '~', 0x7F, - 'FNC3', 'FNC2', 'SHIFT', 'Code C', 'FNC4', 'Code A', 'FNC1', - 'START A', 'START B', 'START C', 'STOP',), - 'C' => array( - '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', - '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', - '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', - '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', - '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', - '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', - '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', - '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', - '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', - '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', - 'Code B', 'Code A', 'FNC1', 'START A', 'START B', 'START C', 'STOP')); - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - // Each characters contain 11 bars... - $characterLength = 11 * $this->barThinWidth * $this->factor; - $convertedChars = count($this->convertToBarcodeChars($this->getText())); - if ($this->withChecksum) { - $convertedChars++; - } - $encodedData = $convertedChars * $characterLength; - // ...except the STOP character (13) - $encodedData += $characterLength + 2 * $this->barThinWidth * $this->factor; - $width = $quietZone + $encodedData + $quietZone; - return $width; - } - - /** - * Partial check of code128 barcode - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - - $convertedChars = $this->convertToBarcodeChars($this->getText()); - - if ($this->withChecksum) { - $convertedChars[] = $this->getChecksum($this->getText()); - } - - // STOP CHARACTER - $convertedChars[] = 106; - - foreach ($convertedChars as $barcodeChar) { - $barcodePattern = $this->codingMap[$barcodeChar]; - foreach (str_split($barcodePattern) as $c) { - $barcodeTable[] = array($c, $this->barThinWidth, 0, 1); - } - } - return $barcodeTable; - } - - /** - * Checks if the next $length chars of $string starting at $pos are numeric. - * Returns false if the end of the string is reached. - * @param string $string String to search - * @param int $pos Starting position - * @param int $length Length to search - * @return bool - */ - protected static function _isDigit($string, $pos, $length = 2) - { - if ($pos + $length > strlen($string)) { - return false; - } - - for ($i = $pos; $i < $pos + $length; $i++) { - if (!is_numeric($string[$i])) { - return false; - } - } - return true; - } - - /** - * Convert string to barcode string - * @param string $string - * @return array - */ - protected function convertToBarcodeChars($string) - { - $string = (string) $string; - if (!strlen($string)) { - return array(); - } - - if (isset($this->convertedText[md5($string)])) { - return $this->convertedText[md5($string)]; - } - - $currentCharset = null; - $result = array(); - - $strlen = strlen($string); - for ($pos = 0; $pos < $strlen; $pos++) { - $char = $string[$pos]; - - if (static::_isDigit($string, $pos, 4) && $currentCharset != 'C' - || static::_isDigit($string, $pos, 2) && $currentCharset == 'C') { - /** - * Switch to C if the next 4 chars are numeric or stay C if the next 2 - * chars are numeric - */ - if ($currentCharset != 'C') { - if ($pos == 0) { - $code = array_search("START C", $this->charSets['C']); - } else { - $code = array_search("Code C", $this->charSets[$currentCharset]); - } - $result[] = $code; - $currentCharset = 'C'; - } - } elseif (in_array($char, $this->charSets['B']) && $currentCharset != 'B' - && !(in_array($char, $this->charSets['A']) && $currentCharset == 'A')) { - /** - * Switch to B as B contains the char and B is not the current charset. - */ - if ($pos == 0) { - $code = array_search("START B", $this->charSets['B']); - } else { - $code = array_search("Code B", $this->charSets[$currentCharset]); - } - $result[] = $code; - $currentCharset = 'B'; - } elseif (array_key_exists($char, $this->charSets['A']) && $currentCharset != 'A' - && !(array_key_exists($char, $this->charSets['B']) && $currentCharset == 'B')) { - /** - * Switch to C as C contains the char and C is not the current charset. - */ - if ($pos == 0) { - $code = array_search("START A", $this->charSets['A']); - } else { - $code = array_search("Code A", $this->charSets[$currentCharset]); - } - $result[] = $code; - $currentCharset = 'A'; - } - - if ($currentCharset == 'C') { - $code = array_search(substr($string, $pos, 2), $this->charSets['C']); - $pos++; //Two chars from input - } else { - $code = array_search($string[$pos], $this->charSets[$currentCharset]); - } - $result[] = $code; - } - - $this->convertedText[md5($string)] = $result; - return $result; - } - - /** - * Set text to encode - * @param string $value - * @return Code128 - */ - public function setText($value) - { - $this->text = $value; - return $this; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - return $this->text; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $tableOfChars = $this->convertToBarcodeChars($text); - - $sum = $tableOfChars[0]; - unset($tableOfChars[0]); - - $k = 1; - foreach ($tableOfChars as $char) { - $sum += ($k++) * $char; - } - - $checksum = $sum % 103; - - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Code25.php b/library/Zend/Barcode/Object/Code25.php deleted file mode 100755 index 2f32ca7af..000000000 --- a/library/Zend/Barcode/Object/Code25.php +++ /dev/null @@ -1,117 +0,0 @@ - '00110', - '1' => '10001', - '2' => '01001', - '3' => '11000', - '4' => '00101', - '5' => '10100', - '6' => '01100', - '7' => '00011', - '8' => '10010', - '9' => '01010', - ); - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (2 * $this->barThickWidth + 4 * $this->barThinWidth) * $this->factor; - $characterLength = (3 * $this->barThinWidth + 2 * $this->barThickWidth + 5 * $this->barThinWidth) - * $this->factor; - $encodedData = strlen($this->getText()) * $characterLength; - $stopCharacter = (2 * $this->barThickWidth + 4 * $this->barThinWidth) * $this->factor; - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved 2 of 5 barcode - * @return void - */ - protected function checkSpecificParams() - { - $this->checkRatio(); - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - - // Start character (30301) - $barcodeTable[] = array(1, $this->barThickWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThickWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth); - - $text = str_split($this->getText()); - foreach ($text as $char) { - $barcodeChar = str_split($this->codingMap[$char]); - foreach ($barcodeChar as $c) { - /* visible, width, top, length */ - $width = $c ? $this->barThickWidth : $this->barThinWidth; - $barcodeTable[] = array(1, $width, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth); - } - } - - // Stop character (30103) - $barcodeTable[] = array(1, $this->barThickWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThickWidth, 0, 1); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $factor = 3; - $checksum = 0; - - for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text{$i - 1}) * $factor; - $factor = 4 - $factor; - } - - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Code25interleaved.php b/library/Zend/Barcode/Object/Code25interleaved.php deleted file mode 100755 index 0fb3ec33a..000000000 --- a/library/Zend/Barcode/Object/Code25interleaved.php +++ /dev/null @@ -1,159 +0,0 @@ -barcodeLength = 'even'; - } - - /** - * Activate/deactivate drawing of bearer bars - * @param bool $value - * @return Code25 - */ - public function setWithBearerBars($value) - { - $this->withBearerBars = (bool) $value; - return $this; - } - - /** - * Retrieve if bearer bars are enabled - * @return bool - */ - public function getWithBearerBars() - { - return $this->withBearerBars; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (4 * $this->barThinWidth) * $this->factor; - $characterLength = (3 * $this->barThinWidth + 2 * $this->barThickWidth) * $this->factor; - $encodedData = strlen($this->getText()) * $characterLength; - $stopCharacter = ($this->barThickWidth + 2 * $this->barThinWidth) * $this->factor; - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - if ($this->withBearerBars) { - $this->withBorder = false; - } - - $barcodeTable = array(); - - // Start character (0000) - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - - // Encoded $text - $text = $this->getText(); - for ($i = 0, $len = strlen($text); $i < $len; $i += 2) { // Draw 2 chars at a time - $char1 = substr($text, $i, 1); - $char2 = substr($text, $i + 1, 1); - - // Interleave - for ($ibar = 0; $ibar < 5; $ibar ++) { - // Draws char1 bar (fore color) - $barWidth = (substr($this->codingMap[$char1], $ibar, 1)) - ? $this->barThickWidth - : $this->barThinWidth; - - $barcodeTable[] = array(1, $barWidth, 0, 1); - - // Left space corresponding to char2 (background color) - $barWidth = (substr($this->codingMap[$char2], $ibar, 1)) - ? $this->barThickWidth - : $this->barThinWidth; - $barcodeTable[] = array(0, $barWidth, 0, 1); - } - } - - // Stop character (100) - $barcodeTable[] = array(1, $this->barThickWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - return $barcodeTable; - } - - /** - * Drawing of bearer bars (if enabled) - * - * @return void - */ - protected function postDrawBarcode() - { - if (!$this->withBearerBars) { - return; - } - - $width = $this->barThickWidth * $this->factor; - $point1 = $this->rotate(-1, -1); - $point2 = $this->rotate($this->calculateWidth() - 1, -1); - $point3 = $this->rotate($this->calculateWidth() - 1, $width - 1); - $point4 = $this->rotate(-1, $width - 1); - $this->addPolygon(array( - $point1, - $point2, - $point3, - $point4, - )); - $point1 = $this->rotate( - 0, - 0 + $this->barHeight * $this->factor - 1 - ); - $point2 = $this->rotate( - $this->calculateWidth() - 1, - 0 + $this->barHeight * $this->factor - 1 - ); - $point3 = $this->rotate( - $this->calculateWidth() - 1, - 0 + $this->barHeight * $this->factor - $width - ); - $point4 = $this->rotate( - 0, - 0 + $this->barHeight * $this->factor - $width - ); - $this->addPolygon(array( - $point1, - $point2, - $point3, - $point4, - )); - } -} diff --git a/library/Zend/Barcode/Object/Code39.php b/library/Zend/Barcode/Object/Code39.php deleted file mode 100755 index c70e289eb..000000000 --- a/library/Zend/Barcode/Object/Code39.php +++ /dev/null @@ -1,162 +0,0 @@ - '000110100', - '1' => '100100001', - '2' => '001100001', - '3' => '101100000', - '4' => '000110001', - '5' => '100110000', - '6' => '001110000', - '7' => '000100101', - '8' => '100100100', - '9' => '001100100', - 'A' => '100001001', - 'B' => '001001001', - 'C' => '101001000', - 'D' => '000011001', - 'E' => '100011000', - 'F' => '001011000', - 'G' => '000001101', - 'H' => '100001100', - 'I' => '001001100', - 'J' => '000011100', - 'K' => '100000011', - 'L' => '001000011', - 'M' => '101000010', - 'N' => '000010011', - 'O' => '100010010', - 'P' => '001010010', - 'Q' => '000000111', - 'R' => '100000110', - 'S' => '001000110', - 'T' => '000010110', - 'U' => '110000001', - 'V' => '011000001', - 'W' => '111000000', - 'X' => '010010001', - 'Y' => '110010000', - 'Z' => '011010000', - '-' => '010000101', - '.' => '110000100', - ' ' => '011000100', - '$' => '010101000', - '/' => '010100010', - '+' => '010001010', - '%' => '000101010', - '*' => '010010100', - ); - - /** - * Partial check of Code39 barcode - * @return void - */ - protected function checkSpecificParams() - { - $this->checkRatio(); - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $characterLength = (6 * $this->barThinWidth + 3 * $this->barThickWidth + 1) * $this->factor; - $encodedData = strlen($this->getText()) * $characterLength - $this->factor; - return $quietZone + $encodedData + $quietZone; - } - - /** - * Set text to encode - * @param string $value - * @return Code39 - */ - public function setText($value) - { - $this->text = $value; - return $this; - } - - /** - * Retrieve text to display - * @return string - */ - public function getText() - { - return '*' . parent::getText() . '*'; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - $text = parent::getTextToDisplay(); - if (substr($text, 0, 1) != '*' && substr($text, -1) != '*') { - return '*' . $text . '*'; - } - - return $text; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $text = str_split($this->getText()); - $barcodeTable = array(); - foreach ($text as $char) { - $barcodeChar = str_split($this->codingMap[$char]); - $visible = true; - foreach ($barcodeChar as $c) { - /* visible, width, top, length */ - $width = $c ? $this->barThickWidth : $this->barThinWidth; - $barcodeTable[] = array((int) $visible, $width, 0, 1); - $visible = ! $visible; - } - $barcodeTable[] = array(0, $this->barThinWidth); - } - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $text = str_split($text); - $charset = array_flip(array_keys($this->codingMap)); - $checksum = 0; - foreach ($text as $character) { - $checksum += $charset[$character]; - } - return array_search(($checksum % 43), $charset); - } -} diff --git a/library/Zend/Barcode/Object/Ean13.php b/library/Zend/Barcode/Object/Ean13.php deleted file mode 100755 index 602668d97..000000000 --- a/library/Zend/Barcode/Object/Ean13.php +++ /dev/null @@ -1,198 +0,0 @@ - array( - 0 => "0001101", 1 => "0011001", 2 => "0010011", 3 => "0111101", 4 => "0100011", - 5 => "0110001", 6 => "0101111", 7 => "0111011", 8 => "0110111", 9 => "0001011" - ), - 'B' => array( - 0 => "0100111", 1 => "0110011", 2 => "0011011", 3 => "0100001", 4 => "0011101", - 5 => "0111001", 6 => "0000101", 7 => "0010001", 8 => "0001001", 9 => "0010111" - ), - 'C' => array( - 0 => "1110010", 1 => "1100110", 2 => "1101100", 3 => "1000010", 4 => "1011100", - 5 => "1001110", 6 => "1010000", 7 => "1000100", 8 => "1001000", 9 => "1110100" - )); - - protected $parities = array( - 0 => array('A','A','A','A','A','A'), - 1 => array('A','A','B','A','B','B'), - 2 => array('A','A','B','B','A','B'), - 3 => array('A','A','B','B','B','A'), - 4 => array('A','B','A','A','B','B'), - 5 => array('A','B','B','A','A','B'), - 6 => array('A','B','B','B','A','A'), - 7 => array('A','B','A','B','A','B'), - 8 => array('A','B','A','B','B','A'), - 9 => array('A','B','B','A','B','A') - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function getDefaultOptions() - { - $this->barcodeLength = 13; - $this->mandatoryChecksum = true; - $this->mandatoryQuietZones = true; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->barThinWidth) * $this->factor; - $middleCharacter = (5 * $this->barThinWidth) * $this->factor; - $stopCharacter = (3 * $this->barThinWidth) * $this->factor; - $encodedData = (7 * $this->barThinWidth) * $this->factor * 12; - return $quietZone + $startCharacter + $middleCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved EAN/UPC barcode - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - - $textTable = str_split($this->getText()); - $parity = $this->parities[$textTable[0]]; - - // First part - for ($i = 1; $i < 7; $i++) { - $bars = str_split($this->codingMap[$parity[$i - 1]][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Middle character (01010) - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - - // Second part - for ($i = 7; $i < 13; $i++) { - $bars = str_split($this->codingMap['C'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Stop character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $factor = 3; - $checksum = 0; - - for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text{$i - 1}) * $factor; - $factor = 4 - $factor; - } - - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; - } - - /** - * Partial function to draw text - * @return void - */ - protected function drawText() - { - if (get_class($this) == 'Zend\Barcode\Object\Ean13') { - $this->drawEan13Text(); - } else { - parent::drawText(); - } - } - - protected function drawEan13Text() - { - if ($this->drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->barThinWidth) * $this->factor; - $leftPosition = $this->getQuietZone() - $characterWidth; - for ($i = 0; $i < $this->barcodeLength; $i ++) { - $this->addText( - $text{$i}, - $this->fontSize * $this->factor, - $this->rotate( - $leftPosition, - (int) $this->withBorder * 2 + $this->factor * ($this->barHeight + $this->fontSize) + 1 - ), - $this->font, - $this->foreColor, - 'left', - - $this->orientation - ); - switch ($i) { - case 0: - $factor = 3; - break; - case 6: - $factor = 4; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->barThinWidth * $this->factor); - } - } - } -} diff --git a/library/Zend/Barcode/Object/Ean2.php b/library/Zend/Barcode/Object/Ean2.php deleted file mode 100755 index b260a62d6..000000000 --- a/library/Zend/Barcode/Object/Ean2.php +++ /dev/null @@ -1,38 +0,0 @@ - array('A','A'), - 1 => array('A','B'), - 2 => array('B','A'), - 3 => array('B','B') - ); - - /** - * Default options for Ean2 barcode - * @return void - */ - protected function getDefaultOptions() - { - $this->barcodeLength = 2; - } - - protected function getParity($i) - { - $modulo = $this->getText() % 4; - return $this->parities[$modulo][$i]; - } -} diff --git a/library/Zend/Barcode/Object/Ean5.php b/library/Zend/Barcode/Object/Ean5.php deleted file mode 100755 index c04708bdc..000000000 --- a/library/Zend/Barcode/Object/Ean5.php +++ /dev/null @@ -1,124 +0,0 @@ - array('B','B','A','A','A'), - 1 => array('B','A','B','A','A'), - 2 => array('B','A','A','B','A'), - 3 => array('B','A','A','A','B'), - 4 => array('A','B','B','A','A'), - 5 => array('A','A','B','B','A'), - 6 => array('A','A','A','B','B'), - 7 => array('A','B','A','B','A'), - 8 => array('A','B','A','A','B'), - 9 => array('A','A','B','A','B') - ); - - /** - * Default options for Ean5 barcode - * @return void - */ - protected function getDefaultOptions() - { - $this->barcodeLength = 5; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (5 * $this->barThinWidth) * $this->factor; - $middleCharacter = (2 * $this->barThinWidth) * $this->factor; - $encodedData = (7 * $this->barThinWidth) * $this->factor; - return $quietZone + $startCharacter + ($this->barcodeLength - 1) * $middleCharacter + $this->barcodeLength * $encodedData + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - - // Start character (01011) - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - - $firstCharacter = true; - $textTable = str_split($this->getText()); - - // Characters - for ($i = 0; $i < $this->barcodeLength; $i++) { - if ($firstCharacter) { - $firstCharacter = false; - } else { - // Intermediate character (01) - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - } - $bars = str_split($this->codingMap[$this->getParity($i)][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $checksum = 0; - - for ($i = 0; $i < $this->barcodeLength; $i ++) { - $checksum += intval($text{$i}) * ($i % 2 ? 9 : 3); - } - - return ($checksum % 10); - } - - /** - * @param int $i - * @return string - */ - protected function getParity($i) - { - $checksum = $this->getChecksum($this->getText()); - return $this->parities[$checksum][$i]; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - return $this->addLeadingZeros($this->text); - } -} diff --git a/library/Zend/Barcode/Object/Ean8.php b/library/Zend/Barcode/Object/Ean8.php deleted file mode 100755 index b36ec3e4c..000000000 --- a/library/Zend/Barcode/Object/Ean8.php +++ /dev/null @@ -1,146 +0,0 @@ -barcodeLength = 8; - $this->mandatoryChecksum = true; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->barThinWidth) * $this->factor; - $middleCharacter = (5 * $this->barThinWidth) * $this->factor; - $stopCharacter = (3 * $this->barThinWidth) * $this->factor; - $encodedData = (7 * $this->barThinWidth) * $this->factor * 8; - return $quietZone + $startCharacter + $middleCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - - $textTable = str_split($this->getText()); - - // First part - for ($i = 0; $i < 4; $i++) { - $bars = str_split($this->codingMap['A'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Middle character (01010) - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - - // Second part - for ($i = 4; $i < 8; $i++) { - $bars = str_split($this->codingMap['C'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Stop character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - return $barcodeTable; - } - - /** - * Partial function to draw text - * @return void - */ - protected function drawText() - { - if ($this->drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->barThinWidth) * $this->factor; - $leftPosition = $this->getQuietZone() + (3 * $this->barThinWidth) * $this->factor; - for ($i = 0; $i < $this->barcodeLength; $i ++) { - $this->addText( - $text{$i}, - $this->fontSize * $this->factor, - $this->rotate( - $leftPosition, - (int) $this->withBorder * 2 + $this->factor * ($this->barHeight + $this->fontSize) + 1 - ), - $this->font, - $this->foreColor, - 'left', - - $this->orientation - ); - switch ($i) { - case 3: - $factor = 4; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->barThinWidth * $this->factor); - } - } - } - - /** - * Particular validation for Ean8 barcode objects - * (to suppress checksum character substitution) - * - * @param string $value - * @param array $options - * @throws Exception\BarcodeValidationException - */ - protected function validateSpecificText($value, $options = array()) - { - $validator = new BarcodeValidator(array( - 'adapter' => 'ean8', - 'checksum' => false, - )); - - $value = $this->addLeadingZeros($value, true); - - if (!$validator->isValid($value)) { - $message = implode("\n", $validator->getMessages()); - throw new Exception\BarcodeValidationException($message); - } - } -} diff --git a/library/Zend/Barcode/Object/Error.php b/library/Zend/Barcode/Object/Error.php deleted file mode 100755 index 15c36bcab..000000000 --- a/library/Zend/Barcode/Object/Error.php +++ /dev/null @@ -1,83 +0,0 @@ -instructions = array(); - $this->addText('ERROR:', 10, array(5, 18), $this->font, 0, 'left'); - $this->addText($this->text, 10, array(5, 32), $this->font, 0, 'left'); - return $this->instructions; - } - - /** - * For compatibility reason - * @return void - */ - protected function prepareBarcode() - { - } - - /** - * For compatibility reason - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * For compatibility reason - * @return void - */ - protected function calculateBarcodeWidth() - { - } -} diff --git a/library/Zend/Barcode/Object/Exception/BarcodeValidationException.php b/library/Zend/Barcode/Object/Exception/BarcodeValidationException.php deleted file mode 100755 index 64f3ea56e..000000000 --- a/library/Zend/Barcode/Object/Exception/BarcodeValidationException.php +++ /dev/null @@ -1,17 +0,0 @@ -barcodeLength = 12; - $this->mandatoryChecksum = true; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - return preg_replace('/([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{3})([0-9])/', '$1.$2 $3.$4 $5', $this->getText()); - } - - /** - * Check allowed characters - * @param string $value - * @return string - * @throws Exception\BarcodeValidationException - */ - public function validateText($value) - { - $this->validateSpecificText($value, array('validator' => $this->getType())); - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $checksum = 0; - - for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text{$i - 1}) * (($i % 2) ? 4 : 9); - } - - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Itf14.php b/library/Zend/Barcode/Object/Itf14.php deleted file mode 100755 index 361f9bd56..000000000 --- a/library/Zend/Barcode/Object/Itf14.php +++ /dev/null @@ -1,26 +0,0 @@ -barcodeLength = 14; - $this->mandatoryChecksum = true; - } -} diff --git a/library/Zend/Barcode/Object/Leitcode.php b/library/Zend/Barcode/Object/Leitcode.php deleted file mode 100755 index f82f3a5c0..000000000 --- a/library/Zend/Barcode/Object/Leitcode.php +++ /dev/null @@ -1,35 +0,0 @@ -barcodeLength = 14; - $this->mandatoryChecksum = true; - } - - /** - * Retrieve text to display - * @return string - */ - public function getTextToDisplay() - { - return preg_replace('/([0-9]{5})([0-9]{3})([0-9]{3})([0-9]{2})([0-9])/', '$1.$2.$3.$4 $5', $this->getText()); - } -} diff --git a/library/Zend/Barcode/Object/ObjectInterface.php b/library/Zend/Barcode/Object/ObjectInterface.php deleted file mode 100755 index 836e0138e..000000000 --- a/library/Zend/Barcode/Object/ObjectInterface.php +++ /dev/null @@ -1,337 +0,0 @@ - "00111", - 1 => "11100", - 2 => "11010", - 3 => "11001", - 4 => "10110", - 5 => "10101", - 6 => "10011", - 7 => "01110", - 8 => "01101", - 9 => "01011" - ); -} diff --git a/library/Zend/Barcode/Object/Postnet.php b/library/Zend/Barcode/Object/Postnet.php deleted file mode 100755 index 07b1d3c2d..000000000 --- a/library/Zend/Barcode/Object/Postnet.php +++ /dev/null @@ -1,110 +0,0 @@ - "11000", - 1 => "00011", - 2 => "00101", - 3 => "00110", - 4 => "01001", - 5 => "01010", - 6 => "01100", - 7 => "10001", - 8 => "10010", - 9 => "10100" - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function getDefaultOptions() - { - $this->barThinWidth = 2; - $this->barHeight = 20; - $this->drawText = false; - $this->stretchText = true; - $this->mandatoryChecksum = true; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (2 * $this->barThinWidth) * $this->factor; - $stopCharacter = (1 * $this->barThinWidth) * $this->factor; - $encodedData = (10 * $this->barThinWidth) * $this->factor * strlen($this->getText()); - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved Postnet barcode - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - - // Start character (1) - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - - // Text to encode - $textTable = str_split($this->getText()); - foreach ($textTable as $char) { - $bars = str_split($this->codingMap[$char]); - foreach ($bars as $b) { - $barcodeTable[] = array(1, $this->barThinWidth, 0.5 - $b * 0.5, 1); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - } - } - - // Stop character (1) - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $sum = array_sum(str_split($text)); - $checksum = (10 - ($sum % 10)) % 10; - return $checksum; - } -} diff --git a/library/Zend/Barcode/Object/Royalmail.php b/library/Zend/Barcode/Object/Royalmail.php deleted file mode 100755 index 23d8a709a..000000000 --- a/library/Zend/Barcode/Object/Royalmail.php +++ /dev/null @@ -1,137 +0,0 @@ - '3300', '1' => '3210', '2' => '3201', '3' => '2310', '4' => '2301', '5' => '2211', - '6' => '3120', '7' => '3030', '8' => '3021', '9' => '2130', 'A' => '2121', 'B' => '2031', - 'C' => '3102', 'D' => '3012', 'E' => '3003', 'F' => '2112', 'G' => '2103', 'H' => '2013', - 'I' => '1320', 'J' => '1230', 'K' => '1221', 'L' => '0330', 'M' => '0321', 'N' => '0231', - 'O' => '1302', 'P' => '1212', 'Q' => '1203', 'R' => '0312', 'S' => '0303', 'T' => '0213', - 'U' => '1122', 'V' => '1032', 'W' => '1023', 'X' => '0132', 'Y' => '0123', 'Z' => '0033' - ); - - protected $rows = array( - '0' => 1, '1' => 1, '2' => 1, '3' => 1, '4' => 1, '5' => 1, - '6' => 2, '7' => 2, '8' => 2, '9' => 2, 'A' => 2, 'B' => 2, - 'C' => 3, 'D' => 3, 'E' => 3, 'F' => 3, 'G' => 3, 'H' => 3, - 'I' => 4, 'J' => 4, 'K' => 4, 'L' => 4, 'M' => 4, 'N' => 4, - 'O' => 5, 'P' => 5, 'Q' => 5, 'R' => 5, 'S' => 5, 'T' => 5, - 'U' => 0, 'V' => 0, 'W' => 0, 'X' => 0, 'Y' => 0, 'Z' => 0, - ); - - protected $columns = array( - '0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5, '5' => 0, - '6' => 1, '7' => 2, '8' => 3, '9' => 4, 'A' => 5, 'B' => 0, - 'C' => 1, 'D' => 2, 'E' => 3, 'F' => 4, 'G' => 5, 'H' => 0, - 'I' => 1, 'J' => 2, 'K' => 3, 'L' => 4, 'M' => 5, 'N' => 0, - 'O' => 1, 'P' => 2, 'Q' => 3, 'R' => 4, 'S' => 5, 'T' => 0, - 'U' => 1, 'V' => 2, 'W' => 3, 'X' => 4, 'Y' => 5, 'Z' => 0, - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function getDefaultOptions() - { - $this->barThinWidth = 2; - $this->barHeight = 20; - $this->drawText = false; - $this->stretchText = true; - $this->mandatoryChecksum = true; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (2 * $this->barThinWidth) * $this->factor; - $stopCharacter = (1 * $this->barThinWidth) * $this->factor; - $encodedData = (8 * $this->barThinWidth) * $this->factor * strlen($this->getText()); - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Partial check of interleaved Postnet barcode - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - - // Start character (1) - $barcodeTable[] = array(1, $this->barThinWidth, 0, 5/8); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - - // Text to encode - $textTable = str_split($this->getText()); - foreach ($textTable as $char) { - $bars = str_split($this->codingMap[$char]); - foreach ($bars as $b) { - $barcodeTable[] = array(1, $this->barThinWidth, ($b > 1 ? 3/8 : 0), ($b % 2 ? 5/8 : 1)); - $barcodeTable[] = array(0, $this->barThinWidth, 0, 1); - } - } - - // Stop character (1) - $barcodeTable[] = array(1, $this->barThinWidth, 0, 1); - return $barcodeTable; - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $this->checkText($text); - $values = str_split($text); - $rowvalue = 0; - $colvalue = 0; - foreach ($values as $row) { - $rowvalue += $this->rows[$row]; - $colvalue += $this->columns[$row]; - } - - $rowvalue %= 6; - $colvalue %= 6; - - $rowchkvalue = array_keys($this->rows, $rowvalue); - $colchkvalue = array_keys($this->columns, $colvalue); - return current(array_intersect($rowchkvalue, $colchkvalue)); - } -} diff --git a/library/Zend/Barcode/Object/Upca.php b/library/Zend/Barcode/Object/Upca.php deleted file mode 100755 index 1add66c78..000000000 --- a/library/Zend/Barcode/Object/Upca.php +++ /dev/null @@ -1,144 +0,0 @@ -barcodeLength = 12; - $this->mandatoryChecksum = true; - $this->mandatoryQuietZones = true; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->barThinWidth) * $this->factor; - $middleCharacter = (5 * $this->barThinWidth) * $this->factor; - $stopCharacter = (3 * $this->barThinWidth) * $this->factor; - $encodedData = (7 * $this->barThinWidth) * $this->factor * 12; - return $quietZone + $startCharacter + $middleCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - - $textTable = str_split($this->getText()); - - // First character - $bars = str_split($this->codingMap['A'][$textTable[0]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, $height); - } - - // First part - for ($i = 1; $i < 6; $i++) { - $bars = str_split($this->codingMap['A'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Middle character (01010) - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - - // Second part - for ($i = 6; $i < 11; $i++) { - $bars = str_split($this->codingMap['C'][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Last character - $bars = str_split($this->codingMap['C'][$textTable[11]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, $height); - } - - // Stop character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - return $barcodeTable; - } - - /** - * Partial function to draw text - * @return void - */ - protected function drawText() - { - if ($this->drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->barThinWidth) * $this->factor; - $leftPosition = $this->getQuietZone() - $characterWidth; - for ($i = 0; $i < $this->barcodeLength; $i ++) { - $fontSize = $this->fontSize; - if ($i == 0 || $i == 11) { - $fontSize *= 0.8; - } - $this->addText( - $text{$i}, - $fontSize * $this->factor, - $this->rotate( - $leftPosition, - (int) $this->withBorder * 2 + $this->factor * ($this->barHeight + $fontSize) + 1 - ), - $this->font, - $this->foreColor, - 'left', - - $this->orientation - ); - switch ($i) { - case 0: - $factor = 10; - break; - case 5: - $factor = 4; - break; - case 10: - $factor = 11; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->barThinWidth * $this->factor); - } - } - } -} diff --git a/library/Zend/Barcode/Object/Upce.php b/library/Zend/Barcode/Object/Upce.php deleted file mode 100755 index 2114b11e3..000000000 --- a/library/Zend/Barcode/Object/Upce.php +++ /dev/null @@ -1,199 +0,0 @@ - array( - 0 => array('B','B','B','A','A','A'), - 1 => array('B','B','A','B','A','A'), - 2 => array('B','B','A','A','B','A'), - 3 => array('B','B','A','A','A','B'), - 4 => array('B','A','B','B','A','A'), - 5 => array('B','A','A','B','B','A'), - 6 => array('B','A','A','A','B','B'), - 7 => array('B','A','B','A','B','A'), - 8 => array('B','A','B','A','A','B'), - 9 => array('B','A','A','B','A','B')), - 1 => array( - 0 => array('A','A','A','B','B','B'), - 1 => array('A','A','B','A','B','B'), - 2 => array('A','A','B','B','A','B'), - 3 => array('A','A','B','B','B','A'), - 4 => array('A','B','A','A','B','B'), - 5 => array('A','B','B','A','A','B'), - 6 => array('A','B','B','B','A','A'), - 7 => array('A','B','A','B','A','B'), - 8 => array('A','B','A','B','B','A'), - 9 => array('A','B','B','A','B','A')) - ); - - /** - * Default options for Postnet barcode - * @return void - */ - protected function getDefaultOptions() - { - $this->barcodeLength = 8; - $this->mandatoryChecksum = true; - $this->mandatoryQuietZones = true; - } - - /** - * Retrieve text to encode - * @return string - */ - public function getText() - { - $text = parent::getText(); - if ($text[0] != 1) { - $text[0] = 0; - } - return $text; - } - - /** - * Width of the barcode (in pixels) - * @return int - */ - protected function calculateBarcodeWidth() - { - $quietZone = $this->getQuietZone(); - $startCharacter = (3 * $this->barThinWidth) * $this->factor; - $stopCharacter = (6 * $this->barThinWidth) * $this->factor; - $encodedData = (7 * $this->barThinWidth) * $this->factor * 6; - return $quietZone + $startCharacter + $encodedData + $stopCharacter + $quietZone; - } - - /** - * Prepare array to draw barcode - * @return array - */ - protected function prepareBarcode() - { - $barcodeTable = array(); - $height = ($this->drawText) ? 1.1 : 1; - - // Start character (101) - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - - $textTable = str_split($this->getText()); - $system = 0; - if ($textTable[0] == 1) { - $system = 1; - } - $checksum = $textTable[7]; - $parity = $this->parities[$system][$checksum]; - - for ($i = 1; $i < 7; $i++) { - $bars = str_split($this->codingMap[$parity[$i - 1]][$textTable[$i]]); - foreach ($bars as $b) { - $barcodeTable[] = array($b, $this->barThinWidth, 0, 1); - } - } - - // Stop character (10101) - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(0, $this->barThinWidth, 0, $height); - $barcodeTable[] = array(1, $this->barThinWidth, 0, $height); - return $barcodeTable; - } - - /** - * Partial function to draw text - * @return void - */ - protected function drawText() - { - if ($this->drawText) { - $text = $this->getTextToDisplay(); - $characterWidth = (7 * $this->barThinWidth) * $this->factor; - $leftPosition = $this->getQuietZone() - $characterWidth; - for ($i = 0; $i < $this->barcodeLength; $i ++) { - $fontSize = $this->fontSize; - if ($i == 0 || $i == 7) { - $fontSize *= 0.8; - } - $this->addText( - $text{$i}, - $fontSize * $this->factor, - $this->rotate( - $leftPosition, - (int) $this->withBorder * 2 + $this->factor * ($this->barHeight + $fontSize) + 1 - ), - $this->font, - $this->foreColor, - 'left', - - $this->orientation - ); - switch ($i) { - case 0: - $factor = 3; - break; - case 6: - $factor = 5; - break; - default: - $factor = 0; - } - $leftPosition = $leftPosition + $characterWidth + ($factor * $this->barThinWidth * $this->factor); - } - } - } - - /** - * Particular validation for Upce barcode objects - * (to suppress checksum character substitution) - * - * @param string $value - * @param array $options - * @throws Exception\BarcodeValidationException - */ - protected function validateSpecificText($value, $options = array()) - { - $validator = new BarcodeValidator(array( - 'adapter' => 'upce', - 'checksum' => false, - )); - - $value = $this->addLeadingZeros($value, true); - - if (!$validator->isValid($value)) { - $message = implode("\n", $validator->getMessages()); - throw new Exception\BarcodeValidationException($message); - } - } - - /** - * Get barcode checksum - * - * @param string $text - * @return int - */ - public function getChecksum($text) - { - $text = $this->addLeadingZeros($text, true); - if ($text[0] != 1) { - $text[0] = 0; - } - return parent::getChecksum($text); - } -} diff --git a/library/Zend/Barcode/ObjectPluginManager.php b/library/Zend/Barcode/ObjectPluginManager.php deleted file mode 100755 index 40345f83b..000000000 --- a/library/Zend/Barcode/ObjectPluginManager.php +++ /dev/null @@ -1,77 +0,0 @@ - 'Zend\Barcode\Object\Codabar', - 'code128' => 'Zend\Barcode\Object\Code128', - 'code25' => 'Zend\Barcode\Object\Code25', - 'code25interleaved' => 'Zend\Barcode\Object\Code25interleaved', - 'code39' => 'Zend\Barcode\Object\Code39', - 'ean13' => 'Zend\Barcode\Object\Ean13', - 'ean2' => 'Zend\Barcode\Object\Ean2', - 'ean5' => 'Zend\Barcode\Object\Ean5', - 'ean8' => 'Zend\Barcode\Object\Ean8', - 'error' => 'Zend\Barcode\Object\Error', - 'identcode' => 'Zend\Barcode\Object\Identcode', - 'itf14' => 'Zend\Barcode\Object\Itf14', - 'leitcode' => 'Zend\Barcode\Object\Leitcode', - 'planet' => 'Zend\Barcode\Object\Planet', - 'postnet' => 'Zend\Barcode\Object\Postnet', - 'royalmail' => 'Zend\Barcode\Object\Royalmail', - 'upca' => 'Zend\Barcode\Object\Upca', - 'upce' => 'Zend\Barcode\Object\Upce', - ); - - /** - * Validate the plugin - * - * Checks that the barcode parser loaded is an instance - * of Object\AbstractObject. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Object\AbstractObject) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must extend %s\Object\AbstractObject', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Barcode/README.md b/library/Zend/Barcode/README.md deleted file mode 100755 index 2dc1c0895..000000000 --- a/library/Zend/Barcode/README.md +++ /dev/null @@ -1,14 +0,0 @@ -Barcode Component from ZF2 -========================== - -This is the Barcode component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. diff --git a/library/Zend/Barcode/Renderer/AbstractRenderer.php b/library/Zend/Barcode/Renderer/AbstractRenderer.php deleted file mode 100755 index 8a625e853..000000000 --- a/library/Zend/Barcode/Renderer/AbstractRenderer.php +++ /dev/null @@ -1,515 +0,0 @@ -setOptions($options); - } - $this->type = strtolower(substr( - get_class($this), - strlen($this->rendererNamespace) + 1 - )); - } - - /** - * Set renderer state from options array - * @param array $options - * @return AbstractRenderer - */ - public function setOptions($options) - { - foreach ($options as $key => $value) { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Set renderer namespace for autoloading - * - * @param string $namespace - * @return AbstractRenderer - */ - public function setRendererNamespace($namespace) - { - $this->rendererNamespace = $namespace; - return $this; - } - - /** - * Retrieve renderer namespace - * - * @return string - */ - public function getRendererNamespace() - { - return $this->rendererNamespace; - } - - /** - * Set whether background should be transparent - * Will work for SVG and Image (png and gif only) - * - * @param $bool - * @return $this - */ - public function setTransparentBackground($bool) - { - $this->transparentBackground = $bool; - - return $this; - } - - /** - * @return bool - */ - public function getTransparentBackground() - { - return $this->transparentBackground; - } - - /** - * Retrieve renderer type - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Manually adjust top position - * @param int $value - * @return AbstractRenderer - * @throws Exception\OutOfRangeException - */ - public function setTopOffset($value) - { - if (!is_numeric($value) || intval($value) < 0) { - throw new Exception\OutOfRangeException( - 'Vertical position must be greater than or equals 0' - ); - } - $this->topOffset = intval($value); - return $this; - } - - /** - * Retrieve vertical adjustment - * @return int - */ - public function getTopOffset() - { - return $this->topOffset; - } - - /** - * Manually adjust left position - * @param int $value - * @return AbstractRenderer - * @throws Exception\OutOfRangeException - */ - public function setLeftOffset($value) - { - if (!is_numeric($value) || intval($value) < 0) { - throw new Exception\OutOfRangeException( - 'Horizontal position must be greater than or equals 0' - ); - } - $this->leftOffset = intval($value); - return $this; - } - - /** - * Retrieve vertical adjustment - * @return int - */ - public function getLeftOffset() - { - return $this->leftOffset; - } - - /** - * Activate/Deactivate the automatic rendering of exception - * @param bool $value - * @return AbstractRenderer - */ - public function setAutomaticRenderError($value) - { - $this->automaticRenderError = (bool) $value; - return $this; - } - - /** - * Horizontal position of the barcode in the rendering resource - * @param string $value - * @return AbstractRenderer - * @throws Exception\UnexpectedValueException - */ - public function setHorizontalPosition($value) - { - if (!in_array($value, array('left', 'center', 'right'))) { - throw new Exception\UnexpectedValueException( - "Invalid barcode position provided must be 'left', 'center' or 'right'" - ); - } - $this->horizontalPosition = $value; - return $this; - } - - /** - * Horizontal position of the barcode in the rendering resource - * @return string - */ - public function getHorizontalPosition() - { - return $this->horizontalPosition; - } - - /** - * Vertical position of the barcode in the rendering resource - * @param string $value - * @return AbstractRenderer - * @throws Exception\UnexpectedValueException - */ - public function setVerticalPosition($value) - { - if (!in_array($value, array('top', 'middle', 'bottom'))) { - throw new Exception\UnexpectedValueException( - "Invalid barcode position provided must be 'top', 'middle' or 'bottom'" - ); - } - $this->verticalPosition = $value; - return $this; - } - - /** - * Vertical position of the barcode in the rendering resource - * @return string - */ - public function getVerticalPosition() - { - return $this->verticalPosition; - } - - /** - * Set the size of a module - * @param float $value - * @return AbstractRenderer - * @throws Exception\OutOfRangeException - */ - public function setModuleSize($value) - { - if (!is_numeric($value) || floatval($value) <= 0) { - throw new Exception\OutOfRangeException( - 'Float size must be greater than 0' - ); - } - $this->moduleSize = floatval($value); - return $this; - } - - /** - * Set the size of a module - * @return float - */ - public function getModuleSize() - { - return $this->moduleSize; - } - - /** - * Retrieve the automatic rendering of exception - * @return bool - */ - public function getAutomaticRenderError() - { - return $this->automaticRenderError; - } - - /** - * Set the barcode object - * @param Object\ObjectInterface $barcode - * @return AbstractRenderer - */ - public function setBarcode(Object\ObjectInterface $barcode) - { - $this->barcode = $barcode; - return $this; - } - - /** - * Retrieve the barcode object - * @return Object\ObjectInterface - */ - public function getBarcode() - { - return $this->barcode; - } - - /** - * Checking of parameters after all settings - * @return bool - */ - public function checkParams() - { - $this->checkBarcodeObject(); - $this->checkSpecificParams(); - return true; - } - - /** - * Check if a barcode object is correctly provided - * @return void - * @throws Exception\RuntimeException - */ - protected function checkBarcodeObject() - { - if ($this->barcode === null) { - throw new Exception\RuntimeException( - 'No barcode object provided' - ); - } - } - - /** - * Calculate the left and top offset of the barcode in the - * rendering support - * - * @param float $supportHeight - * @param float $supportWidth - * @return void - */ - protected function adjustPosition($supportHeight, $supportWidth) - { - $barcodeHeight = $this->barcode->getHeight(true) * $this->moduleSize; - if ($barcodeHeight != $supportHeight && $this->topOffset == 0) { - switch ($this->verticalPosition) { - case 'middle': - $this->topOffset = floor(($supportHeight - $barcodeHeight) / 2); - break; - case 'bottom': - $this->topOffset = $supportHeight - $barcodeHeight; - break; - case 'top': - default: - $this->topOffset = 0; - break; - } - } - $barcodeWidth = $this->barcode->getWidth(true) * $this->moduleSize; - if ($barcodeWidth != $supportWidth && $this->leftOffset == 0) { - switch ($this->horizontalPosition) { - case 'center': - $this->leftOffset = floor(($supportWidth - $barcodeWidth) / 2); - break; - case 'right': - $this->leftOffset = $supportWidth - $barcodeWidth; - break; - case 'left': - default: - $this->leftOffset = 0; - break; - } - } - } - - /** - * Draw the barcode in the rendering resource - * - * @throws BarcodeException\ExceptionInterface - * @return mixed - */ - public function draw() - { - try { - $this->checkParams(); - $this->initRenderer(); - $this->drawInstructionList(); - } catch (BarcodeException\ExceptionInterface $e) { - if ($this->automaticRenderError && !($e instanceof BarcodeException\RendererCreationException)) { - $barcode = Barcode::makeBarcode( - 'error', - array('text' => $e->getMessage()) - ); - $this->setBarcode($barcode); - $this->resource = null; - $this->initRenderer(); - $this->drawInstructionList(); - } else { - throw $e; - } - } - return $this->resource; - } - - /** - * Sub process to draw the barcode instructions - * Needed by the automatic error rendering - */ - private function drawInstructionList() - { - $instructionList = $this->barcode->draw(); - foreach ($instructionList as $instruction) { - switch ($instruction['type']) { - case 'polygon': - $this->drawPolygon( - $instruction['points'], - $instruction['color'], - $instruction['filled'] - ); - break; - case 'text': //$text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0) - $this->drawText( - $instruction['text'], - $instruction['size'], - $instruction['position'], - $instruction['font'], - $instruction['color'], - $instruction['alignment'], - $instruction['orientation'] - ); - break; - default: - throw new Exception\UnexpectedValueException( - 'Unkown drawing command' - ); - } - } - } - - /** - * Checking of parameters after all settings - * @return void - */ - abstract protected function checkSpecificParams(); - - /** - * Initialize the rendering resource - * @return void - */ - abstract protected function initRenderer(); - - /** - * Draw a polygon in the rendering resource - * @param array $points - * @param int $color - * @param bool $filled - */ - abstract protected function drawPolygon($points, $color, $filled = true); - - /** - * Draw a polygon in the rendering resource - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param int $color - * @param string $alignment - * @param float $orientation - */ - abstract protected function drawText( - $text, - $size, - $position, - $font, - $color, - $alignment = 'center', - $orientation = 0 - ); -} diff --git a/library/Zend/Barcode/Renderer/Exception/ExceptionInterface.php b/library/Zend/Barcode/Renderer/Exception/ExceptionInterface.php deleted file mode 100755 index f7f4d4454..000000000 --- a/library/Zend/Barcode/Renderer/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -userHeight = intval($value); - return $this; - } - - /** - * Get barcode height - * - * @return int - */ - public function getHeight() - { - return $this->userHeight; - } - - /** - * Set barcode width - * - * @param mixed $value - * @throws Exception\OutOfRangeException - * @return self - */ - public function setWidth($value) - { - if (!is_numeric($value) || intval($value) < 0) { - throw new Exception\OutOfRangeException( - 'Image width must be greater than or equals 0' - ); - } - $this->userWidth = intval($value); - return $this; - } - - /** - * Get barcode width - * - * @return int - */ - public function getWidth() - { - return $this->userWidth; - } - - /** - * Set an image resource to draw the barcode inside - * - * @param resource $image - * @return Image - * @throws Exception\InvalidArgumentException - */ - public function setResource($image) - { - if (gettype($image) != 'resource' || get_resource_type($image) != 'gd') { - throw new Exception\InvalidArgumentException( - 'Invalid image resource provided to setResource()' - ); - } - $this->resource = $image; - return $this; - } - - /** - * Set the image type to produce (png, jpeg, gif) - * - * @param string $value - * @throws Exception\InvalidArgumentException - * @return Image - */ - public function setImageType($value) - { - if ($value == 'jpg') { - $value = 'jpeg'; - } - - if (!in_array($value, $this->allowedImageType)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid type "%s" provided to setImageType()', - $value - )); - } - - $this->imageType = $value; - return $this; - } - - /** - * Retrieve the image type to produce - * - * @return string - */ - public function getImageType() - { - return $this->imageType; - } - - /** - * Initialize the image resource - * - * @return void - */ - protected function initRenderer() - { - $barcodeWidth = $this->barcode->getWidth(true); - $barcodeHeight = $this->barcode->getHeight(true); - - if (null === $this->resource) { - $width = $barcodeWidth; - $height = $barcodeHeight; - if ($this->userWidth && $this->barcode->getType() != 'error') { - $width = $this->userWidth; - } - if ($this->userHeight && $this->barcode->getType() != 'error') { - $height = $this->userHeight; - } - - $this->resource = imagecreatetruecolor($width, $height); - - $white = imagecolorallocate($this->resource, 255, 255, 255); - imagefilledrectangle($this->resource, 0, 0, $width - 1, $height - 1, $white); - } - - $foreColor = $this->barcode->getForeColor(); - $this->imageForeColor = imagecolorallocate( - $this->resource, - ($foreColor & 0xFF0000) >> 16, - ($foreColor & 0x00FF00) >> 8, - $foreColor & 0x0000FF - ); - - $backgroundColor = $this->barcode->getBackgroundColor(); - $this->imageBackgroundColor = imagecolorallocate( - $this->resource, - ($backgroundColor & 0xFF0000) >> 16, - ($backgroundColor & 0x00FF00) >> 8, - $backgroundColor & 0x0000FF - ); - - // JPEG does not support transparency, if transparentBackground is true and - // image type is JPEG, ignore transparency - if ($this->getImageType() != "jpeg" && $this->transparentBackground) { - imagecolortransparent($this->resource, $this->imageBackgroundColor); - } - - $this->adjustPosition(imagesy($this->resource), imagesx($this->resource)); - - imagefilledrectangle( - $this->resource, - $this->leftOffset, - $this->topOffset, - $this->leftOffset + $barcodeWidth - 1, - $this->topOffset + $barcodeHeight - 1, - $this->imageBackgroundColor - ); - } - - /** - * Check barcode parameters - * - * @return void - */ - protected function checkSpecificParams() - { - $this->checkDimensions(); - } - - /** - * Check barcode dimensions - * - * @throws Exception\RuntimeException - * @return void - */ - protected function checkDimensions() - { - if ($this->resource !== null) { - if (imagesy($this->resource) < $this->barcode->getHeight(true)) { - throw new Exception\RuntimeException( - 'Barcode is define outside the image (height)' - ); - } - } else { - if ($this->userHeight) { - $height = $this->barcode->getHeight(true); - if ($this->userHeight < $height) { - throw new Exception\RuntimeException(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $height, - $this->userHeight - )); - } - } - } - if ($this->resource !== null) { - if (imagesx($this->resource) < $this->barcode->getWidth(true)) { - throw new Exception\RuntimeException( - 'Barcode is define outside the image (width)' - ); - } - } else { - if ($this->userWidth) { - $width = $this->barcode->getWidth(true); - if ($this->userWidth < $width) { - throw new Exception\RuntimeException(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $width, - $this->userWidth - )); - } - } - } - } - - /** - * Draw and render the barcode with correct headers - * - * @return mixed - */ - public function render() - { - $this->draw(); - header("Content-Type: image/" . $this->imageType); - $functionName = 'image' . $this->imageType; - $functionName($this->resource); - - ErrorHandler::start(E_WARNING); - imagedestroy($this->resource); - ErrorHandler::stop(); - } - - /** - * Draw a polygon in the image resource - * - * @param array $points - * @param int $color - * @param bool $filled - */ - protected function drawPolygon($points, $color, $filled = true) - { - $newPoints = array($points[0][0] + $this->leftOffset, - $points[0][1] + $this->topOffset, - $points[1][0] + $this->leftOffset, - $points[1][1] + $this->topOffset, - $points[2][0] + $this->leftOffset, - $points[2][1] + $this->topOffset, - $points[3][0] + $this->leftOffset, - $points[3][1] + $this->topOffset, ); - - $allocatedColor = imagecolorallocate( - $this->resource, - ($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - $color & 0x0000FF - ); - - if ($filled) { - imagefilledpolygon($this->resource, $newPoints, 4, $allocatedColor); - } else { - imagepolygon($this->resource, $newPoints, 4, $allocatedColor); - } - } - - /** - * Draw a polygon in the image resource - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param int $color - * @param string $alignment - * @param float $orientation - * @throws Exception\RuntimeException - */ - protected function drawText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0) - { - $allocatedColor = imagecolorallocate( - $this->resource, - ($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - $color & 0x0000FF - ); - - if ($font == null) { - $font = 3; - } - $position[0] += $this->leftOffset; - $position[1] += $this->topOffset; - - if (is_numeric($font)) { - if ($orientation) { - /** - * imagestring() doesn't allow orientation, if orientation - * needed: a TTF font is required. - * Throwing an exception here, allow to use automaticRenderError - * to informe user of the problem instead of simply not drawing - * the text - */ - throw new Exception\RuntimeException( - 'No orientation possible with GD internal font' - ); - } - $fontWidth = imagefontwidth($font); - $positionY = $position[1] - imagefontheight($font) + 1; - switch ($alignment) { - case 'left': - $positionX = $position[0]; - break; - case 'center': - $positionX = $position[0] - ceil(($fontWidth * strlen($text)) / 2); - break; - case 'right': - $positionX = $position[0] - ($fontWidth * strlen($text)); - break; - } - imagestring($this->resource, $font, $positionX, $positionY, $text, $color); - } else { - if (!function_exists('imagettfbbox')) { - throw new Exception\RuntimeException( - 'A font was provided, but this instance of PHP does not have TTF (FreeType) support' - ); - } - - $box = imagettfbbox($size, 0, $font, $text); - switch ($alignment) { - case 'left': - $width = 0; - break; - case 'center': - $width = ($box[2] - $box[0]) / 2; - break; - case 'right': - $width = ($box[2] - $box[0]); - break; - } - imagettftext( - $this->resource, - $size, - $orientation, - $position[0] - ($width * cos(pi() * $orientation / 180)), - $position[1] + ($width * sin(pi() * $orientation / 180)), - $allocatedColor, - $font, - $text - ); - } - } -} diff --git a/library/Zend/Barcode/Renderer/Pdf.php b/library/Zend/Barcode/Renderer/Pdf.php deleted file mode 100755 index e4e084d49..000000000 --- a/library/Zend/Barcode/Renderer/Pdf.php +++ /dev/null @@ -1,215 +0,0 @@ -resource = $pdf; - $this->page = intval($page); - - if (!count($this->resource->pages)) { - $this->page = 0; - $this->resource->pages[] = new Page( - Page::SIZE_A4 - ); - } - return $this; - } - - /** - * Check renderer parameters - * - * @return void - */ - protected function checkSpecificParams() - { - } - - /** - * Draw the barcode in the PDF, send headers and the PDF - * @return mixed - */ - public function render() - { - $this->draw(); - header("Content-Type: application/pdf"); - echo $this->resource->render(); - } - - /** - * Initialize the PDF resource - * @return void - */ - protected function initRenderer() - { - if ($this->resource === null) { - $this->resource = new PdfDocument(); - $this->resource->pages[] = new Page( - Page::SIZE_A4 - ); - } - - $pdfPage = $this->resource->pages[$this->page]; - $this->adjustPosition($pdfPage->getHeight(), $pdfPage->getWidth()); - } - - /** - * Draw a polygon in the rendering resource - * @param array $points - * @param int $color - * @param bool $filled - */ - protected function drawPolygon($points, $color, $filled = true) - { - $page = $this->resource->pages[$this->page]; - $x = array(); - $y = array(); - foreach ($points as $point) { - $x[] = $point[0] * $this->moduleSize + $this->leftOffset; - $y[] = $page->getHeight() - $point[1] * $this->moduleSize - $this->topOffset; - } - if (count($y) == 4) { - if ($x[0] != $x[3] && $y[0] == $y[3]) { - $y[0] -= ($this->moduleSize / 2); - $y[3] -= ($this->moduleSize / 2); - } - if ($x[1] != $x[2] && $y[1] == $y[2]) { - $y[1] += ($this->moduleSize / 2); - $y[2] += ($this->moduleSize / 2); - } - } - - $color = new Color\Rgb( - (($color & 0xFF0000) >> 16) / 255.0, - (($color & 0x00FF00) >> 8) / 255.0, - ($color & 0x0000FF) / 255.0 - ); - - $page->setLineColor($color); - $page->setFillColor($color); - $page->setLineWidth($this->moduleSize); - - $fillType = ($filled) - ? Page::SHAPE_DRAW_FILL_AND_STROKE - : Page::SHAPE_DRAW_STROKE; - - $page->drawPolygon($x, $y, $fillType); - } - - /** - * Draw a polygon in the rendering resource - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param int $color - * @param string $alignment - * @param float $orientation - */ - protected function drawText( - $text, - $size, - $position, - $font, - $color, - $alignment = 'center', - $orientation = 0 - ) { - $page = $this->resource->pages[$this->page]; - $color = new Color\Rgb( - (($color & 0xFF0000) >> 16) / 255.0, - (($color & 0x00FF00) >> 8) / 255.0, - ($color & 0x0000FF) / 255.0 - ); - - $page->setLineColor($color); - $page->setFillColor($color); - $page->setFont(Font::fontWithPath($font), $size * $this->moduleSize * 1.2); - - $width = $this->widthForStringUsingFontSize( - $text, - Font::fontWithPath($font), - $size * $this->moduleSize - ); - - $angle = pi() * $orientation / 180; - $left = $position[0] * $this->moduleSize + $this->leftOffset; - $top = $page->getHeight() - $position[1] * $this->moduleSize - $this->topOffset; - - switch ($alignment) { - case 'center': - $left -= ($width / 2) * cos($angle); - $top -= ($width / 2) * sin($angle); - break; - case 'right': - $left -= $width; - break; - } - $page->rotate($left, $top, $angle); - $page->drawText($text, $left, $top); - $page->rotate($left, $top, - $angle); - } - - /** - * Calculate the width of a string: - * in case of using alignment parameter in drawText - * @param string $text - * @param Font $font - * @param float $fontSize - * @return float - */ - public function widthForStringUsingFontSize($text, $font, $fontSize) - { - $drawingString = iconv('UTF-8', 'UTF-16BE//IGNORE', $text); - $characters = array(); - for ($i = 0, $len = strlen($drawingString); $i < $len; $i++) { - $characters[] = (ord($drawingString[$i ++]) << 8) | ord($drawingString[$i]); - } - $glyphs = $font->glyphNumbersForCharacters($characters); - $widths = $font->widthsForGlyphs($glyphs); - $stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize; - return $stringWidth; - } -} diff --git a/library/Zend/Barcode/Renderer/RendererInterface.php b/library/Zend/Barcode/Renderer/RendererInterface.php deleted file mode 100755 index 795654f30..000000000 --- a/library/Zend/Barcode/Renderer/RendererInterface.php +++ /dev/null @@ -1,161 +0,0 @@ -userHeight = intval($value); - return $this; - } - - /** - * Get barcode height - * - * @return int - */ - public function getHeight() - { - return $this->userHeight; - } - - /** - * Set barcode width - * - * @param mixed $value - * @throws Exception\OutOfRangeException - * @return self - */ - public function setWidth($value) - { - if (!is_numeric($value) || intval($value) < 0) { - throw new Exception\OutOfRangeException( - 'Svg width must be greater than or equals 0' - ); - } - $this->userWidth = intval($value); - return $this; - } - - /** - * Get barcode width - * - * @return int - */ - public function getWidth() - { - return $this->userWidth; - } - - /** - * Set an image resource to draw the barcode inside - * - * @param DOMDocument $svg - * @return Svg - */ - public function setResource(DOMDocument $svg) - { - $this->resource = $svg; - return $this; - } - - /** - * Initialize the image resource - * - * @return void - */ - protected function initRenderer() - { - $barcodeWidth = $this->barcode->getWidth(true); - $barcodeHeight = $this->barcode->getHeight(true); - - $backgroundColor = $this->barcode->getBackgroundColor(); - $imageBackgroundColor = 'rgb(' . implode(', ', array(($backgroundColor & 0xFF0000) >> 16, - ($backgroundColor & 0x00FF00) >> 8, - ($backgroundColor & 0x0000FF))) . ')'; - - $width = $barcodeWidth; - $height = $barcodeHeight; - if ($this->userWidth && $this->barcode->getType() != 'error') { - $width = $this->userWidth; - } - if ($this->userHeight && $this->barcode->getType() != 'error') { - $height = $this->userHeight; - } - if ($this->resource === null) { - $this->resource = new DOMDocument('1.0', 'utf-8'); - $this->resource->formatOutput = true; - $this->rootElement = $this->resource->createElement('svg'); - $this->rootElement->setAttribute('xmlns', "http://www.w3.org/2000/svg"); - $this->rootElement->setAttribute('version', '1.1'); - $this->rootElement->setAttribute('width', $width); - $this->rootElement->setAttribute('height', $height); - - $this->appendRootElement( - 'title', - array(), - "Barcode " . strtoupper($this->barcode->getType()) . " " . $this->barcode->getText() - ); - } else { - $this->readRootElement(); - $width = $this->rootElement->getAttribute('width'); - $height = $this->rootElement->getAttribute('height'); - } - $this->adjustPosition($height, $width); - - $rect = array('x' => $this->leftOffset, - 'y' => $this->topOffset, - 'width' => ($this->leftOffset + $barcodeWidth - 1), - 'height' => ($this->topOffset + $barcodeHeight - 1), - 'fill' => $imageBackgroundColor); - - if ($this->transparentBackground) { - $rect['fill-opacity'] = 0; - } - - $this->appendRootElement('rect', $rect); - } - - protected function readRootElement() - { - if ($this->resource !== null) { - $this->rootElement = $this->resource->documentElement; - } - } - - /** - * Append a new DOMElement to the root element - * - * @param string $tagName - * @param array $attributes - * @param string $textContent - */ - protected function appendRootElement($tagName, $attributes = array(), $textContent = null) - { - $newElement = $this->createElement($tagName, $attributes, $textContent); - $this->rootElement->appendChild($newElement); - } - - /** - * Create DOMElement - * - * @param string $tagName - * @param array $attributes - * @param string $textContent - * @return DOMElement - */ - protected function createElement($tagName, $attributes = array(), $textContent = null) - { - $element = $this->resource->createElement($tagName); - foreach ($attributes as $k => $v) { - $element->setAttribute($k, $v); - } - if ($textContent !== null) { - $element->appendChild(new DOMText((string) $textContent)); - } - return $element; - } - - /** - * Check barcode parameters - * - * @return void - */ - protected function checkSpecificParams() - { - $this->checkDimensions(); - } - - /** - * Check barcode dimensions - * - * @throws Exception\RuntimeException - * @return void - */ - protected function checkDimensions() - { - if ($this->resource !== null) { - $this->readRootElement(); - $height = (float) $this->rootElement->getAttribute('height'); - if ($height < $this->barcode->getHeight(true)) { - throw new Exception\RuntimeException( - 'Barcode is define outside the image (height)' - ); - } - } else { - if ($this->userHeight) { - $height = $this->barcode->getHeight(true); - if ($this->userHeight < $height) { - throw new Exception\RuntimeException(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $height, - $this->userHeight - )); - } - } - } - if ($this->resource !== null) { - $this->readRootElement(); - $width = $this->rootElement->getAttribute('width'); - if ($width < $this->barcode->getWidth(true)) { - throw new Exception\RuntimeException( - 'Barcode is define outside the image (width)' - ); - } - } else { - if ($this->userWidth) { - $width = (float) $this->barcode->getWidth(true); - if ($this->userWidth < $width) { - throw new Exception\RuntimeException(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $width, - $this->userWidth - )); - } - } - } - } - - /** - * Draw the barcode in the rendering resource - * @return DOMDocument - */ - public function draw() - { - parent::draw(); - $this->resource->appendChild($this->rootElement); - return $this->resource; - } - - /** - * Draw and render the barcode with correct headers - * - * @return mixed - */ - public function render() - { - $this->draw(); - header("Content-Type: image/svg+xml"); - echo $this->resource->saveXML(); - } - - /** - * Draw a polygon in the svg resource - * - * @param array $points - * @param int $color - * @param bool $filled - */ - protected function drawPolygon($points, $color, $filled = true) - { - $color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - ($color & 0x0000FF))) . ')'; - $orientation = $this->getBarcode()->getOrientation(); - $newPoints = array( - $points[0][0] + $this->leftOffset, - $points[0][1] + $this->topOffset, - $points[1][0] + $this->leftOffset, - $points[1][1] + $this->topOffset, - $points[2][0] + $this->leftOffset + cos(-$orientation), - $points[2][1] + $this->topOffset - sin($orientation), - $points[3][0] + $this->leftOffset + cos(-$orientation), - $points[3][1] + $this->topOffset - sin($orientation), - ); - $newPoints = implode(' ', $newPoints); - $attributes = array(); - $attributes['points'] = $newPoints; - $attributes['fill'] = $color; - - // SVG passes a rect in as the first call to drawPolygon, we'll need to intercept - // this and set transparency if necessary. - if (!$this->drawPolygonExecuted) { - if ($this->transparentBackground) { - $attributes['fill-opacity'] = '0'; - } - $this->drawPolygonExecuted = true; - } - - $this->appendRootElement('polygon', $attributes); - } - - /** - * Draw a polygon in the svg resource - * - * @param string $text - * @param float $size - * @param array $position - * @param string $font - * @param int $color - * @param string $alignment - * @param float $orientation - */ - protected function drawText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0) - { - $color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16, - ($color & 0x00FF00) >> 8, - ($color & 0x0000FF))) . ')'; - $attributes = array(); - $attributes['x'] = $position[0] + $this->leftOffset; - $attributes['y'] = $position[1] + $this->topOffset; - //$attributes['font-family'] = $font; - $attributes['color'] = $color; - $attributes['font-size'] = $size * 1.2; - switch ($alignment) { - case 'left': - $textAnchor = 'start'; - break; - case 'right': - $textAnchor = 'end'; - break; - case 'center': - default: - $textAnchor = 'middle'; - } - $attributes['style'] = 'text-anchor: ' . $textAnchor; - $attributes['transform'] = 'rotate(' - . (- $orientation) - . ', ' - . ($position[0] + $this->leftOffset) - . ', ' . ($position[1] + $this->topOffset) - . ')'; - $this->appendRootElement('text', $attributes, $text); - } -} diff --git a/library/Zend/Barcode/RendererPluginManager.php b/library/Zend/Barcode/RendererPluginManager.php deleted file mode 100755 index 0c8c2f8ae..000000000 --- a/library/Zend/Barcode/RendererPluginManager.php +++ /dev/null @@ -1,62 +0,0 @@ - 'Zend\Barcode\Renderer\Image', - 'pdf' => 'Zend\Barcode\Renderer\Pdf', - 'svg' => 'Zend\Barcode\Renderer\Svg' - ); - - /** - * Validate the plugin - * - * Checks that the barcode parser loaded is an instance - * of Renderer\AbstractRenderer. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Renderer\AbstractRenderer) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must extend %s\Renderer\AbstractRenderer', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Barcode/composer.json b/library/Zend/Barcode/composer.json deleted file mode 100755 index f351302eb..000000000 --- a/library/Zend/Barcode/composer.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "zendframework/zend-barcode", - "description": "provides a generic way to generate barcodes", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "barcode" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Barcode\\": "" - } - }, - "target-dir": "Zend/Barcode", - "require": { - "php": ">=5.3.23", - "zendframework/zend-stdlib": "self.version", - "zendframework/zend-validator": "self.version" - }, - "require-dev": { - "zendframework/zend-servicemanager": "self.version", - "zendframework/zendpdf": "*" - }, - "suggest": { - "zendframework/zend-servicemanager": "Zend\\ServiceManager component, required when using the factory methods of Zend\\Barcode.", - "zendframework/zendpdf": "ZendPdf component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Cache/CONTRIBUTING.md b/library/Zend/Cache/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Cache/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Cache/Exception/BadMethodCallException.php b/library/Zend/Cache/Exception/BadMethodCallException.php deleted file mode 100755 index dc8af1fc5..000000000 --- a/library/Zend/Cache/Exception/BadMethodCallException.php +++ /dev/null @@ -1,15 +0,0 @@ -options = $options; - return $this; - } - - /** - * Get all pattern options - * - * @return PatternOptions - */ - public function getOptions() - { - if (null === $this->options) { - $this->setOptions(new PatternOptions()); - } - return $this->options; - } -} diff --git a/library/Zend/Cache/Pattern/CallbackCache.php b/library/Zend/Cache/Pattern/CallbackCache.php deleted file mode 100755 index a26a00746..000000000 --- a/library/Zend/Cache/Pattern/CallbackCache.php +++ /dev/null @@ -1,200 +0,0 @@ -getStorage()) { - throw new Exception\InvalidArgumentException("Missing option 'storage'"); - } - return $this; - } - - /** - * Call the specified callback or get the result from cache - * - * @param callable $callback A valid callback - * @param array $args Callback arguments - * @return mixed Result - * @throws Exception\RuntimeException if invalid cached data - * @throws \Exception - */ - public function call($callback, array $args = array()) - { - $options = $this->getOptions(); - $storage = $options->getStorage(); - $success = null; - $key = $this->generateCallbackKey($callback, $args); - $result = $storage->getItem($key, $success); - if ($success) { - if (!array_key_exists(0, $result)) { - throw new Exception\RuntimeException("Invalid cached data for key '{$key}'"); - } - - echo isset($result[1]) ? $result[1] : ''; - return $result[0]; - } - - $cacheOutput = $options->getCacheOutput(); - if ($cacheOutput) { - ob_start(); - ob_implicit_flush(false); - } - - // TODO: do not cache on errors using [set|restore]_error_handler - - try { - if ($args) { - $ret = call_user_func_array($callback, $args); - } else { - $ret = call_user_func($callback); - } - } catch (\Exception $e) { - if ($cacheOutput) { - ob_end_flush(); - } - throw $e; - } - - if ($cacheOutput) { - $data = array($ret, ob_get_flush()); - } else { - $data = array($ret); - } - - $storage->setItem($key, $data); - - return $ret; - } - - /** - * function call handler - * - * @param string $function Function name to call - * @param array $args Function arguments - * @return mixed - * @throws Exception\RuntimeException - * @throws \Exception - */ - public function __call($function, array $args) - { - return $this->call($function, $args); - } - - /** - * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part. - * - * @param callable $callback A valid callback - * @param array $args Callback arguments - * @return string - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - */ - public function generateKey($callback, array $args = array()) - { - return $this->generateCallbackKey($callback, $args); - } - - /** - * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part. - * - * @param callable $callback A valid callback - * @param array $args Callback arguments - * @throws Exception\RuntimeException if callback not serializable - * @throws Exception\InvalidArgumentException if invalid callback - * @return string - */ - protected function generateCallbackKey($callback, array $args) - { - if (!is_callable($callback, false, $callbackKey)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - // functions, methods and classnames are case-insensitive - $callbackKey = strtolower($callbackKey); - - // generate a unique key of object callbacks - if (is_object($callback)) { // Closures & __invoke - $object = $callback; - } elseif (isset($callback[0])) { // array($object, 'method') - $object = $callback[0]; - } - if (isset($object)) { - ErrorHandler::start(); - try { - $serializedObject = serialize($object); - } catch (\Exception $e) { - ErrorHandler::stop(); - throw new Exception\RuntimeException("Can't serialize callback: see previous exception", 0, $e); - } - $error = ErrorHandler::stop(); - - if (!$serializedObject) { - throw new Exception\RuntimeException( - sprintf('Cannot serialize callback%s', ($error ? ': ' . $error->getMessage() : '')), - 0, - $error - ); - } - $callbackKey.= $serializedObject; - } - - return md5($callbackKey) . $this->generateArgumentsKey($args); - } - - /** - * Generate a unique key of the argument part. - * - * @param array $args - * @throws Exception\RuntimeException - * @return string - */ - protected function generateArgumentsKey(array $args) - { - if (!$args) { - return ''; - } - - ErrorHandler::start(); - try { - $serializedArgs = serialize(array_values($args)); - } catch (\Exception $e) { - ErrorHandler::stop(); - throw new Exception\RuntimeException("Can't serialize arguments: see previous exception", 0, $e); - } - $error = ErrorHandler::stop(); - - if (!$serializedArgs) { - throw new Exception\RuntimeException( - sprintf('Cannot serialize arguments%s', ($error ? ': ' . $error->getMessage() : '')), - 0, - $error - ); - } - - return md5($serializedArgs); - } -} diff --git a/library/Zend/Cache/Pattern/CaptureCache.php b/library/Zend/Cache/Pattern/CaptureCache.php deleted file mode 100755 index 7d5cec698..000000000 --- a/library/Zend/Cache/Pattern/CaptureCache.php +++ /dev/null @@ -1,388 +0,0 @@ -detectPageId(); - } - - $that = $this; - ob_start(function ($content) use ($that, $pageId) { - $that->set($content, $pageId); - - // http://php.net/manual/function.ob-start.php - // -> If output_callback returns FALSE original input is sent to the browser. - return false; - }); - - ob_implicit_flush(false); - } - - /** - * Write content to page identity - * - * @param string $content - * @param null|string $pageId - * @throws Exception\LogicException - */ - public function set($content, $pageId = null) - { - $publicDir = $this->getOptions()->getPublicDir(); - if ($publicDir === null) { - throw new Exception\LogicException("Option 'public_dir' no set"); - } - - if ($pageId === null) { - $pageId = $this->detectPageId(); - } - - $path = $this->pageId2Path($pageId); - $file = $path . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); - - $this->createDirectoryStructure($publicDir . DIRECTORY_SEPARATOR . $path); - $this->putFileContent($publicDir . DIRECTORY_SEPARATOR . $file, $content); - } - - /** - * Get from cache - * - * @param null|string $pageId - * @return string|null - * @throws Exception\LogicException - * @throws Exception\RuntimeException - */ - public function get($pageId = null) - { - $publicDir = $this->getOptions()->getPublicDir(); - if ($publicDir === null) { - throw new Exception\LogicException("Option 'public_dir' no set"); - } - - if ($pageId === null) { - $pageId = $this->detectPageId(); - } - - $file = $publicDir - . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); - - if (file_exists($file)) { - ErrorHandler::start(); - $content = file_get_contents($file); - $error = ErrorHandler::stop(); - if ($content === false) { - throw new Exception\RuntimeException("Failed to read cached pageId '{$pageId}'", 0, $error); - } - return $content; - } - } - - /** - * Checks if a cache with given id exists - * - * @param null|string $pageId - * @throws Exception\LogicException - * @return bool - */ - public function has($pageId = null) - { - $publicDir = $this->getOptions()->getPublicDir(); - if ($publicDir === null) { - throw new Exception\LogicException("Option 'public_dir' no set"); - } - - if ($pageId === null) { - $pageId = $this->detectPageId(); - } - - $file = $publicDir - . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); - - return file_exists($file); - } - - /** - * Remove from cache - * - * @param null|string $pageId - * @throws Exception\LogicException - * @throws Exception\RuntimeException - * @return bool - */ - public function remove($pageId = null) - { - $publicDir = $this->getOptions()->getPublicDir(); - if ($publicDir === null) { - throw new Exception\LogicException("Option 'public_dir' no set"); - } - - if ($pageId === null) { - $pageId = $this->detectPageId(); - } - - $file = $publicDir - . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); - - if (file_exists($file)) { - ErrorHandler::start(); - $res = unlink($file); - $err = ErrorHandler::stop(); - if (!$res) { - throw new Exception\RuntimeException("Failed to remove cached pageId '{$pageId}'", 0, $err); - } - return true; - } - - return false; - } - - /** - * Clear cached pages matching glob pattern - * - * @param string $pattern - * @throws Exception\LogicException - */ - public function clearByGlob($pattern = '**') - { - $publicDir = $this->getOptions()->getPublicDir(); - if ($publicDir === null) { - throw new Exception\LogicException("Option 'public_dir' no set"); - } - - $it = new \GlobIterator( - $publicDir . '/' . $pattern, - \GlobIterator::CURRENT_AS_SELF | \GlobIterator::SKIP_DOTS | \GlobIterator::UNIX_PATHS - ); - foreach ($it as $pathname => $entry) { - if ($entry->isFile()) { - unlink($pathname); - } - } - } - - /** - * Determine the page to save from the request - * - * @throws Exception\RuntimeException - * @return string - */ - protected function detectPageId() - { - if (!isset($_SERVER['REQUEST_URI'])) { - throw new Exception\RuntimeException("Can't auto-detect current page identity"); - } - - return $_SERVER['REQUEST_URI']; - } - - /** - * Get filename for page id - * - * @param string $pageId - * @return string - */ - protected function pageId2Filename($pageId) - { - if (substr($pageId, -1) === '/') { - return $this->getOptions()->getIndexFilename(); - } - - return basename($pageId); - } - - /** - * Get path for page id - * - * @param string $pageId - * @return string - */ - protected function pageId2Path($pageId) - { - if (substr($pageId, -1) == '/') { - $path = rtrim($pageId, '/'); - } else { - $path = dirname($pageId); - } - - // convert requested "/" to the valid local directory separator - if ('/' != DIRECTORY_SEPARATOR) { - $path = str_replace('/', DIRECTORY_SEPARATOR, $path); - } - - return $path; - } - - /** - * Write content to a file - * - * @param string $file File complete path - * @param string $data Data to write - * @return void - * @throws Exception\RuntimeException - */ - protected function putFileContent($file, $data) - { - $options = $this->getOptions(); - $locking = $options->getFileLocking(); - $perm = $options->getFilePermission(); - $umask = $options->getUmask(); - if ($umask !== false && $perm !== false) { - $perm = $perm & ~$umask; - } - - ErrorHandler::start(); - - $umask = ($umask !== false) ? umask($umask) : false; - $rs = file_put_contents($file, $data, $locking ? LOCK_EX : 0); - if ($umask) { - umask($umask); - } - - if ($rs === false) { - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error writing file '{$file}'", 0, $err); - } - - if ($perm !== false && !chmod($file, $perm)) { - $oct = decoct($perm); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("chmod('{$file}', 0{$oct}) failed", 0, $err); - } - - ErrorHandler::stop(); - } - - /** - * Creates directory if not already done. - * - * @param string $pathname - * @return void - * @throws Exception\RuntimeException - */ - protected function createDirectoryStructure($pathname) - { - // Directory structure already exists - if (file_exists($pathname)) { - return; - } - - $options = $this->getOptions(); - $perm = $options->getDirPermission(); - $umask = $options->getUmask(); - if ($umask !== false && $perm !== false) { - $perm = $perm & ~$umask; - } - - ErrorHandler::start(); - - if ($perm === false) { - // build-in mkdir function is enough - - $umask = ($umask !== false) ? umask($umask) : false; - $res = mkdir($pathname, ($perm !== false) ? $perm : 0777, true); - - if ($umask !== false) { - umask($umask); - } - - if (!$res) { - $oct = ($perm === false) ? '777' : decoct($perm); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("mkdir('{$pathname}', 0{$oct}, true) failed", 0, $err); - } - - if ($perm !== false && !chmod($pathname, $perm)) { - $oct = decoct($perm); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("chmod('{$pathname}', 0{$oct}) failed", 0, $err); - } - } else { - // build-in mkdir function sets permission together with current umask - // which doesn't work well on multo threaded webservers - // -> create directories one by one and set permissions - - // find existing path and missing path parts - $parts = array(); - $path = $pathname; - while (!file_exists($path)) { - array_unshift($parts, basename($path)); - $nextPath = dirname($path); - if ($nextPath === $path) { - break; - } - $path = $nextPath; - } - - // make all missing path parts - foreach ($parts as $part) { - $path.= DIRECTORY_SEPARATOR . $part; - - // create a single directory, set and reset umask immediately - $umask = ($umask !== false) ? umask($umask) : false; - $res = mkdir($path, ($perm === false) ? 0777 : $perm, false); - if ($umask !== false) { - umask($umask); - } - - if (!$res) { - $oct = ($perm === false) ? '777' : decoct($perm); - ErrorHandler::stop(); - throw new Exception\RuntimeException( - "mkdir('{$path}', 0{$oct}, false) failed" - ); - } - - if ($perm !== false && !chmod($path, $perm)) { - $oct = decoct($perm); - ErrorHandler::stop(); - throw new Exception\RuntimeException( - "chmod('{$path}', 0{$oct}) failed" - ); - } - } - } - - ErrorHandler::stop(); - } - - /** - * Returns the generated file name. - * - * @param null|string $pageId - * @return string - */ - public function getFilename($pageId = null) - { - if ($pageId === null) { - $pageId = $this->detectPageId(); - } - - $publicDir = $this->getOptions()->getPublicDir(); - $path = $this->pageId2Path($pageId); - $file = $path . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); - - return $publicDir . $file; - } -} diff --git a/library/Zend/Cache/Pattern/ClassCache.php b/library/Zend/Cache/Pattern/ClassCache.php deleted file mode 100755 index 238feed5e..000000000 --- a/library/Zend/Cache/Pattern/ClassCache.php +++ /dev/null @@ -1,167 +0,0 @@ -getClass()) { - throw new Exception\InvalidArgumentException("Missing option 'class'"); - } elseif (!$options->getStorage()) { - throw new Exception\InvalidArgumentException("Missing option 'storage'"); - } - return $this; - } - - /** - * Call and cache a class method - * - * @param string $method Method name to call - * @param array $args Method arguments - * @return mixed - * @throws Exception\RuntimeException - * @throws \Exception - */ - public function call($method, array $args = array()) - { - $options = $this->getOptions(); - $classname = $options->getClass(); - $method = strtolower($method); - $callback = $classname . '::' . $method; - - $cache = $options->getCacheByDefault(); - if ($cache) { - $cache = !in_array($method, $options->getClassNonCacheMethods()); - } else { - $cache = in_array($method, $options->getClassCacheMethods()); - } - - if (!$cache) { - if ($args) { - return call_user_func_array($callback, $args); - } else { - return $classname::$method(); - } - } - - return parent::call($callback, $args); - } - - /** - * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part. - * - * @param string $method The method - * @param array $args Callback arguments - * @return string - * @throws Exception\RuntimeException - */ - public function generateKey($method, array $args = array()) - { - return $this->generateCallbackKey( - $this->getOptions()->getClass() . '::' . $method, - $args - ); - } - - /** - * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part. - * - * @param callable $callback A valid callback - * @param array $args Callback arguments - * @return string - * @throws Exception\RuntimeException - */ - protected function generateCallbackKey($callback, array $args) - { - $callbackKey = md5(strtolower($callback)); - $argumentKey = $this->generateArgumentsKey($args); - return $callbackKey . $argumentKey; - } - - /** - * Calling a method of the entity. - * - * @param string $method Method name to call - * @param array $args Method arguments - * @return mixed - * @throws Exception\RuntimeException - * @throws \Exception - */ - public function __call($method, array $args) - { - return $this->call($method, $args); - } - - /** - * Set a static property - * - * @param string $name - * @param mixed $value - * @return void - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members - */ - public function __set($name, $value) - { - $class = $this->getOptions()->getClass(); - $class::$name = $value; - } - - /** - * Get a static property - * - * @param string $name - * @return mixed - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members - */ - public function __get($name) - { - $class = $this->getOptions()->getClass(); - return $class::$name; - } - - /** - * Is a static property exists. - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - $class = $this->getOptions()->getClass(); - return isset($class::$name); - } - - /** - * Unset a static property - * - * @param string $name - * @return void - */ - public function __unset($name) - { - $class = $this->getOptions()->getClass(); - unset($class::$name); - } -} diff --git a/library/Zend/Cache/Pattern/ObjectCache.php b/library/Zend/Cache/Pattern/ObjectCache.php deleted file mode 100755 index 9ef2a2414..000000000 --- a/library/Zend/Cache/Pattern/ObjectCache.php +++ /dev/null @@ -1,284 +0,0 @@ -getObject()) { - throw new Exception\InvalidArgumentException("Missing option 'object'"); - } elseif (!$options->getStorage()) { - throw new Exception\InvalidArgumentException("Missing option 'storage'"); - } - } - - /** - * Call and cache a class method - * - * @param string $method Method name to call - * @param array $args Method arguments - * @return mixed - * @throws Exception\RuntimeException - * @throws \Exception - */ - public function call($method, array $args = array()) - { - $options = $this->getOptions(); - $object = $options->getObject(); - $method = strtolower($method); - - // handle magic methods - switch ($method) { - case '__set': - $property = array_shift($args); - $value = array_shift($args); - - $object->{$property} = $value; - - if (!$options->getObjectCacheMagicProperties() - || property_exists($object, $property) - ) { - // no caching if property isn't magic - // or caching magic properties is disabled - return; - } - - // remove cached __get and __isset - $removeKeys = null; - if (method_exists($object, '__get')) { - $removeKeys[] = $this->generateKey('__get', array($property)); - } - if (method_exists($object, '__isset')) { - $removeKeys[] = $this->generateKey('__isset', array($property)); - } - if ($removeKeys) { - $options->getStorage()->removeItems($removeKeys); - } - return; - - case '__get': - $property = array_shift($args); - - if (!$options->getObjectCacheMagicProperties() - || property_exists($object, $property) - ) { - // no caching if property isn't magic - // or caching magic properties is disabled - return $object->{$property}; - } - - array_unshift($args, $property); - return parent::call(array($object, '__get'), $args); - - case '__isset': - $property = array_shift($args); - - if (!$options->getObjectCacheMagicProperties() - || property_exists($object, $property) - ) { - // no caching if property isn't magic - // or caching magic properties is disabled - return isset($object->{$property}); - } - - return parent::call(array($object, '__isset'), array($property)); - - case '__unset': - $property = array_shift($args); - - unset($object->{$property}); - - if (!$options->getObjectCacheMagicProperties() - || property_exists($object, $property) - ) { - // no caching if property isn't magic - // or caching magic properties is disabled - return; - } - - // remove previous cached __get and __isset calls - $removeKeys = null; - if (method_exists($object, '__get')) { - $removeKeys[] = $this->generateKey('__get', array($property)); - } - if (method_exists($object, '__isset')) { - $removeKeys[] = $this->generateKey('__isset', array($property)); - } - if ($removeKeys) { - $options->getStorage()->removeItems($removeKeys); - } - return; - } - - $cache = $options->getCacheByDefault(); - if ($cache) { - $cache = !in_array($method, $options->getObjectNonCacheMethods()); - } else { - $cache = in_array($method, $options->getObjectCacheMethods()); - } - - if (!$cache) { - if ($args) { - return call_user_func_array(array($object, $method), $args); - } - return $object->{$method}(); - } - - return parent::call(array($object, $method), $args); - } - - /** - * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part. - * - * @param string $method The method - * @param array $args Callback arguments - * @return string - * @throws Exception\RuntimeException - */ - public function generateKey($method, array $args = array()) - { - return $this->generateCallbackKey( - array($this->getOptions()->getObject(), $method), - $args - ); - } - - /** - * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part. - * - * @param callable $callback A valid callback - * @param array $args Callback arguments - * @return string - * @throws Exception\RuntimeException - */ - protected function generateCallbackKey($callback, array $args = array()) - { - $callbackKey = md5($this->getOptions()->getObjectKey() . '::' . strtolower($callback[1])); - $argumentKey = $this->generateArgumentsKey($args); - return $callbackKey . $argumentKey; - } - - /** - * Class method call handler - * - * @param string $method Method name to call - * @param array $args Method arguments - * @return mixed - * @throws Exception\RuntimeException - * @throws \Exception - */ - public function __call($method, array $args) - { - return $this->call($method, $args); - } - - /** - * Writing data to properties. - * - * NOTE: - * Magic properties will be cached too if the option cacheMagicProperties - * is enabled and the property doesn't exist in real. If so it calls __set - * and removes cached data of previous __get and __isset calls. - * - * @param string $name - * @param mixed $value - * @return void - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members - */ - public function __set($name, $value) - { - return $this->call('__set', array($name, $value)); - } - - /** - * Reading data from properties. - * - * NOTE: - * Magic properties will be cached too if the option cacheMagicProperties - * is enabled and the property doesn't exist in real. If so it calls __get. - * - * @param string $name - * @return mixed - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members - */ - public function __get($name) - { - return $this->call('__get', array($name)); - } - - /** - * Checking existing properties. - * - * NOTE: - * Magic properties will be cached too if the option cacheMagicProperties - * is enabled and the property doesn't exist in real. If so it calls __get. - * - * @param string $name - * @return bool - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members - */ - public function __isset($name) - { - return $this->call('__isset', array($name)); - } - - /** - * Unseting a property. - * - * NOTE: - * Magic properties will be cached too if the option cacheMagicProperties - * is enabled and the property doesn't exist in real. If so it removes - * previous cached __isset and __get calls. - * - * @param string $name - * @return void - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members - */ - public function __unset($name) - { - return $this->call('__unset', array($name)); - } - - /** - * Handle casting to string - * - * @return string - * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.tostring - */ - public function __toString() - { - return $this->call('__toString'); - } - - /** - * Handle invoke calls - * - * @return mixed - * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.invoke - */ - public function __invoke() - { - return $this->call('__invoke', func_get_args()); - } -} diff --git a/library/Zend/Cache/Pattern/OutputCache.php b/library/Zend/Cache/Pattern/OutputCache.php deleted file mode 100755 index 549e17122..000000000 --- a/library/Zend/Cache/Pattern/OutputCache.php +++ /dev/null @@ -1,89 +0,0 @@ -getStorage()) { - throw new Exception\InvalidArgumentException("Missing option 'storage'"); - } - - return $this; - } - - /** - * if there is a cached item with the given key display it's data and return true - * else start buffering output until end() is called or the script ends. - * - * @param string $key Key - * @throws Exception\MissingKeyException if key is missing - * @return bool - */ - public function start($key) - { - if (($key = (string) $key) === '') { - throw new Exception\MissingKeyException('Missing key to read/write output from cache'); - } - - $success = null; - $data = $this->getOptions()->getStorage()->getItem($key, $success); - if ($success) { - echo $data; - return true; - } - - ob_start(); - ob_implicit_flush(false); - $this->keyStack[] = $key; - return false; - } - - /** - * Stops buffering output, write buffered data to cache using the given key on start() - * and displays the buffer. - * - * @throws Exception\RuntimeException if output cache not started or buffering not active - * @return bool TRUE on success, FALSE on failure writing to cache - */ - public function end() - { - $key = array_pop($this->keyStack); - if ($key === null) { - throw new Exception\RuntimeException('Output cache not started'); - } - - $output = ob_get_flush(); - if ($output === false) { - throw new Exception\RuntimeException('Output buffering not active'); - } - - return $this->getOptions()->getStorage()->setItem($key, $output); - } -} diff --git a/library/Zend/Cache/Pattern/PatternInterface.php b/library/Zend/Cache/Pattern/PatternInterface.php deleted file mode 100755 index a79bf5188..000000000 --- a/library/Zend/Cache/Pattern/PatternInterface.php +++ /dev/null @@ -1,28 +0,0 @@ -filePermission = false; - $this->dirPermission = false; - } - - parent::__construct($options); - } - - /** - * Set flag indicating whether or not to cache by default - * - * Used by: - * - ClassCache - * - ObjectCache - * - * @param bool $cacheByDefault - * @return PatternOptions - */ - public function setCacheByDefault($cacheByDefault) - { - $this->cacheByDefault = $cacheByDefault; - return $this; - } - - /** - * Do we cache by default? - * - * Used by: - * - ClassCache - * - ObjectCache - * - * @return bool - */ - public function getCacheByDefault() - { - return $this->cacheByDefault; - } - - /** - * Set whether or not to cache output - * - * Used by: - * - CallbackCache - * - ClassCache - * - ObjectCache - * - * @param bool $cacheOutput - * @return PatternOptions - */ - public function setCacheOutput($cacheOutput) - { - $this->cacheOutput = (bool) $cacheOutput; - return $this; - } - - /** - * Will we cache output? - * - * Used by: - * - CallbackCache - * - ClassCache - * - ObjectCache - * - * @return bool - */ - public function getCacheOutput() - { - return $this->cacheOutput; - } - - /** - * Set class name - * - * Used by: - * - ClassCache - * - * @param string $class - * @throws Exception\InvalidArgumentException - * @return PatternOptions - */ - public function setClass($class) - { - if (!is_string($class)) { - throw new Exception\InvalidArgumentException('Invalid classname provided; must be a string'); - } - $this->class = $class; - return $this; - } - - /** - * Get class name - * - * Used by: - * - ClassCache - * - * @return null|string - */ - public function getClass() - { - return $this->class; - } - - /** - * Set list of method return values to cache - * - * Used by: - * - ClassCache - * - * @param array $classCacheMethods - * @return PatternOptions - */ - public function setClassCacheMethods(array $classCacheMethods) - { - $this->classCacheMethods = $this->recursiveStrtolower($classCacheMethods); - return $this; - } - - /** - * Get list of methods from which to cache return values - * - * Used by: - * - ClassCache - * - * @return array - */ - public function getClassCacheMethods() - { - return $this->classCacheMethods; - } - - /** - * Set list of method return values NOT to cache - * - * Used by: - * - ClassCache - * - * @param array $classNonCacheMethods - * @return PatternOptions - */ - public function setClassNonCacheMethods(array $classNonCacheMethods) - { - $this->classNonCacheMethods = $this->recursiveStrtolower($classNonCacheMethods); - return $this; - } - - /** - * Get list of methods from which NOT to cache return values - * - * Used by: - * - ClassCache - * - * @return array - */ - public function getClassNonCacheMethods() - { - return $this->classNonCacheMethods; - } - - /** - * Set directory permission - * - * @param false|int $dirPermission - * @throws Exception\InvalidArgumentException - * @return PatternOptions - */ - public function setDirPermission($dirPermission) - { - if ($dirPermission !== false) { - if (is_string($dirPermission)) { - $dirPermission = octdec($dirPermission); - } else { - $dirPermission = (int) $dirPermission; - } - - // validate - if (($dirPermission & 0700) != 0700) { - throw new Exception\InvalidArgumentException( - 'Invalid directory permission: need permission to execute, read and write by owner' - ); - } - } - - $this->dirPermission = $dirPermission; - return $this; - } - - /** - * Gets directory permission - * - * @return false|int - */ - public function getDirPermission() - { - return $this->dirPermission; - } - - /** - * Set umask - * - * Used by: - * - CaptureCache - * - * @param false|int $umask - * @throws Exception\InvalidArgumentException - * @return PatternOptions - */ - public function setUmask($umask) - { - if ($umask !== false) { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int) $umask; - } - - // validate - if ($umask & 0700) { - throw new Exception\InvalidArgumentException( - 'Invalid umask: need permission to execute, read and write by owner' - ); - } - - // normalize - $umask = $umask & 0777; - } - - $this->umask = $umask; - return $this; - } - - /** - * Get umask - * - * Used by: - * - CaptureCache - * - * @return false|int - */ - public function getUmask() - { - return $this->umask; - } - - /** - * Set whether or not file locking should be used - * - * Used by: - * - CaptureCache - * - * @param bool $fileLocking - * @return PatternOptions - */ - public function setFileLocking($fileLocking) - { - $this->fileLocking = (bool) $fileLocking; - return $this; - } - - /** - * Is file locking enabled? - * - * Used by: - * - CaptureCache - * - * @return bool - */ - public function getFileLocking() - { - return $this->fileLocking; - } - - /** - * Set file permission - * - * @param false|int $filePermission - * @throws Exception\InvalidArgumentException - * @return PatternOptions - */ - public function setFilePermission($filePermission) - { - if ($filePermission !== false) { - if (is_string($filePermission)) { - $filePermission = octdec($filePermission); - } else { - $filePermission = (int) $filePermission; - } - - // validate - if (($filePermission & 0600) != 0600) { - throw new Exception\InvalidArgumentException( - 'Invalid file permission: need permission to read and write by owner' - ); - } elseif ($filePermission & 0111) { - throw new Exception\InvalidArgumentException( - "Invalid file permission: Files shoudn't be executable" - ); - } - } - - $this->filePermission = $filePermission; - return $this; - } - - /** - * Gets file permission - * - * @return false|int - */ - public function getFilePermission() - { - return $this->filePermission; - } - - /** - * Set value for index filename - * - * @param string $indexFilename - * @return PatternOptions - */ - public function setIndexFilename($indexFilename) - { - $this->indexFilename = (string) $indexFilename; - return $this; - } - - /** - * Get value for index filename - * - * @return string - */ - public function getIndexFilename() - { - return $this->indexFilename; - } - - /** - * Set object to cache - * - * @param mixed $object - * @throws Exception\InvalidArgumentException - * @return PatternOptions - */ - public function setObject($object) - { - if (!is_object($object)) { - throw new Exception\InvalidArgumentException( - sprintf('%s expects an object; received "%s"', __METHOD__, gettype($object)) - ); - } - $this->object = $object; - return $this; - } - - /** - * Get object to cache - * - * @return null|object - */ - public function getObject() - { - return $this->object; - } - - /** - * Set flag indicating whether or not to cache magic properties - * - * Used by: - * - ObjectCache - * - * @param bool $objectCacheMagicProperties - * @return PatternOptions - */ - public function setObjectCacheMagicProperties($objectCacheMagicProperties) - { - $this->objectCacheMagicProperties = (bool) $objectCacheMagicProperties; - return $this; - } - - /** - * Should we cache magic properties? - * - * Used by: - * - ObjectCache - * - * @return bool - */ - public function getObjectCacheMagicProperties() - { - return $this->objectCacheMagicProperties; - } - - /** - * Set list of object methods for which to cache return values - * - * @param array $objectCacheMethods - * @return PatternOptions - * @throws Exception\InvalidArgumentException - */ - public function setObjectCacheMethods(array $objectCacheMethods) - { - $this->objectCacheMethods = $this->normalizeObjectMethods($objectCacheMethods); - return $this; - } - - /** - * Get list of object methods for which to cache return values - * - * @return array - */ - public function getObjectCacheMethods() - { - return $this->objectCacheMethods; - } - - /** - * Set the object key part. - * - * Used to generate a callback key in order to speed up key generation. - * - * Used by: - * - ObjectCache - * - * @param mixed $objectKey - * @return PatternOptions - */ - public function setObjectKey($objectKey) - { - if ($objectKey !== null) { - $this->objectKey = (string) $objectKey; - } else { - $this->objectKey = null; - } - return $this; - } - - /** - * Get object key - * - * Used by: - * - ObjectCache - * - * @return string - */ - public function getObjectKey() - { - if (!$this->objectKey) { - return get_class($this->getObject()); - } - return $this->objectKey; - } - - /** - * Set list of object methods for which NOT to cache return values - * - * @param array $objectNonCacheMethods - * @return PatternOptions - * @throws Exception\InvalidArgumentException - */ - public function setObjectNonCacheMethods(array $objectNonCacheMethods) - { - $this->objectNonCacheMethods = $this->normalizeObjectMethods($objectNonCacheMethods); - return $this; - } - - /** - * Get list of object methods for which NOT to cache return values - * - * @return array - */ - public function getObjectNonCacheMethods() - { - return $this->objectNonCacheMethods; - } - - /** - * Set location of public directory - * - * Used by: - * - CaptureCache - * - * @param string $publicDir - * @throws Exception\InvalidArgumentException - * @return PatternOptions - */ - public function setPublicDir($publicDir) - { - $publicDir = (string) $publicDir; - - if (!is_dir($publicDir)) { - throw new Exception\InvalidArgumentException( - "Public directory '{$publicDir}' not found or not a directory" - ); - } elseif (!is_writable($publicDir)) { - throw new Exception\InvalidArgumentException( - "Public directory '{$publicDir}' not writable" - ); - } elseif (!is_readable($publicDir)) { - throw new Exception\InvalidArgumentException( - "Public directory '{$publicDir}' not readable" - ); - } - - $this->publicDir = rtrim(realpath($publicDir), DIRECTORY_SEPARATOR); - return $this; - } - - /** - * Get location of public directory - * - * Used by: - * - CaptureCache - * - * @return null|string - */ - public function getPublicDir() - { - return $this->publicDir; - } - - /** - * Set storage adapter - * - * Required for the following Pattern classes: - * - CallbackCache - * - ClassCache - * - ObjectCache - * - OutputCache - * - * @param string|array|Storage $storage - * @return PatternOptions - */ - public function setStorage($storage) - { - $this->storage = $this->storageFactory($storage); - return $this; - } - - /** - * Get storage adapter - * - * Used by: - * - CallbackCache - * - ClassCache - * - ObjectCache - * - OutputCache - * - * @return null|Storage - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Recursively apply strtolower on all values of an array, and return as a - * list of unique values - * - * @param array $array - * @return array - */ - protected function recursiveStrtolower(array $array) - { - return array_values(array_unique(array_map('strtolower', $array))); - } - - /** - * Normalize object methods - * - * Recursively casts values to lowercase, then determines if any are in a - * list of methods not handled, raising an exception if so. - * - * @param array $methods - * @return array - * @throws Exception\InvalidArgumentException - */ - protected function normalizeObjectMethods(array $methods) - { - $methods = $this->recursiveStrtolower($methods); - $intersect = array_intersect(array('__set', '__get', '__unset', '__isset'), $methods); - if (!empty($intersect)) { - throw new Exception\InvalidArgumentException( - "Magic properties are handled by option 'cache_magic_properties'" - ); - } - return $methods; - } - - /** - * Create a storage object from a given specification - * - * @param array|string|Storage $storage - * @throws Exception\InvalidArgumentException - * @return Storage - */ - protected function storageFactory($storage) - { - if (is_array($storage)) { - $storage = StorageFactory::factory($storage); - } elseif (is_string($storage)) { - $storage = StorageFactory::adapterFactory($storage); - } elseif (!($storage instanceof Storage)) { - throw new Exception\InvalidArgumentException( - 'The storage must be an instanceof Zend\Cache\Storage\StorageInterface ' - . 'or an array passed to Zend\Cache\Storage::factory ' - . 'or simply the name of the storage adapter' - ); - } - - return $storage; - } -} diff --git a/library/Zend/Cache/PatternFactory.php b/library/Zend/Cache/PatternFactory.php deleted file mode 100755 index dceed0032..000000000 --- a/library/Zend/Cache/PatternFactory.php +++ /dev/null @@ -1,92 +0,0 @@ -setOptions($options); - return $patternName; - } - - $pattern = static::getPluginManager()->get($patternName); - $pattern->setOptions($options); - return $pattern; - } - - /** - * Get the pattern plugin manager - * - * @return PatternPluginManager - */ - public static function getPluginManager() - { - if (static::$plugins === null) { - static::$plugins = new PatternPluginManager(); - } - - return static::$plugins; - } - - /** - * Set the pattern plugin manager - * - * @param PatternPluginManager $plugins - * @return void - */ - public static function setPluginManager(PatternPluginManager $plugins) - { - static::$plugins = $plugins; - } - - /** - * Reset pattern plugin manager to default - * - * @return void - */ - public static function resetPluginManager() - { - static::$plugins = null; - } -} diff --git a/library/Zend/Cache/PatternPluginManager.php b/library/Zend/Cache/PatternPluginManager.php deleted file mode 100755 index 7d5d0e1a6..000000000 --- a/library/Zend/Cache/PatternPluginManager.php +++ /dev/null @@ -1,66 +0,0 @@ - 'Zend\Cache\Pattern\CallbackCache', - 'capture' => 'Zend\Cache\Pattern\CaptureCache', - 'class' => 'Zend\Cache\Pattern\ClassCache', - 'object' => 'Zend\Cache\Pattern\ObjectCache', - 'output' => 'Zend\Cache\Pattern\OutputCache', - 'page' => 'Zend\Cache\Pattern\PageCache', - ); - - /** - * Don't share by default - * - * @var array - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the pattern adapter loaded is an instance of Pattern\PatternInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\RuntimeException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Pattern\PatternInterface) { - // we're okay - return; - } - - throw new Exception\RuntimeException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Pattern\PatternInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Cache/README.md b/library/Zend/Cache/README.md deleted file mode 100755 index 62aa9e0e0..000000000 --- a/library/Zend/Cache/README.md +++ /dev/null @@ -1,14 +0,0 @@ -Cache Component from ZF2 -======================== - -This is the Cache component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. diff --git a/library/Zend/Cache/Service/StorageCacheAbstractServiceFactory.php b/library/Zend/Cache/Service/StorageCacheAbstractServiceFactory.php deleted file mode 100755 index 66eb6505e..000000000 --- a/library/Zend/Cache/Service/StorageCacheAbstractServiceFactory.php +++ /dev/null @@ -1,88 +0,0 @@ -getConfig($services); - if (empty($config)) { - return false; - } - - return (isset($config[$requestedName]) && is_array($config[$requestedName])); - } - - /** - * @param ServiceLocatorInterface $services - * @param string $name - * @param string $requestedName - * @return \Zend\Cache\Storage\StorageInterface - */ - public function createServiceWithName(ServiceLocatorInterface $services, $name, $requestedName) - { - $config = $this->getConfig($services); - $config = $config[$requestedName]; - return StorageFactory::factory($config); - } - - /** - * Retrieve cache configuration, if any - * - * @param ServiceLocatorInterface $services - * @return array - */ - protected function getConfig(ServiceLocatorInterface $services) - { - if ($this->config !== null) { - return $this->config; - } - - if (!$services->has('Config')) { - $this->config = array(); - return $this->config; - } - - $config = $services->get('Config'); - if (!isset($config[$this->configKey])) { - $this->config = array(); - return $this->config; - } - - $this->config = $config[$this->configKey]; - return $this->config; - } -} diff --git a/library/Zend/Cache/Service/StorageCacheFactory.php b/library/Zend/Cache/Service/StorageCacheFactory.php deleted file mode 100755 index f2c204993..000000000 --- a/library/Zend/Cache/Service/StorageCacheFactory.php +++ /dev/null @@ -1,30 +0,0 @@ -get('Config'); - $cacheConfig = isset($config['cache']) ? $config['cache'] : array(); - $cache = StorageFactory::factory($cacheConfig); - - return $cache; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/AbstractAdapter.php b/library/Zend/Cache/Storage/Adapter/AbstractAdapter.php deleted file mode 100755 index 71edf763e..000000000 --- a/library/Zend/Cache/Storage/Adapter/AbstractAdapter.php +++ /dev/null @@ -1,1580 +0,0 @@ -setOptions($options); - } - } - - /** - * Destructor - * - * detach all registered plugins to free - * event handles of event manager - * - * @return void - */ - public function __destruct() - { - foreach ($this->getPluginRegistry() as $plugin) { - $this->removePlugin($plugin); - } - - if ($this->eventHandles) { - $events = $this->getEventManager(); - foreach ($this->eventHandles as $handle) { - $events->detach($handle); - } - } - } - - /* configuration */ - - /** - * Set options. - * - * @param array|Traversable|AdapterOptions $options - * @return AbstractAdapter - * @see getOptions() - */ - public function setOptions($options) - { - if ($this->options !== $options) { - if (!$options instanceof AdapterOptions) { - $options = new AdapterOptions($options); - } - - if ($this->options) { - $this->options->setAdapter(null); - } - $options->setAdapter($this); - $this->options = $options; - - $event = new Event('option', $this, new ArrayObject($options->toArray())); - $this->getEventManager()->trigger($event); - } - return $this; - } - - /** - * Get options. - * - * @return AdapterOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new AdapterOptions()); - } - return $this->options; - } - - /** - * Enable/Disable caching. - * - * Alias of setWritable and setReadable. - * - * @see setWritable() - * @see setReadable() - * @param bool $flag - * @return AbstractAdapter - */ - public function setCaching($flag) - { - $flag = (bool) $flag; - $options = $this->getOptions(); - $options->setWritable($flag); - $options->setReadable($flag); - return $this; - } - - /** - * Get caching enabled. - * - * Alias of getWritable and getReadable. - * - * @see getWritable() - * @see getReadable() - * @return bool - */ - public function getCaching() - { - $options = $this->getOptions(); - return ($options->getWritable() && $options->getReadable()); - } - - /* Event/Plugin handling */ - - /** - * Get the event manager - * - * @return EventManagerInterface - */ - public function getEventManager() - { - if ($this->events === null) { - $this->events = new EventManager(array(__CLASS__, get_class($this))); - } - return $this->events; - } - - /** - * Trigger a pre event and return the event response collection - * - * @param string $eventName - * @param ArrayObject $args - * @return \Zend\EventManager\ResponseCollection All handler return values - */ - protected function triggerPre($eventName, ArrayObject $args) - { - return $this->getEventManager()->trigger(new Event($eventName . '.pre', $this, $args)); - } - - /** - * Triggers the PostEvent and return the result value. - * - * @param string $eventName - * @param ArrayObject $args - * @param mixed $result - * @return mixed - */ - protected function triggerPost($eventName, ArrayObject $args, & $result) - { - $postEvent = new PostEvent($eventName . '.post', $this, $args, $result); - $eventRs = $this->getEventManager()->trigger($postEvent); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - return $postEvent->getResult(); - } - - /** - * Trigger an exception event - * - * If the ExceptionEvent has the flag "throwException" enabled throw the - * exception after trigger else return the result. - * - * @param string $eventName - * @param ArrayObject $args - * @param mixed $result - * @param \Exception $exception - * @throws Exception\ExceptionInterface - * @return mixed - */ - protected function triggerException($eventName, ArrayObject $args, & $result, \Exception $exception) - { - $exceptionEvent = new ExceptionEvent($eventName . '.exception', $this, $args, $result, $exception); - $eventRs = $this->getEventManager()->trigger($exceptionEvent); - - if ($exceptionEvent->getThrowException()) { - throw $exceptionEvent->getException(); - } - - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - return $exceptionEvent->getResult(); - } - - /** - * Check if a plugin is registered - * - * @param Plugin\PluginInterface $plugin - * @return bool - */ - public function hasPlugin(Plugin\PluginInterface $plugin) - { - $registry = $this->getPluginRegistry(); - return $registry->contains($plugin); - } - - /** - * Register a plugin - * - * @param Plugin\PluginInterface $plugin - * @param int $priority - * @return AbstractAdapter Fluent interface - * @throws Exception\LogicException - */ - public function addPlugin(Plugin\PluginInterface $plugin, $priority = 1) - { - $registry = $this->getPluginRegistry(); - if ($registry->contains($plugin)) { - throw new Exception\LogicException(sprintf( - 'Plugin of type "%s" already registered', - get_class($plugin) - )); - } - - $plugin->attach($this->getEventManager(), $priority); - $registry->attach($plugin); - - return $this; - } - - /** - * Unregister an already registered plugin - * - * @param Plugin\PluginInterface $plugin - * @return AbstractAdapter Fluent interface - * @throws Exception\LogicException - */ - public function removePlugin(Plugin\PluginInterface $plugin) - { - $registry = $this->getPluginRegistry(); - if ($registry->contains($plugin)) { - $plugin->detach($this->getEventManager()); - $registry->detach($plugin); - } - return $this; - } - - /** - * Return registry of plugins - * - * @return SplObjectStorage - */ - public function getPluginRegistry() - { - if (!$this->pluginRegistry instanceof SplObjectStorage) { - $this->pluginRegistry = new SplObjectStorage(); - } - return $this->pluginRegistry; - } - - /* reading */ - - /** - * Get an item. - * - * @param string $key - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) - */ - public function getItem($key, & $success = null, & $casToken = null) - { - if (!$this->getOptions()->getReadable()) { - $success = false; - return null; - } - - $this->normalizeKey($key); - - $argn = func_num_args(); - $args = array( - 'key' => & $key, - ); - if ($argn > 1) { - $args['success'] = & $success; - } - if ($argn > 2) { - $args['casToken'] = & $casToken; - } - $args = new ArrayObject($args); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($args->offsetExists('success') && $args->offsetExists('casToken')) { - $result = $this->internalGetItem($args['key'], $args['success'], $args['casToken']); - } elseif ($args->offsetExists('success')) { - $result = $this->internalGetItem($args['key'], $args['success']); - } else { - $result = $this->internalGetItem($args['key']); - } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - abstract protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null); - - /** - * Get multiple items. - * - * @param array $keys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) - */ - public function getItems(array $keys) - { - if (!$this->getOptions()->getReadable()) { - return array(); - } - - $this->normalizeKeys($keys); - $args = new ArrayObject(array( - 'keys' => & $keys, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalGetItems($args['keys']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array(); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $success = null; - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - $value = $this->internalGetItem($normalizedKey, $success); - if ($success) { - $result[$normalizedKey] = $value; - } - } - - return $result; - } - - /** - * Test if an item exists. - * - * @param string $key - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers hasItem.pre(PreEvent) - * @triggers hasItem.post(PostEvent) - * @triggers hasItem.exception(ExceptionEvent) - */ - public function hasItem($key) - { - if (!$this->getOptions()->getReadable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalHasItem($args['key']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $success = null; - $this->internalGetItem($normalizedKey, $success); - return $success; - } - - /** - * Test multiple items. - * - * @param array $keys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - * - * @triggers hasItems.pre(PreEvent) - * @triggers hasItems.post(PostEvent) - * @triggers hasItems.exception(ExceptionEvent) - */ - public function hasItems(array $keys) - { - if (!$this->getOptions()->getReadable()) { - return array(); - } - - $this->normalizeKeys($keys); - $args = new ArrayObject(array( - 'keys' => & $keys, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalHasItems($args['keys']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array(); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - */ - protected function internalHasItems(array & $normalizedKeys) - { - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if ($this->internalHasItem($normalizedKey)) { - $result[] = $normalizedKey; - } - } - return $result; - } - - /** - * Get metadata of an item. - * - * @param string $key - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - * - * @triggers getMetadata.pre(PreEvent) - * @triggers getMetadata.post(PostEvent) - * @triggers getMetadata.exception(ExceptionEvent) - */ - public function getMetadata($key) - { - if (!$this->getOptions()->getReadable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalGetMetadata($args['key']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to get metadata of an item. - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadata(& $normalizedKey) - { - if (!$this->internalHasItem($normalizedKey)) { - return false; - } - - return array(); - } - - /** - * Get multiple metadata - * - * @param array $keys - * @return array Associative array of keys and metadata - * @throws Exception\ExceptionInterface - * - * @triggers getMetadatas.pre(PreEvent) - * @triggers getMetadatas.post(PostEvent) - * @triggers getMetadatas.exception(ExceptionEvent) - */ - public function getMetadatas(array $keys) - { - if (!$this->getOptions()->getReadable()) { - return array(); - } - - $this->normalizeKeys($keys); - $args = new ArrayObject(array( - 'keys' => & $keys, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalGetMetadatas($args['keys']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array(); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to get multiple metadata - * - * @param array $normalizedKeys - * @return array Associative array of keys and metadata - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadatas(array & $normalizedKeys) - { - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - $metadata = $this->internalGetMetadata($normalizedKey); - if ($metadata !== false) { - $result[$normalizedKey] = $metadata; - } - } - return $result; - } - - /* writing */ - - /** - * Store an item. - * - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) - */ - public function setItem($key, $value) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalSetItem($args['key'], $args['value']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - abstract protected function internalSetItem(& $normalizedKey, & $value); - - /** - * Store multiple items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - * - * @triggers setItems.pre(PreEvent) - * @triggers setItems.post(PostEvent) - * @triggers setItems.exception(ExceptionEvent) - */ - public function setItems(array $keyValuePairs) - { - if (!$this->getOptions()->getWritable()) { - return array_keys($keyValuePairs); - } - - $this->normalizeKeyValuePairs($keyValuePairs); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalSetItems($args['keyValuePairs']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array_keys($keyValuePairs); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $failedKeys = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!$this->internalSetItem($normalizedKey, $value)) { - $failedKeys[] = $normalizedKey; - } - } - return $failedKeys; - } - - /** - * Add an item. - * - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers addItem.pre(PreEvent) - * @triggers addItem.post(PostEvent) - * @triggers addItem.exception(ExceptionEvent) - */ - public function addItem($key, $value) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalAddItem($args['key'], $args['value']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - if ($this->internalHasItem($normalizedKey)) { - return false; - } - return $this->internalSetItem($normalizedKey, $value); - } - - /** - * Add multiple items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - * - * @triggers addItems.pre(PreEvent) - * @triggers addItems.post(PostEvent) - * @triggers addItems.exception(ExceptionEvent) - */ - public function addItems(array $keyValuePairs) - { - if (!$this->getOptions()->getWritable()) { - return array_keys($keyValuePairs); - } - - $this->normalizeKeyValuePairs($keyValuePairs); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalAddItems($args['keyValuePairs']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array_keys($keyValuePairs); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to add multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalAddItems(array & $normalizedKeyValuePairs) - { - $result = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!$this->internalAddItem($normalizedKey, $value)) { - $result[] = $normalizedKey; - } - } - return $result; - } - - /** - * Replace an existing item. - * - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers replaceItem.pre(PreEvent) - * @triggers replaceItem.post(PostEvent) - * @triggers replaceItem.exception(ExceptionEvent) - */ - public function replaceItem($key, $value) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalReplaceItem($args['key'], $args['value']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - if (!$this->internalhasItem($normalizedKey)) { - return false; - } - - return $this->internalSetItem($normalizedKey, $value); - } - - /** - * Replace multiple existing items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - * - * @triggers replaceItems.pre(PreEvent) - * @triggers replaceItems.post(PostEvent) - * @triggers replaceItems.exception(ExceptionEvent) - */ - public function replaceItems(array $keyValuePairs) - { - if (!$this->getOptions()->getWritable()) { - return array_keys($keyValuePairs); - } - - $this->normalizeKeyValuePairs($keyValuePairs); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalReplaceItems($args['keyValuePairs']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array_keys($keyValuePairs); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to replace multiple existing items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItems(array & $normalizedKeyValuePairs) - { - $result = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!$this->internalReplaceItem($normalizedKey, $value)) { - $result[] = $normalizedKey; - } - } - return $result; - } - - /** - * Set an item only if token matches - * - * It uses the token received from getItem() to check if the item has - * changed before overwriting it. - * - * @param mixed $token - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * @see getItem() - * @see setItem() - */ - public function checkAndSetItem($token, $key, $value) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'token' => & $token, - 'key' => & $key, - 'value' => & $value, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalCheckAndSetItem($args['token'], $args['key'], $args['value']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to set an item only if token matches - * - * @param mixed $token - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * @see getItem() - * @see setItem() - */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) - { - $oldValue = $this->internalGetItem($normalizedKey); - if ($oldValue !== $token) { - return false; - } - - return $this->internalSetItem($normalizedKey, $value); - } - - /** - * Reset lifetime of an item - * - * @param string $key - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers touchItem.pre(PreEvent) - * @triggers touchItem.post(PostEvent) - * @triggers touchItem.exception(ExceptionEvent) - */ - public function touchItem($key) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalTouchItem($args['key']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to reset lifetime of an item - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalTouchItem(& $normalizedKey) - { - $success = null; - $value = $this->internalGetItem($normalizedKey, $success); - if (!$success) { - return false; - } - - return $this->internalReplaceItem($normalizedKey, $value); - } - - /** - * Reset lifetime of multiple items. - * - * @param array $keys - * @return array Array of not updated keys - * @throws Exception\ExceptionInterface - * - * @triggers touchItems.pre(PreEvent) - * @triggers touchItems.post(PostEvent) - * @triggers touchItems.exception(ExceptionEvent) - */ - public function touchItems(array $keys) - { - if (!$this->getOptions()->getWritable()) { - return $keys; - } - - $this->normalizeKeys($keys); - $args = new ArrayObject(array( - 'keys' => & $keys, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalTouchItems($args['keys']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $keys, $e); - } - } - - /** - * Internal method to reset lifetime of multiple items. - * - * @param array $normalizedKeys - * @return array Array of not updated keys - * @throws Exception\ExceptionInterface - */ - protected function internalTouchItems(array & $normalizedKeys) - { - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if (!$this->internalTouchItem($normalizedKey)) { - $result[] = $normalizedKey; - } - } - return $result; - } - - /** - * Remove an item. - * - * @param string $key - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) - */ - public function removeItem($key) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalRemoveItem($args['key']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - abstract protected function internalRemoveItem(& $normalizedKey); - - /** - * Remove multiple items. - * - * @param array $keys - * @return array Array of not removed keys - * @throws Exception\ExceptionInterface - * - * @triggers removeItems.pre(PreEvent) - * @triggers removeItems.post(PostEvent) - * @triggers removeItems.exception(ExceptionEvent) - */ - public function removeItems(array $keys) - { - if (!$this->getOptions()->getWritable()) { - return $keys; - } - - $this->normalizeKeys($keys); - $args = new ArrayObject(array( - 'keys' => & $keys, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalRemoveItems($args['keys']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $keys, $e); - } - } - - /** - * Internal method to remove multiple items. - * - * @param array $normalizedKeys - * @return array Array of not removed keys - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItems(array & $normalizedKeys) - { - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if (!$this->internalRemoveItem($normalizedKey)) { - $result[] = $normalizedKey; - } - } - return $result; - } - - /** - * Increment an item. - * - * @param string $key - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - * - * @triggers incrementItem.pre(PreEvent) - * @triggers incrementItem.post(PostEvent) - * @triggers incrementItem.exception(ExceptionEvent) - */ - public function incrementItem($key, $value) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalIncrementItem($args['key'], $args['value']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $success = null; - $value = (int) $value; - $get = (int) $this->internalGetItem($normalizedKey, $success); - $newValue = $get + $value; - - if ($success) { - $this->internalReplaceItem($normalizedKey, $newValue); - } else { - $this->internalAddItem($normalizedKey, $newValue); - } - - return $newValue; - } - - /** - * Increment multiple items. - * - * @param array $keyValuePairs - * @return array Associative array of keys and new values - * @throws Exception\ExceptionInterface - * - * @triggers incrementItems.pre(PreEvent) - * @triggers incrementItems.post(PostEvent) - * @triggers incrementItems.exception(ExceptionEvent) - */ - public function incrementItems(array $keyValuePairs) - { - if (!$this->getOptions()->getWritable()) { - return array(); - } - - $this->normalizeKeyValuePairs($keyValuePairs); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalIncrementItems($args['keyValuePairs']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array(); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to increment multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Associative array of keys and new values - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItems(array & $normalizedKeyValuePairs) - { - $result = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $newValue = $this->internalIncrementItem($normalizedKey, $value); - if ($newValue !== false) { - $result[$normalizedKey] = $newValue; - } - } - return $result; - } - - /** - * Decrement an item. - * - * @param string $key - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - * - * @triggers decrementItem.pre(PreEvent) - * @triggers decrementItem.post(PostEvent) - * @triggers decrementItem.exception(ExceptionEvent) - */ - public function decrementItem($key, $value) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalDecrementItem($args['key'], $args['value']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $success = null; - $value = (int) $value; - $get = (int) $this->internalGetItem($normalizedKey, $success); - $newValue = $get - $value; - - if ($success) { - $this->internalReplaceItem($normalizedKey, $newValue); - } else { - $this->internalAddItem($normalizedKey, $newValue); - } - - return $newValue; - } - - /** - * Decrement multiple items. - * - * @param array $keyValuePairs - * @return array Associative array of keys and new values - * @throws Exception\ExceptionInterface - * - * @triggers incrementItems.pre(PreEvent) - * @triggers incrementItems.post(PostEvent) - * @triggers incrementItems.exception(ExceptionEvent) - */ - public function decrementItems(array $keyValuePairs) - { - if (!$this->getOptions()->getWritable()) { - return array(); - } - - $this->normalizeKeyValuePairs($keyValuePairs); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalDecrementItems($args['keyValuePairs']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array(); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to decrement multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Associative array of keys and new values - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItems(array & $normalizedKeyValuePairs) - { - $result = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $newValue = $this->decrementItem($normalizedKey, $value); - if ($newValue !== false) { - $result[$normalizedKey] = $newValue; - } - } - return $result; - } - - /* status */ - - /** - * Get capabilities of this adapter - * - * @return Capabilities - * @triggers getCapabilities.pre(PreEvent) - * @triggers getCapabilities.post(PostEvent) - * @triggers getCapabilities.exception(ExceptionEvent) - */ - public function getCapabilities() - { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalGetCapabilities(); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities($this, $this->capabilityMarker); - } - return $this->capabilities; - } - - /* internal */ - - /** - * Validates and normalizes a key - * - * @param string $key - * @return void - * @throws Exception\InvalidArgumentException On an invalid key - */ - protected function normalizeKey(& $key) - { - $key = (string) $key; - - if ($key === '') { - throw new Exception\InvalidArgumentException( - "An empty key isn't allowed" - ); - } elseif (($p = $this->getOptions()->getKeyPattern()) && !preg_match($p, $key)) { - throw new Exception\InvalidArgumentException( - "The key '{$key}' doesn't match against pattern '{$p}'" - ); - } - } - - /** - * Validates and normalizes multiple keys - * - * @param array $keys - * @return void - * @throws Exception\InvalidArgumentException On an invalid key - */ - protected function normalizeKeys(array & $keys) - { - if (!$keys) { - throw new Exception\InvalidArgumentException( - "An empty list of keys isn't allowed" - ); - } - - array_walk($keys, array($this, 'normalizeKey')); - $keys = array_values(array_unique($keys)); - } - - /** - * Validates and normalizes an array of key-value pairs - * - * @param array $keyValuePairs - * @return void - * @throws Exception\InvalidArgumentException On an invalid key - */ - protected function normalizeKeyValuePairs(array & $keyValuePairs) - { - $normalizedKeyValuePairs = array(); - foreach ($keyValuePairs as $key => $value) { - $this->normalizeKey($key); - $normalizedKeyValuePairs[$key] = $value; - } - $keyValuePairs = $normalizedKeyValuePairs; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/AbstractZendServer.php b/library/Zend/Cache/Storage/Adapter/AbstractZendServer.php deleted file mode 100755 index 22933beb0..000000000 --- a/library/Zend/Cache/Storage/Adapter/AbstractZendServer.php +++ /dev/null @@ -1,273 +0,0 @@ -getOptions()->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . self::NAMESPACE_SEPARATOR; - - $result = $this->zdcFetch($prefix . $normalizedKey); - if ($result === null) { - $success = false; - } else { - $success = true; - $casToken = $result; - } - - return $result; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $namespace = $this->getOptions()->getNamespace(); - if ($namespace === '') { - return $this->zdcFetchMulti($normalizedKeys); - } - - $prefix = $namespace . self::NAMESPACE_SEPARATOR; - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $fetch = $this->zdcFetchMulti($internalKeys); - $result = array(); - $prefixL = strlen($prefix); - foreach ($fetch as $k => & $v) { - $result[substr($k, $prefixL)] = $v; - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $namespace = $this->getOptions()->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . self::NAMESPACE_SEPARATOR; - return ($this->zdcFetch($prefix . $normalizedKey) !== false); - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - */ - protected function internalHasItems(array & $normalizedKeys) - { - $namespace = $this->getOptions()->getNamespace(); - if ($namespace === '') { - return array_keys($this->zdcFetchMulti($normalizedKeys)); - } - - $prefix = $namespace . self::NAMESPACE_SEPARATOR; - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $fetch = $this->zdcFetchMulti($internalKeys); - $result = array(); - $prefixL = strlen($prefix); - foreach ($fetch as $internalKey => & $value) { - $result[] = substr($internalKey, $prefixL); - } - - return $result; - } - - /** - * Get metadata for multiple items - * - * @param array $normalizedKeys - * @return array Associative array of keys and metadata - * - * @triggers getMetadatas.pre(PreEvent) - * @triggers getMetadatas.post(PostEvent) - * @triggers getMetadatas.exception(ExceptionEvent) - */ - protected function internalGetMetadatas(array & $normalizedKeys) - { - $namespace = $this->getOptions()->getNamespace(); - if ($namespace === '') { - $result = $this->zdcFetchMulti($normalizedKeys); - return array_fill_keys(array_keys($result), array()); - } - - $prefix = $namespace . self::NAMESPACE_SEPARATOR; - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $fetch = $this->zdcFetchMulti($internalKeys); - $result = array(); - $prefixL = strlen($prefix); - foreach ($fetch as $internalKey => $value) { - $result[substr($internalKey, $prefixL)] = array(); - } - - return $result; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . self::NAMESPACE_SEPARATOR; - $this->zdcStore($prefix . $normalizedKey, $value, $options->getTtl()); - return true; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $namespace = $this->getOptions()->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . self::NAMESPACE_SEPARATOR; - return $this->zdcDelete($prefix . $normalizedKey); - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this, - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 0, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, - ) - ); - } - - return $this->capabilities; - } - - /* internal wrapper of zend_[disk|shm]_cache_* functions */ - - /** - * Store data into Zend Data Cache (zdc) - * - * @param string $internalKey - * @param mixed $value - * @param int $ttl - * @return void - * @throws Exception\RuntimeException - */ - abstract protected function zdcStore($internalKey, $value, $ttl); - - /** - * Fetch a single item from Zend Data Cache (zdc) - * - * @param string $internalKey - * @return mixed The stored value or FALSE if item wasn't found - * @throws Exception\RuntimeException - */ - abstract protected function zdcFetch($internalKey); - - /** - * Fetch multiple items from Zend Data Cache (zdc) - * - * @param array $internalKeys - * @return array All found items - * @throws Exception\RuntimeException - */ - abstract protected function zdcFetchMulti(array $internalKeys); - - /** - * Delete data from Zend Data Cache (zdc) - * - * @param string $internalKey - * @return bool - * @throws Exception\RuntimeException - */ - abstract protected function zdcDelete($internalKey); -} diff --git a/library/Zend/Cache/Storage/Adapter/AdapterOptions.php b/library/Zend/Cache/Storage/Adapter/AdapterOptions.php deleted file mode 100755 index b3669ffa4..000000000 --- a/library/Zend/Cache/Storage/Adapter/AdapterOptions.php +++ /dev/null @@ -1,264 +0,0 @@ -adapter = $adapter; - return $this; - } - - /** - * Set key pattern - * - * @param null|string $keyPattern - * @throws Exception\InvalidArgumentException - * @return AdapterOptions - */ - public function setKeyPattern($keyPattern) - { - $keyPattern = (string) $keyPattern; - if ($this->keyPattern !== $keyPattern) { - // validate pattern - if ($keyPattern !== '') { - ErrorHandler::start(E_WARNING); - $result = preg_match($keyPattern, ''); - $error = ErrorHandler::stop(); - if ($result === false) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid pattern "%s"%s', - $keyPattern, - ($error ? ': ' . $error->getMessage() : '') - ), 0, $error); - } - } - - $this->triggerOptionEvent('key_pattern', $keyPattern); - $this->keyPattern = $keyPattern; - } - - return $this; - } - - /** - * Get key pattern - * - * @return string - */ - public function getKeyPattern() - { - return $this->keyPattern; - } - - /** - * Set namespace. - * - * @param string $namespace - * @return AdapterOptions - */ - public function setNamespace($namespace) - { - $namespace = (string) $namespace; - if ($this->namespace !== $namespace) { - $this->triggerOptionEvent('namespace', $namespace); - $this->namespace = $namespace; - } - - return $this; - } - - /** - * Get namespace - * - * @return string - */ - public function getNamespace() - { - return $this->namespace; - } - - /** - * Enable/Disable reading data from cache. - * - * @param bool $readable - * @return AbstractAdapter - */ - public function setReadable($readable) - { - $readable = (bool) $readable; - if ($this->readable !== $readable) { - $this->triggerOptionEvent('readable', $readable); - $this->readable = $readable; - } - return $this; - } - - /** - * If reading data from cache enabled. - * - * @return bool - */ - public function getReadable() - { - return $this->readable; - } - - /** - * Set time to live. - * - * @param int|float $ttl - * @return AdapterOptions - */ - public function setTtl($ttl) - { - $this->normalizeTtl($ttl); - if ($this->ttl !== $ttl) { - $this->triggerOptionEvent('ttl', $ttl); - $this->ttl = $ttl; - } - return $this; - } - - /** - * Get time to live. - * - * @return float - */ - public function getTtl() - { - return $this->ttl; - } - - /** - * Enable/Disable writing data to cache. - * - * @param bool $writable - * @return AdapterOptions - */ - public function setWritable($writable) - { - $writable = (bool) $writable; - if ($this->writable !== $writable) { - $this->triggerOptionEvent('writable', $writable); - $this->writable = $writable; - } - return $this; - } - - /** - * If writing data to cache enabled. - * - * @return bool - */ - public function getWritable() - { - return $this->writable; - } - - /** - * Triggers an option event if this options instance has a connection to - * an adapter implements EventsCapableInterface. - * - * @param string $optionName - * @param mixed $optionValue - * @return void - */ - protected function triggerOptionEvent($optionName, $optionValue) - { - if ($this->adapter instanceof EventsCapableInterface) { - $event = new Event('option', $this->adapter, new ArrayObject(array($optionName => $optionValue))); - $this->adapter->getEventManager()->trigger($event); - } - } - - /** - * Validates and normalize a TTL. - * - * @param int|float $ttl - * @throws Exception\InvalidArgumentException - * @return void - */ - protected function normalizeTtl(&$ttl) - { - if (!is_int($ttl)) { - $ttl = (float) $ttl; - - // convert to int if possible - if ($ttl === (float) (int) $ttl) { - $ttl = (int) $ttl; - } - } - - if ($ttl < 0) { - throw new Exception\InvalidArgumentException("TTL can't be negative"); - } - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Apc.php b/library/Zend/Cache/Storage/Adapter/Apc.php deleted file mode 100755 index c2336e96a..000000000 --- a/library/Zend/Cache/Storage/Adapter/Apc.php +++ /dev/null @@ -1,751 +0,0 @@ - 0) { - throw new Exception\ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); - } - - $enabled = ini_get('apc.enabled'); - if (PHP_SAPI == 'cli') { - $enabled = $enabled && (bool) ini_get('apc.enable_cli'); - } - - if (!$enabled) { - throw new Exception\ExtensionNotLoadedException( - "ext/apc is disabled - see 'apc.enabled' and 'apc.enable_cli'" - ); - } - - parent::__construct($options); - } - - /* options */ - - /** - * Set options. - * - * @param array|Traversable|ApcOptions $options - * @return Apc - * @see getOptions() - */ - public function setOptions($options) - { - if (!$options instanceof ApcOptions) { - $options = new ApcOptions($options); - } - - return parent::setOptions($options); - } - - /** - * Get options. - * - * @return ApcOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new ApcOptions()); - } - return $this->options; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - if ($this->totalSpace === null) { - $smaInfo = apc_sma_info(true); - $this->totalSpace = $smaInfo['num_seg'] * $smaInfo['seg_size']; - } - - return $this->totalSpace; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $smaInfo = apc_sma_info(true); - return $smaInfo['avail_mem']; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return ApcIterator - */ - public function getIterator() - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ''; - $pattern = null; - if ($namespace !== '') { - $prefix = $namespace . $options->getNamespaceSeparator(); - $pattern = '/^' . preg_quote($prefix, '/') . '/'; - } - - $baseIt = new BaseApcIterator('user', $pattern, 0, 1, APC_LIST_ACTIVE); - return new ApcIterator($this, $baseIt, $prefix); - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - return apc_clear_cache('user'); - } - - /* ClearByNamespaceInterface */ - - /** - * Remove items by given namespace - * - * @param string $namespace - * @return bool - */ - public function clearByNamespace($namespace) - { - $namespace = (string) $namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } - - $options = $this->getOptions(); - $prefix = $namespace . $options->getNamespaceSeparator(); - $pattern = '/^' . preg_quote($prefix, '/') . '/'; - return apc_delete(new BaseApcIterator('user', $pattern, 0, 1, APC_LIST_ACTIVE)); - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @return bool - */ - public function clearByPrefix($prefix) - { - $prefix = (string) $prefix; - if ($prefix === '') { - throw new Exception\InvalidArgumentException('No prefix given'); - } - - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $nsPrefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $pattern = '/^' . preg_quote($nsPrefix . $prefix, '/') . '/'; - return apc_delete(new BaseApcIterator('user', $pattern, 0, 1, APC_LIST_ACTIVE)); - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $result = apc_fetch($internalKey, $success); - - if (!$success) { - return null; - } - - $casToken = $result; - return $result; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return apc_fetch($normalizedKeys); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $fetch = apc_fetch($internalKeys); - - // remove namespace prefix - $prefixL = strlen($prefix); - $result = array(); - foreach ($fetch as $internalKey => & $value) { - $result[substr($internalKey, $prefixL)] = $value; - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - return apc_exists($prefix . $normalizedKey); - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - */ - protected function internalHasItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - // array_filter with no callback will remove entries equal to FALSE - return array_keys(array_filter(apc_exists($normalizedKeys))); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $exists = apc_exists($internalKeys); - $result = array(); - $prefixL = strlen($prefix); - foreach ($exists as $internalKey => $bool) { - if ($bool === true) { - $result[] = substr($internalKey, $prefixL); - } - } - - return $result; - } - - /** - * Get metadata of an item. - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadata(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - // @see http://pecl.php.net/bugs/bug.php?id=22564 - if (!apc_exists($internalKey)) { - $metadata = false; - } else { - $format = APC_ITER_ALL ^ APC_ITER_VALUE ^ APC_ITER_TYPE ^ APC_ITER_REFCOUNT; - $regexp = '/^' . preg_quote($internalKey, '/') . '$/'; - $it = new BaseApcIterator('user', $regexp, $format, 100, APC_LIST_ACTIVE); - $metadata = $it->current(); - } - - if (!$metadata) { - return false; - } - - $this->normalizeMetadata($metadata); - return $metadata; - } - - /** - * Get metadata of multiple items - * - * @param array $normalizedKeys - * @return array Associative array of keys and metadata - * - * @triggers getMetadatas.pre(PreEvent) - * @triggers getMetadatas.post(PostEvent) - * @triggers getMetadatas.exception(ExceptionEvent) - */ - protected function internalGetMetadatas(array & $normalizedKeys) - { - $keysRegExp = array(); - foreach ($normalizedKeys as $normalizedKey) { - $keysRegExp[] = preg_quote($normalizedKey, '/'); - } - - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - $pattern = '/^(' . implode('|', $keysRegExp) . ')' . '$/'; - } else { - $prefix = $namespace . $options->getNamespaceSeparator(); - $pattern = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $keysRegExp) . ')' . '$/'; - } - $format = APC_ITER_ALL ^ APC_ITER_VALUE ^ APC_ITER_TYPE ^ APC_ITER_REFCOUNT; - $it = new BaseApcIterator('user', $pattern, $format, 100, APC_LIST_ACTIVE); - $result = array(); - $prefixL = strlen($prefix); - foreach ($it as $internalKey => $metadata) { - // @see http://pecl.php.net/bugs/bug.php?id=22564 - if (!apc_exists($internalKey)) { - continue; - } - - $this->normalizeMetadata($metadata); - $result[substr($internalKey, $prefixL)] = & $metadata; - } - - return $result; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - - if (!apc_store($internalKey, $value, $ttl)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "apc_store('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return array_keys(apc_store($normalizedKeyValuePairs, null, $options->getTtl())); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeyValuePairs = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => &$value) { - $internalKey = $prefix . $normalizedKey; - $internalKeyValuePairs[$internalKey] = &$value; - } - - $failedKeys = apc_store($internalKeyValuePairs, null, $options->getTtl()); - $failedKeys = array_keys($failedKeys); - - // remove prefix - $prefixL = strlen($prefix); - foreach ($failedKeys as & $key) { - $key = substr($key, $prefixL); - } - - return $failedKeys; - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - - if (!apc_add($internalKey, $value, $ttl)) { - if (apc_exists($internalKey)) { - return false; - } - - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "apc_add('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to add multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalAddItems(array & $normalizedKeyValuePairs) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return array_keys(apc_add($normalizedKeyValuePairs, null, $options->getTtl())); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeyValuePairs = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $internalKey = $prefix . $normalizedKey; - $internalKeyValuePairs[$internalKey] = $value; - } - - $failedKeys = apc_add($internalKeyValuePairs, null, $options->getTtl()); - $failedKeys = array_keys($failedKeys); - - // remove prefix - $prefixL = strlen($prefix); - foreach ($failedKeys as & $key) { - $key = substr($key, $prefixL); - } - - return $failedKeys; - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - if (!apc_exists($internalKey)) { - return false; - } - - $ttl = $options->getTtl(); - if (!apc_store($internalKey, $value, $ttl)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "apc_store('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - return apc_delete($prefix . $normalizedKey); - } - - /** - * Internal method to remove multiple items. - * - * @param array $normalizedKeys - * @return array Array of not removed keys - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return apc_delete($normalizedKeys); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $failedKeys = apc_delete($internalKeys); - - // remove prefix - $prefixL = strlen($prefix); - foreach ($failedKeys as & $key) { - $key = substr($key, $prefixL); - } - - return $failedKeys; - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $value = (int) $value; - $newValue = apc_inc($internalKey, $value); - - // initial value - if ($newValue === false) { - $ttl = $options->getTtl(); - $newValue = $value; - if (!apc_add($internalKey, $newValue, $ttl)) { - throw new Exception\RuntimeException( - "apc_add('{$internalKey}', {$newValue}, {$ttl}) failed" - ); - } - } - - return $newValue; - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $value = (int) $value; - $newValue = apc_dec($internalKey, $value); - - // initial value - if ($newValue === false) { - $ttl = $options->getTtl(); - $newValue = -$value; - if (!apc_add($internalKey, $newValue, $ttl)) { - throw new Exception\RuntimeException( - "apc_add('{$internalKey}', {$newValue}, {$ttl}) failed" - ); - } - } - - return $newValue; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $marker = new stdClass(); - $capabilities = new Capabilities( - $this, - $marker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array( - 'internal_key', - 'atime', 'ctime', 'mtime', 'rtime', - 'size', 'hits', 'ttl', - ), - 'minTtl' => 1, - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => (bool) ini_get('apc.use_request_time'), - 'expiredRead' => false, - 'maxKeyLength' => 5182, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - ) - ); - - // update namespace separator on change option - $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { - $params = $event->getParams(); - - if (isset($params['namespace_separator'])) { - $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); - } - }); - - $this->capabilities = $capabilities; - $this->capabilityMarker = $marker; - } - - return $this->capabilities; - } - - /* internal */ - - /** - * Normalize metadata to work with APC - * - * @param array $metadata - * @return void - */ - protected function normalizeMetadata(array & $metadata) - { - $metadata['internal_key'] = $metadata['key']; - $metadata['ctime'] = $metadata['creation_time']; - $metadata['atime'] = $metadata['access_time']; - $metadata['rtime'] = $metadata['deletion_time']; - $metadata['size'] = $metadata['mem_size']; - $metadata['hits'] = $metadata['num_hits']; - - unset( - $metadata['key'], - $metadata['creation_time'], - $metadata['access_time'], - $metadata['deletion_time'], - $metadata['mem_size'], - $metadata['num_hits'] - ); - } - - /** - * Internal method to set an item only if token matches - * - * @param mixed $token - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @see getItem() - * @see setItem() - */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) - { - return apc_cas($normalizedKey, $token, $value); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/ApcIterator.php b/library/Zend/Cache/Storage/Adapter/ApcIterator.php deleted file mode 100755 index 3cdcbf1c5..000000000 --- a/library/Zend/Cache/Storage/Adapter/ApcIterator.php +++ /dev/null @@ -1,157 +0,0 @@ -storage = $storage; - $this->baseIterator = $baseIterator; - $this->prefixLength = strlen($prefix); - } - - /** - * Get storage instance - * - * @return Apc - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Get iterator mode - * - * @return int Value of IteratorInterface::CURRENT_AS_* - */ - public function getMode() - { - return $this->mode; - } - - /** - * Set iterator mode - * - * @param int $mode - * @return ApcIterator Fluent interface - */ - public function setMode($mode) - { - $this->mode = (int) $mode; - return $this; - } - - /* Iterator */ - - /** - * Get current key, value or metadata. - * - * @return mixed - */ - public function current() - { - if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { - return $this; - } - - $key = $this->key(); - - if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { - return $this->storage->getItem($key); - } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { - return $this->storage->getMetadata($key); - } - - return $key; - } - - /** - * Get current key - * - * @return string - */ - public function key() - { - $key = $this->baseIterator->key(); - - // remove namespace prefix - return substr($key, $this->prefixLength); - } - - /** - * Move forward to next element - * - * @return void - */ - public function next() - { - $this->baseIterator->next(); - } - - /** - * Checks if current position is valid - * - * @return bool - */ - public function valid() - { - return $this->baseIterator->valid(); - } - - /** - * Rewind the Iterator to the first element. - * - * @return void - */ - public function rewind() - { - return $this->baseIterator->rewind(); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/ApcOptions.php b/library/Zend/Cache/Storage/Adapter/ApcOptions.php deleted file mode 100755 index 0299d9446..000000000 --- a/library/Zend/Cache/Storage/Adapter/ApcOptions.php +++ /dev/null @@ -1,47 +0,0 @@ -triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/BlackHole.php b/library/Zend/Cache/Storage/Adapter/BlackHole.php deleted file mode 100755 index 2938cfdee..000000000 --- a/library/Zend/Cache/Storage/Adapter/BlackHole.php +++ /dev/null @@ -1,502 +0,0 @@ -setOptions($options); - } - } - - /** - * Set options. - * - * @param array|\Traversable|AdapterOptions $options - * @return StorageInterface Fluent interface - */ - public function setOptions($options) - { - if ($this->options !== $options) { - if (!$options instanceof AdapterOptions) { - $options = new AdapterOptions($options); - } - - if ($this->options) { - $this->options->setAdapter(null); - } - $options->setAdapter($this); - $this->options = $options; - } - return $this; - } - - /** - * Get options - * - * @return AdapterOptions - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new AdapterOptions()); - } - return $this->options; - } - - /** - * Get an item. - * - * @param string $key - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - */ - public function getItem($key, & $success = null, & $casToken = null) - { - $success = false; - return null; - } - - /** - * Get multiple items. - * - * @param array $keys - * @return array Associative array of keys and values - */ - public function getItems(array $keys) - { - return array(); - } - - /** - * Test if an item exists. - * - * @param string $key - * @return bool - */ - public function hasItem($key) - { - return false; - } - - /** - * Test multiple items. - * - * @param array $keys - * @return array Array of found keys - */ - public function hasItems(array $keys) - { - return array(); - } - - /** - * Get metadata of an item. - * - * @param string $key - * @return array|bool Metadata on success, false on failure - */ - public function getMetadata($key) - { - return false; - } - - /** - * Get multiple metadata - * - * @param array $keys - * @return array Associative array of keys and metadata - */ - public function getMetadatas(array $keys) - { - return array(); - } - - /** - * Store an item. - * - * @param string $key - * @param mixed $value - * @return bool - */ - public function setItem($key, $value) - { - return false; - } - - /** - * Store multiple items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - */ - public function setItems(array $keyValuePairs) - { - return array_keys($keyValuePairs); - } - - /** - * Add an item. - * - * @param string $key - * @param mixed $value - * @return bool - */ - public function addItem($key, $value) - { - return false; - } - - /** - * Add multiple items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - */ - public function addItems(array $keyValuePairs) - { - return array_keys($keyValuePairs); - } - - /** - * Replace an existing item. - * - * @param string $key - * @param mixed $value - * @return bool - */ - public function replaceItem($key, $value) - { - return false; - } - - /** - * Replace multiple existing items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - */ - public function replaceItems(array $keyValuePairs) - { - return array_keys($keyValuePairs); - } - - /** - * Set an item only if token matches - * - * It uses the token received from getItem() to check if the item has - * changed before overwriting it. - * - * @param mixed $token - * @param string $key - * @param mixed $value - * @return bool - */ - public function checkAndSetItem($token, $key, $value) - { - return false; - } - - /** - * Reset lifetime of an item - * - * @param string $key - * @return bool - */ - public function touchItem($key) - { - return false; - } - - /** - * Reset lifetime of multiple items. - * - * @param array $keys - * @return array Array of not updated keys - */ - public function touchItems(array $keys) - { - return $keys; - } - - /** - * Remove an item. - * - * @param string $key - * @return bool - */ - public function removeItem($key) - { - return false; - } - - /** - * Remove multiple items. - * - * @param array $keys - * @return array Array of not removed keys - */ - public function removeItems(array $keys) - { - return $keys; - } - - /** - * Increment an item. - * - * @param string $key - * @param int $value - * @return int|bool The new value on success, false on failure - */ - public function incrementItem($key, $value) - { - return false; - } - - /** - * Increment multiple items. - * - * @param array $keyValuePairs - * @return array Associative array of keys and new values - */ - public function incrementItems(array $keyValuePairs) - { - return array(); - } - - /** - * Decrement an item. - * - * @param string $key - * @param int $value - * @return int|bool The new value on success, false on failure - */ - public function decrementItem($key, $value) - { - return false; - } - - /** - * Decrement multiple items. - * - * @param array $keyValuePairs - * @return array Associative array of keys and new values - */ - public function decrementItems(array $keyValuePairs) - { - return array(); - } - - /** - * Capabilities of this storage - * - * @return Capabilities - */ - public function getCapabilities() - { - if ($this->capabilities === null) { - // use default capabilities only - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities($this, $this->capabilityMarker); - } - return $this->capabilities; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - return 0; - } - - /* ClearByNamespaceInterface */ - - /** - * Remove items of given namespace - * - * @param string $namespace - * @return bool - */ - public function clearByNamespace($namespace) - { - return false; - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @return bool - */ - public function clearByPrefix($prefix) - { - return false; - } - - /* ClearExpiredInterface */ - - /** - * Remove expired items - * - * @return bool - */ - public function clearExpired() - { - return false; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - return false; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return KeyListIterator - */ - public function getIterator() - { - return new KeyListIterator($this, array()); - } - - /* OptimizableInterface */ - - /** - * Optimize the storage - * - * @return bool - */ - public function optimize() - { - return false; - } - - /* TaggableInterface */ - - /** - * Set tags to an item by given key. - * An empty array will remove all tags. - * - * @param string $key - * @param string[] $tags - * @return bool - */ - public function setTags($key, array $tags) - { - return false; - } - - /** - * Get tags of an item by given key - * - * @param string $key - * @return string[]|FALSE - */ - public function getTags($key) - { - return false; - } - - /** - * Remove items matching given tags. - * - * If $disjunction only one of the given tags must match - * else all given tags must match. - * - * @param string[] $tags - * @param bool $disjunction - * @return bool - */ - public function clearByTags(array $tags, $disjunction = false) - { - return false; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - return 0; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Dba.php b/library/Zend/Cache/Storage/Adapter/Dba.php deleted file mode 100755 index bb2860d7c..000000000 --- a/library/Zend/Cache/Storage/Adapter/Dba.php +++ /dev/null @@ -1,541 +0,0 @@ -_close(); - - parent::__destruct(); - } - - /* options */ - - /** - * Set options. - * - * @param array|Traversable|DbaOptions $options - * @return Apc - * @see getOptions() - */ - public function setOptions($options) - { - if (!$options instanceof DbaOptions) { - $options = new DbaOptions($options); - } - - return parent::setOptions($options); - } - - /** - * Get options. - * - * @return DbaOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new DbaOptions()); - } - return $this->options; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - if ($this->totalSpace === null) { - $pathname = $this->getOptions()->getPathname(); - - if ($pathname === '') { - throw new Exception\LogicException('No pathname to database file'); - } - - ErrorHandler::start(); - $total = disk_total_space(dirname($pathname)); - $error = ErrorHandler::stop(); - if ($total === false) { - throw new Exception\RuntimeException("Can't detect total space of '{$pathname}'", 0, $error); - } - $this->totalSpace = $total; - - // clean total space buffer on change pathname - $events = $this->getEventManager(); - $handle = null; - $totalSpace = & $this->totalSpace; - $callback = function ($event) use (& $events, & $handle, & $totalSpace) { - $params = $event->getParams(); - if (isset($params['pathname'])) { - $totalSpace = null; - $events->detach($handle); - } - }; - $events->attach('option', $callback); - } - - return $this->totalSpace; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $pathname = $this->getOptions()->getPathname(); - - if ($pathname === '') { - throw new Exception\LogicException('No pathname to database file'); - } - - ErrorHandler::start(); - $avail = disk_free_space(dirname($pathname)); - $error = ErrorHandler::stop(); - if ($avail === false) { - throw new Exception\RuntimeException("Can't detect free space of '{$pathname}'", 0, $error); - } - - return $avail; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - $pathname = $this->getOptions()->getPathname(); - - if ($pathname === '') { - throw new Exception\LogicException('No pathname to database file'); - } - - if (file_exists($pathname)) { - // close the dba file before delete - // and reopen (create) on next use - $this->_close(); - - ErrorHandler::start(); - $result = unlink($pathname); - $error = ErrorHandler::stop(); - if (!$result) { - throw new Exception\RuntimeException("unlink('{$pathname}') failed", 0, $error); - } - } - - return true; - } - - /* ClearByNamespaceInterface */ - - /** - * Remove items by given namespace - * - * @param string $namespace - * @return bool - */ - public function clearByNamespace($namespace) - { - $namespace = (string) $namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } - - $prefix = $namespace . $this->getOptions()->getNamespaceSeparator(); - $prefixl = strlen($prefix); - $result = true; - - $this->_open(); - - do { // Workaround for PHP-Bug #62491 & #62492 - $recheck = false; - $internalKey = dba_firstkey($this->handle); - while ($internalKey !== false && $internalKey !== null) { - if (substr($internalKey, 0, $prefixl) === $prefix) { - $result = dba_delete($internalKey, $this->handle) && $result; - } - - $internalKey = dba_nextkey($this->handle); - } - } while ($recheck); - - return $result; - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @return bool - */ - public function clearByPrefix($prefix) - { - $prefix = (string) $prefix; - if ($prefix === '') { - throw new Exception\InvalidArgumentException('No prefix given'); - } - - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator() . $prefix; - $prefixL = strlen($prefix); - $result = true; - - $this->_open(); - - do { // Workaround for PHP-Bug #62491 & #62492 - $recheck = false; - $internalKey = dba_firstkey($this->handle); - while ($internalKey !== false && $internalKey !== null) { - if (substr($internalKey, 0, $prefixL) === $prefix) { - $result = dba_delete($internalKey, $this->handle) && $result; - $recheck = true; - } - - $internalKey = dba_nextkey($this->handle); - } - } while ($recheck); - - return $result; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return ApcIterator - */ - public function getIterator() - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - return new DbaIterator($this, $this->handle, $prefix); - } - - /* OptimizableInterface */ - - /** - * Optimize the storage - * - * @return bool - * @return Exception\RuntimeException - */ - public function optimize() - { - $this->_open(); - if (!dba_optimize($this->handle)) { - throw new Exception\RuntimeException('dba_optimize failed'); - } - return true; - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - $this->_open(); - $value = dba_fetch($prefix . $normalizedKey, $this->handle); - - if ($value === false) { - $success = false; - return null; - } - - $success = true; - $casToken = $value; - return $value; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - $this->_open(); - return dba_exists($prefix . $normalizedKey, $this->handle); - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - $this->_open(); - if (!dba_replace($internalKey, $value, $this->handle)) { - throw new Exception\RuntimeException("dba_replace('{$internalKey}', ...) failed"); - } - - return true; - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - $this->_open(); - - // Workaround for PHP-Bug #54242 & #62489 - if (dba_exists($internalKey, $this->handle)) { - return false; - } - - // Workaround for PHP-Bug #54242 & #62489 - // dba_insert returns true if key already exists - ErrorHandler::start(); - $result = dba_insert($internalKey, $value, $this->handle); - $error = ErrorHandler::stop(); - if (!$result || $error) { - return false; - } - - return true; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - $this->_open(); - - // Workaround for PHP-Bug #62490 - if (!dba_exists($internalKey, $this->handle)) { - return false; - } - - return dba_delete($internalKey, $this->handle); - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $marker = new stdClass(); - $capabilities = new Capabilities( - $this, - $marker, - array( - 'supportedDatatypes' => array( - 'NULL' => 'string', - 'boolean' => 'string', - 'integer' => 'string', - 'double' => 'string', - 'string' => true, - 'array' => false, - 'object' => false, - 'resource' => false, - ), - 'minTtl' => 0, - 'supportedMetadata' => array(), - 'maxKeyLength' => 0, // TODO: maxKeyLength ???? - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - ) - ); - - // update namespace separator on change option - $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { - $params = $event->getParams(); - - if (isset($params['namespace_separator'])) { - $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); - } - }); - - $this->capabilities = $capabilities; - $this->capabilityMarker = $marker; - } - - return $this->capabilities; - } - - /** - * Open the database if not already done. - * - * @return void - * @throws Exception\LogicException - * @throws Exception\RuntimeException - */ - protected function _open() - { - if (!$this->handle) { - $options = $this->getOptions(); - $pathname = $options->getPathname(); - $mode = $options->getMode(); - $handler = $options->getHandler(); - - if ($pathname === '') { - throw new Exception\LogicException('No pathname to database file'); - } - - ErrorHandler::start(); - $dba = dba_open($pathname, $mode, $handler); - $err = ErrorHandler::stop(); - if (!$dba) { - throw new Exception\RuntimeException( - "dba_open('{$pathname}', '{$mode}', '{$handler}') failed", - 0, - $err - ); - } - $this->handle = $dba; - } - } - - /** - * Close database file if opened - * - * @return void - */ - protected function _close() - { - if ($this->handle) { - ErrorHandler::start(E_NOTICE); - dba_close($this->handle); - ErrorHandler::stop(); - $this->handle = null; - } - } -} diff --git a/library/Zend/Cache/Storage/Adapter/DbaIterator.php b/library/Zend/Cache/Storage/Adapter/DbaIterator.php deleted file mode 100755 index a895ce545..000000000 --- a/library/Zend/Cache/Storage/Adapter/DbaIterator.php +++ /dev/null @@ -1,190 +0,0 @@ -storage = $storage; - $this->handle = $handle; - $this->prefixLength = strlen($prefix); - - $this->rewind(); - } - - /** - * Get storage instance - * - * @return Dba - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Get iterator mode - * - * @return int Value of IteratorInterface::CURRENT_AS_* - */ - public function getMode() - { - return $this->mode; - } - - /** - * Set iterator mode - * - * @param int $mode - * @return ApcIterator Fluent interface - */ - public function setMode($mode) - { - $this->mode = (int) $mode; - return $this; - } - - /* Iterator */ - - /** - * Get current key, value or metadata. - * - * @return mixed - * @throws Exception\RuntimeException - */ - public function current() - { - if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { - return $this; - } - - $key = $this->key(); - - if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { - return $this->storage->getItem($key); - } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { - return $this->storage->getMetadata($key); - } - - return $key; - } - - /** - * Get current key - * - * @return string - * @throws Exception\RuntimeException - */ - public function key() - { - if ($this->currentInternalKey === false) { - throw new Exception\RuntimeException("Iterator is on an invalid state"); - } - - // remove namespace prefix - return substr($this->currentInternalKey, $this->prefixLength); - } - - /** - * Move forward to next element - * - * @return void - * @throws Exception\RuntimeException - */ - public function next() - { - if ($this->currentInternalKey === false) { - throw new Exception\RuntimeException("Iterator is on an invalid state"); - } - - $this->currentInternalKey = dba_nextkey($this->handle); - - // Workaround for PHP-Bug #62492 - if ($this->currentInternalKey === null) { - $this->currentInternalKey = false; - } - } - - /** - * Checks if current position is valid - * - * @return bool - */ - public function valid() - { - return ($this->currentInternalKey !== false); - } - - /** - * Rewind the Iterator to the first element. - * - * @return void - * @throws Exception\RuntimeException - */ - public function rewind() - { - if ($this->currentInternalKey === false) { - throw new Exception\RuntimeException("Iterator is on an invalid state"); - } - - $this->currentInternalKey = dba_firstkey($this->handle); - - // Workaround for PHP-Bug #62492 - if ($this->currentInternalKey === null) { - $this->currentInternalKey = false; - } - } -} diff --git a/library/Zend/Cache/Storage/Adapter/DbaOptions.php b/library/Zend/Cache/Storage/Adapter/DbaOptions.php deleted file mode 100755 index 13172b749..000000000 --- a/library/Zend/Cache/Storage/Adapter/DbaOptions.php +++ /dev/null @@ -1,129 +0,0 @@ -triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * Set pathname to database file - * - * @param string $pathname - * @return DbaOptions - */ - public function setPathname($pathname) - { - $this->pathname = (string) $pathname; - $this->triggerOptionEvent('pathname', $pathname); - return $this; - } - - /** - * Get pathname to database file - * - * @return string - */ - public function getPathname() - { - return $this->pathname; - } - - /** - * - * - * @param string $mode - * @return \Zend\Cache\Storage\Adapter\DbaOptions - */ - public function setMode($mode) - { - $this->mode = (string) $mode; - $this->triggerOptionEvent('mode', $mode); - return $this; - } - - public function getMode() - { - return $this->mode; - } - - public function setHandler($handler) - { - $handler = (string) $handler; - - if (!function_exists('dba_handlers') || !in_array($handler, dba_handlers())) { - throw new Exception\ExtensionNotLoadedException("DBA-Handler '{$handler}' not supported"); - } - - $this->triggerOptionEvent('handler', $handler); - $this->handler = $handler; - return $this; - } - - public function getHandler() - { - return $this->handler; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Filesystem.php b/library/Zend/Cache/Storage/Adapter/Filesystem.php deleted file mode 100755 index ef1c2a7de..000000000 --- a/library/Zend/Cache/Storage/Adapter/Filesystem.php +++ /dev/null @@ -1,1616 +0,0 @@ -options) { - $this->setOptions(new FilesystemOptions()); - } - return $this->options; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @throws Exception\RuntimeException - * @return bool - */ - public function flush() - { - $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; - $dir = $this->getOptions()->getCacheDir(); - $clearFolder = null; - $clearFolder = function ($dir) use (& $clearFolder, $flags) { - $it = new GlobIterator($dir . DIRECTORY_SEPARATOR . '*', $flags); - foreach ($it as $pathname) { - if ($it->isDir()) { - $clearFolder($pathname); - rmdir($pathname); - } else { - unlink($pathname); - } - } - }; - - ErrorHandler::start(); - $clearFolder($dir); - $error = ErrorHandler::stop(); - if ($error) { - throw new Exception\RuntimeException("Flushing directory '{$dir}' failed", 0, $error); - } - - return true; - } - - /* ClearExpiredInterface */ - - /** - * Remove expired items - * - * @return bool - * - * @triggers clearExpired.exception(ExceptionEvent) - */ - public function clearExpired() - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_FILEINFO; - $path = $options->getCacheDir() - . str_repeat(DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) - . DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new GlobIterator($path, $flags); - $time = time(); - $ttl = $options->getTtl(); - - ErrorHandler::start(); - foreach ($glob as $entry) { - $mtime = $entry->getMTime(); - if ($time >= $mtime + $ttl) { - $pathname = $entry->getPathname(); - unlink($pathname); - - $tagPathname = substr($pathname, 0, -4) . '.tag'; - if (file_exists($tagPathname)) { - unlink($tagPathname); - } - } - } - $error = ErrorHandler::stop(); - if ($error) { - $result = false; - return $this->triggerException( - __FUNCTION__, - new ArrayObject(), - $result, - new Exception\RuntimeException('Failed to clear expired items', 0, $error) - ); - } - - return true; - } - - /* ClearByNamespaceInterface */ - - /** - * Remove items by given namespace - * - * @param string $namespace - * @throws Exception\RuntimeException - * @return bool - */ - public function clearByNamespace($namespace) - { - $namespace = (string) $namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } - - $options = $this->getOptions(); - $prefix = $namespace . $options->getNamespaceSeparator(); - - $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; - $path = $options->getCacheDir() - . str_repeat(DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) - . DIRECTORY_SEPARATOR . $prefix . '*.*'; - $glob = new GlobIterator($path, $flags); - - ErrorHandler::start(); - foreach ($glob as $pathname) { - unlink($pathname); - } - $error = ErrorHandler::stop(); - if ($error) { - throw new Exception\RuntimeException("Failed to remove files of '{$path}'", 0, $error); - } - - return true; - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @throws Exception\RuntimeException - * @return bool - */ - public function clearByPrefix($prefix) - { - $prefix = (string) $prefix; - if ($prefix === '') { - throw new Exception\InvalidArgumentException('No prefix given'); - } - - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $nsPrefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; - $path = $options->getCacheDir() - . str_repeat(DIRECTORY_SEPARATOR . $nsPrefix . '*', $options->getDirLevel()) - . DIRECTORY_SEPARATOR . $nsPrefix . $prefix . '*.*'; - $glob = new GlobIterator($path, $flags); - - ErrorHandler::start(); - foreach ($glob as $pathname) { - unlink($pathname); - } - $error = ErrorHandler::stop(); - if ($error) { - throw new Exception\RuntimeException("Failed to remove files of '{$path}'", 0, $error); - } - - return true; - } - - /* TaggableInterface */ - - /** - * Set tags to an item by given key. - * An empty array will remove all tags. - * - * @param string $key - * @param string[] $tags - * @return bool - */ - public function setTags($key, array $tags) - { - $this->normalizeKey($key); - if (!$this->internalHasItem($key)) { - return false; - } - - $filespec = $this->getFileSpec($key); - - if (!$tags) { - $this->unlink($filespec . '.tag'); - return true; - } - - $this->putFileContent($filespec . '.tag', implode("\n", $tags)); - return true; - } - - /** - * Get tags of an item by given key - * - * @param string $key - * @return string[]|FALSE - */ - public function getTags($key) - { - $this->normalizeKey($key); - if (!$this->internalHasItem($key)) { - return false; - } - - $filespec = $this->getFileSpec($key); - $tags = array(); - if (file_exists($filespec . '.tag')) { - $tags = explode("\n", $this->getFileContent($filespec . '.tag')); - } - - return $tags; - } - - /** - * Remove items matching given tags. - * - * If $disjunction only one of the given tags must match - * else all given tags must match. - * - * @param string[] $tags - * @param bool $disjunction - * @return bool - */ - public function clearByTags(array $tags, $disjunction = false) - { - if (!$tags) { - return true; - } - - $tagCount = count($tags); - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; - $path = $options->getCacheDir() - . str_repeat(DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) - . DIRECTORY_SEPARATOR . $prefix . '*.tag'; - $glob = new GlobIterator($path, $flags); - - foreach ($glob as $pathname) { - $diff = array_diff($tags, explode("\n", $this->getFileContent($pathname))); - - $rem = false; - if ($disjunction && count($diff) < $tagCount) { - $rem = true; - } elseif (!$disjunction && !$diff) { - $rem = true; - } - - if ($rem) { - unlink($pathname); - - $datPathname = substr($pathname, 0, -4) . '.dat'; - if (file_exists($datPathname)) { - unlink($datPathname); - } - } - } - - return true; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return FilesystemIterator - */ - public function getIterator() - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $path = $options->getCacheDir() - . str_repeat(DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) - . DIRECTORY_SEPARATOR . $prefix . '*.dat'; - return new FilesystemIterator($this, $path, $prefix); - } - - /* OptimizableInterface */ - - /** - * Optimize the storage - * - * @return bool - * @return Exception\RuntimeException - */ - public function optimize() - { - $options = $this->getOptions(); - if ($options->getDirLevel()) { - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - - // removes only empty directories - $this->rmDir($options->getCacheDir(), $prefix); - } - return true; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @throws Exception\RuntimeException - * @return int|float - */ - public function getTotalSpace() - { - if ($this->totalSpace === null) { - $path = $this->getOptions()->getCacheDir(); - - ErrorHandler::start(); - $total = disk_total_space($path); - $error = ErrorHandler::stop(); - if ($total === false) { - throw new Exception\RuntimeException("Can't detect total space of '{$path}'", 0, $error); - } - $this->totalSpace = $total; - - // clean total space buffer on change cache_dir - $events = $this->getEventManager(); - $handle = null; - $totalSpace = & $this->totalSpace; - $callback = function ($event) use (& $events, & $handle, & $totalSpace) { - $params = $event->getParams(); - if (isset($params['cache_dir'])) { - $totalSpace = null; - $events->detach($handle); - } - }; - $events->attach('option', $callback); - } - - return $this->totalSpace; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @throws Exception\RuntimeException - * @return int|float - */ - public function getAvailableSpace() - { - $path = $this->getOptions()->getCacheDir(); - - ErrorHandler::start(); - $avail = disk_free_space($path); - $error = ErrorHandler::stop(); - if ($avail === false) { - throw new Exception\RuntimeException("Can't detect free space of '{$path}'", 0, $error); - } - - return $avail; - } - - /* reading */ - - /** - * Get an item. - * - * @param string $key - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) - */ - public function getItem($key, & $success = null, & $casToken = null) - { - $options = $this->getOptions(); - if ($options->getReadable() && $options->getClearStatCache()) { - clearstatcache(); - } - - $argn = func_num_args(); - if ($argn > 2) { - return parent::getItem($key, $success, $casToken); - } elseif ($argn > 1) { - return parent::getItem($key, $success); - } - - return parent::getItem($key); - } - - /** - * Get multiple items. - * - * @param array $keys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) - */ - public function getItems(array $keys) - { - $options = $this->getOptions(); - if ($options->getReadable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::getItems($keys); - } - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - if (!$this->internalHasItem($normalizedKey)) { - $success = false; - return null; - } - - try { - $filespec = $this->getFileSpec($normalizedKey); - $data = $this->getFileContent($filespec . '.dat'); - - // use filemtime + filesize as CAS token - if (func_num_args() > 2) { - $casToken = filemtime($filespec . '.dat') . filesize($filespec . '.dat'); - } - $success = true; - return $data; - } catch (BaseException $e) { - $success = false; - throw $e; - } - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $keys = $normalizedKeys; // Don't change argument passed by reference - $result = array(); - while ($keys) { - // LOCK_NB if more than one items have to read - $nonBlocking = count($keys) > 1; - $wouldblock = null; - - // read items - foreach ($keys as $i => $key) { - if (!$this->internalHasItem($key)) { - unset($keys[$i]); - continue; - } - - $filespec = $this->getFileSpec($key); - $data = $this->getFileContent($filespec . '.dat', $nonBlocking, $wouldblock); - if ($nonBlocking && $wouldblock) { - continue; - } else { - unset($keys[$i]); - } - - $result[$key] = $data; - } - - // TODO: Don't check ttl after first iteration - // $options['ttl'] = 0; - } - - return $result; - } - - /** - * Test if an item exists. - * - * @param string $key - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers hasItem.pre(PreEvent) - * @triggers hasItem.post(PostEvent) - * @triggers hasItem.exception(ExceptionEvent) - */ - public function hasItem($key) - { - $options = $this->getOptions(); - if ($options->getReadable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::hasItem($key); - } - - /** - * Test multiple items. - * - * @param array $keys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - * - * @triggers hasItems.pre(PreEvent) - * @triggers hasItems.post(PostEvent) - * @triggers hasItems.exception(ExceptionEvent) - */ - public function hasItems(array $keys) - { - $options = $this->getOptions(); - if ($options->getReadable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::hasItems($keys); - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $file = $this->getFileSpec($normalizedKey) . '.dat'; - if (!file_exists($file)) { - return false; - } - - $ttl = $this->getOptions()->getTtl(); - if ($ttl) { - ErrorHandler::start(); - $mtime = filemtime($file); - $error = ErrorHandler::stop(); - if (!$mtime) { - throw new Exception\RuntimeException("Error getting mtime of file '{$file}'", 0, $error); - } - - if (time() >= ($mtime + $ttl)) { - return false; - } - } - - return true; - } - - /** - * Get metadata - * - * @param string $key - * @return array|bool Metadata on success, false on failure - */ - public function getMetadata($key) - { - $options = $this->getOptions(); - if ($options->getReadable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::getMetadata($key); - } - - /** - * Get metadatas - * - * @param array $keys - * @param array $options - * @return array Associative array of keys and metadata - */ - public function getMetadatas(array $keys, array $options = array()) - { - $options = $this->getOptions(); - if ($options->getReadable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::getMetadatas($keys); - } - - /** - * Get info by key - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - */ - protected function internalGetMetadata(& $normalizedKey) - { - if (!$this->internalHasItem($normalizedKey)) { - return false; - } - - $options = $this->getOptions(); - $filespec = $this->getFileSpec($normalizedKey); - $file = $filespec . '.dat'; - - $metadata = array( - 'filespec' => $filespec, - 'mtime' => filemtime($file) - ); - - if (!$options->getNoCtime()) { - $metadata['ctime'] = filectime($file); - } - - if (!$options->getNoAtime()) { - $metadata['atime'] = fileatime($file); - } - - return $metadata; - } - - /** - * Internal method to get multiple metadata - * - * @param array $normalizedKeys - * @return array Associative array of keys and metadata - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadatas(array & $normalizedKeys) - { - $options = $this->getOptions(); - $result = array(); - - foreach ($normalizedKeys as $normalizedKey) { - $filespec = $this->getFileSpec($normalizedKey); - $file = $filespec . '.dat'; - - $metadata = array( - 'filespec' => $filespec, - 'mtime' => filemtime($file), - ); - - if (!$options->getNoCtime()) { - $metadata['ctime'] = filectime($file); - } - - if (!$options->getNoAtime()) { - $metadata['atime'] = fileatime($file); - } - - $result[$normalizedKey] = $metadata; - } - - return $result; - } - - /* writing */ - - /** - * Store an item. - * - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) - */ - public function setItem($key, $value) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - return parent::setItem($key, $value); - } - - /** - * Store multiple items. - * - * @param array $keyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - * - * @triggers setItems.pre(PreEvent) - * @triggers setItems.post(PostEvent) - * @triggers setItems.exception(ExceptionEvent) - */ - public function setItems(array $keyValuePairs) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::setItems($keyValuePairs); - } - - /** - * Add an item. - * - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers addItem.pre(PreEvent) - * @triggers addItem.post(PostEvent) - * @triggers addItem.exception(ExceptionEvent) - */ - public function addItem($key, $value) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::addItem($key, $value); - } - - /** - * Add multiple items. - * - * @param array $keyValuePairs - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers addItems.pre(PreEvent) - * @triggers addItems.post(PostEvent) - * @triggers addItems.exception(ExceptionEvent) - */ - public function addItems(array $keyValuePairs) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::addItems($keyValuePairs); - } - - /** - * Replace an existing item. - * - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers replaceItem.pre(PreEvent) - * @triggers replaceItem.post(PostEvent) - * @triggers replaceItem.exception(ExceptionEvent) - */ - public function replaceItem($key, $value) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::replaceItem($key, $value); - } - - /** - * Replace multiple existing items. - * - * @param array $keyValuePairs - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers replaceItems.pre(PreEvent) - * @triggers replaceItems.post(PostEvent) - * @triggers replaceItems.exception(ExceptionEvent) - */ - public function replaceItems(array $keyValuePairs) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::replaceItems($keyValuePairs); - } - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $filespec = $this->getFileSpec($normalizedKey); - $this->prepareDirectoryStructure($filespec); - - // write data in non-blocking mode - $wouldblock = null; - $this->putFileContent($filespec . '.dat', $value, true, $wouldblock); - - // delete related tag file (if present) - $this->unlink($filespec . '.tag'); - - // Retry writing data in blocking mode if it was blocked before - if ($wouldblock) { - $this->putFileContent($filespec . '.dat', $value); - } - - return true; - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $oldUmask = null; - - // create an associated array of files and contents to write - $contents = array(); - foreach ($normalizedKeyValuePairs as $key => & $value) { - $filespec = $this->getFileSpec($key); - $this->prepareDirectoryStructure($filespec); - - // *.dat file - $contents[$filespec . '.dat'] = & $value; - - // *.tag file - $this->unlink($filespec . '.tag'); - } - - // write to disk - while ($contents) { - $nonBlocking = count($contents) > 1; - $wouldblock = null; - - foreach ($contents as $file => & $content) { - $this->putFileContent($file, $content, $nonBlocking, $wouldblock); - if (!$nonBlocking || !$wouldblock) { - unset($contents[$file]); - } - } - } - - // return OK - return array(); - } - - /** - * Set an item only if token matches - * - * It uses the token received from getItem() to check if the item has - * changed before overwriting it. - * - * @param mixed $token - * @param string $key - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * @see getItem() - * @see setItem() - */ - public function checkAndSetItem($token, $key, $value) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::checkAndSetItem($token, $key, $value); - } - - /** - * Internal method to set an item only if token matches - * - * @param mixed $token - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * @see getItem() - * @see setItem() - */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) - { - if (!$this->internalHasItem($normalizedKey)) { - return false; - } - - // use filemtime + filesize as CAS token - $file = $this->getFileSpec($normalizedKey) . '.dat'; - $check = filemtime($file) . filesize($file); - if ($token !== $check) { - return false; - } - - return $this->internalSetItem($normalizedKey, $value); - } - - /** - * Reset lifetime of an item - * - * @param string $key - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers touchItem.pre(PreEvent) - * @triggers touchItem.post(PostEvent) - * @triggers touchItem.exception(ExceptionEvent) - */ - public function touchItem($key) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::touchItem($key); - } - - /** - * Reset lifetime of multiple items. - * - * @param array $keys - * @return array Array of not updated keys - * @throws Exception\ExceptionInterface - * - * @triggers touchItems.pre(PreEvent) - * @triggers touchItems.post(PostEvent) - * @triggers touchItems.exception(ExceptionEvent) - */ - public function touchItems(array $keys) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::touchItems($keys); - } - - /** - * Internal method to reset lifetime of an item - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalTouchItem(& $normalizedKey) - { - if (!$this->internalHasItem($normalizedKey)) { - return false; - } - - $filespec = $this->getFileSpec($normalizedKey); - - ErrorHandler::start(); - $touch = touch($filespec . '.dat'); - $error = ErrorHandler::stop(); - if (!$touch) { - throw new Exception\RuntimeException("Error touching file '{$filespec}.dat'", 0, $error); - } - - return true; - } - - /** - * Remove an item. - * - * @param string $key - * @return bool - * @throws Exception\ExceptionInterface - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) - */ - public function removeItem($key) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::removeItem($key); - } - - /** - * Remove multiple items. - * - * @param array $keys - * @return array Array of not removed keys - * @throws Exception\ExceptionInterface - * - * @triggers removeItems.pre(PreEvent) - * @triggers removeItems.post(PostEvent) - * @triggers removeItems.exception(ExceptionEvent) - */ - public function removeItems(array $keys) - { - $options = $this->getOptions(); - if ($options->getWritable() && $options->getClearStatCache()) { - clearstatcache(); - } - - return parent::removeItems($keys); - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $filespec = $this->getFileSpec($normalizedKey); - if (!file_exists($filespec . '.dat')) { - return false; - } else { - $this->unlink($filespec . '.dat'); - $this->unlink($filespec . '.tag'); - } - return true; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $marker = new stdClass(); - $options = $this->getOptions(); - - // detect metadata - $metadata = array('mtime', 'filespec'); - if (!$options->getNoAtime()) { - $metadata[] = 'atime'; - } - if (!$options->getNoCtime()) { - $metadata[] = 'ctime'; - } - - $capabilities = new Capabilities( - $this, - $marker, - array( - 'supportedDatatypes' => array( - 'NULL' => 'string', - 'boolean' => 'string', - 'integer' => 'string', - 'double' => 'string', - 'string' => true, - 'array' => false, - 'object' => false, - 'resource' => false, - ), - 'supportedMetadata' => $metadata, - 'minTtl' => 1, - 'maxTtl' => 0, - 'staticTtl' => false, - 'ttlPrecision' => 1, - 'expiredRead' => true, - 'maxKeyLength' => 251, // 255 - strlen(.dat | .tag) - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $options->getNamespaceSeparator(), - ) - ); - - // update capabilities on change options - $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { - $params = $event->getParams(); - - if (isset($params['namespace_separator'])) { - $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); - } - - if (isset($params['no_atime']) || isset($params['no_ctime'])) { - $metadata = $capabilities->getSupportedMetadata(); - - if (isset($params['no_atime']) && !$params['no_atime']) { - $metadata[] = 'atime'; - } elseif (isset($params['no_atime']) && ($index = array_search('atime', $metadata)) !== false) { - unset($metadata[$index]); - } - - if (isset($params['no_ctime']) && !$params['no_ctime']) { - $metadata[] = 'ctime'; - } elseif (isset($params['no_ctime']) && ($index = array_search('ctime', $metadata)) !== false) { - unset($metadata[$index]); - } - - $capabilities->setSupportedMetadata($marker, $metadata); - } - }); - - $this->capabilityMarker = $marker; - $this->capabilities = $capabilities; - } - - return $this->capabilities; - } - - /* internal */ - - /** - * Removes directories recursive by namespace - * - * @param string $dir Directory to delete - * @param string $prefix Namespace + Separator - * @return bool - */ - protected function rmDir($dir, $prefix) - { - $glob = glob( - $dir . DIRECTORY_SEPARATOR . $prefix . '*', - GLOB_ONLYDIR | GLOB_NOESCAPE | GLOB_NOSORT - ); - if (!$glob) { - // On some systems glob returns false even on empty result - return true; - } - - $ret = true; - foreach ($glob as $subdir) { - // skip removing current directory if removing of sub-directory failed - if ($this->rmDir($subdir, $prefix)) { - // ignore not empty directories - ErrorHandler::start(); - $ret = rmdir($subdir) && $ret; - ErrorHandler::stop(); - } else { - $ret = false; - } - } - - return $ret; - } - - /** - * Get file spec of the given key and namespace - * - * @param string $normalizedKey - * @return string - */ - protected function getFileSpec($normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $path = $options->getCacheDir() . DIRECTORY_SEPARATOR; - $level = $options->getDirLevel(); - - $fileSpecId = $path . $prefix . $normalizedKey . '/' . $level; - if ($this->lastFileSpecId !== $fileSpecId) { - if ($level > 0) { - // create up to 256 directories per directory level - $hash = md5($normalizedKey); - for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { - $path .= $prefix . $hash[$i] . $hash[$i+1] . DIRECTORY_SEPARATOR; - } - } - - $this->lastFileSpecId = $fileSpecId; - $this->lastFileSpec = $path . $prefix . $normalizedKey; - } - - return $this->lastFileSpec; - } - - /** - * Read info file - * - * @param string $file - * @param bool $nonBlocking Don't block script if file is locked - * @param bool $wouldblock The optional argument is set to TRUE if the lock would block - * @return array|bool The info array or false if file wasn't found - * @throws Exception\RuntimeException - */ - protected function readInfoFile($file, $nonBlocking = false, & $wouldblock = null) - { - if (!file_exists($file)) { - return false; - } - - $content = $this->getFileContent($file, $nonBlocking, $wouldblock); - if ($nonBlocking && $wouldblock) { - return false; - } - - ErrorHandler::start(); - $ifo = unserialize($content); - $err = ErrorHandler::stop(); - if (!is_array($ifo)) { - throw new Exception\RuntimeException("Corrupted info file '{$file}'", 0, $err); - } - - return $ifo; - } - - /** - * Read a complete file - * - * @param string $file File complete path - * @param bool $nonBlocking Don't block script if file is locked - * @param bool $wouldblock The optional argument is set to TRUE if the lock would block - * @return string - * @throws Exception\RuntimeException - */ - protected function getFileContent($file, $nonBlocking = false, & $wouldblock = null) - { - $locking = $this->getOptions()->getFileLocking(); - $wouldblock = null; - - ErrorHandler::start(); - - // if file locking enabled -> file_get_contents can't be used - if ($locking) { - $fp = fopen($file, 'rb'); - if ($fp === false) { - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error opening file '{$file}'", 0, $err); - } - - if ($nonBlocking) { - $lock = flock($fp, LOCK_SH | LOCK_NB, $wouldblock); - if ($wouldblock) { - fclose($fp); - ErrorHandler::stop(); - return; - } - } else { - $lock = flock($fp, LOCK_SH); - } - - if (!$lock) { - fclose($fp); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error locking file '{$file}'", 0, $err); - } - - $res = stream_get_contents($fp); - if ($res === false) { - flock($fp, LOCK_UN); - fclose($fp); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException('Error getting stream contents', 0, $err); - } - - flock($fp, LOCK_UN); - fclose($fp); - - // if file locking disabled -> file_get_contents can be used - } else { - $res = file_get_contents($file, false); - if ($res === false) { - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error getting file contents for file '{$file}'", 0, $err); - } - } - - ErrorHandler::stop(); - return $res; - } - - /** - * Prepares a directory structure for the given file(spec) - * using the configured directory level. - * - * @param string $file - * @return void - * @throws Exception\RuntimeException - */ - protected function prepareDirectoryStructure($file) - { - $options = $this->getOptions(); - $level = $options->getDirLevel(); - - // Directory structure is required only if directory level > 0 - if (!$level) { - return; - } - - // Directory structure already exists - $pathname = dirname($file); - if (file_exists($pathname)) { - return; - } - - $perm = $options->getDirPermission(); - $umask = $options->getUmask(); - if ($umask !== false && $perm !== false) { - $perm = $perm & ~$umask; - } - - ErrorHandler::start(); - - if ($perm === false || $level == 1) { - // build-in mkdir function is enough - - $umask = ($umask !== false) ? umask($umask) : false; - $res = mkdir($pathname, ($perm !== false) ? $perm : 0777, true); - - if ($umask !== false) { - umask($umask); - } - - if (!$res) { - $err = ErrorHandler::stop(); - - // Issue 6435: - // mkdir could fail because of a race condition it was already created by another process - // after the first file_exists above - if (file_exists($pathname)) { - return; - } - - $oct = ($perm === false) ? '777' : decoct($perm); - throw new Exception\RuntimeException("mkdir('{$pathname}', 0{$oct}, true) failed", 0, $err); - } - - if ($perm !== false && !chmod($pathname, $perm)) { - $oct = decoct($perm); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("chmod('{$pathname}', 0{$oct}) failed", 0, $err); - } - } else { - // build-in mkdir function sets permission together with current umask - // which doesn't work well on multo threaded webservers - // -> create directories one by one and set permissions - - // find existing path and missing path parts - $parts = array(); - $path = $pathname; - while (!file_exists($path)) { - array_unshift($parts, basename($path)); - $nextPath = dirname($path); - if ($nextPath === $path) { - break; - } - $path = $nextPath; - } - - // make all missing path parts - foreach ($parts as $part) { - $path.= DIRECTORY_SEPARATOR . $part; - - // create a single directory, set and reset umask immediately - $umask = ($umask !== false) ? umask($umask) : false; - $res = mkdir($path, ($perm === false) ? 0777 : $perm, false); - if ($umask !== false) { - umask($umask); - } - - if (!$res) { - // Issue 6435: - // mkdir could fail because of a race condition it was already created by another process - // after the first file_exists above ... go to the next path part. - if (file_exists($path)) { - continue; - } - - $oct = ($perm === false) ? '777' : decoct($perm); - ErrorHandler::stop(); - throw new Exception\RuntimeException( - "mkdir('{$path}', 0{$oct}, false) failed" - ); - } - - if ($perm !== false && !chmod($path, $perm)) { - $oct = decoct($perm); - ErrorHandler::stop(); - throw new Exception\RuntimeException( - "chmod('{$path}', 0{$oct}) failed" - ); - } - } - } - - ErrorHandler::stop(); - } - - /** - * Write content to a file - * - * @param string $file File complete path - * @param string $data Data to write - * @param bool $nonBlocking Don't block script if file is locked - * @param bool $wouldblock The optional argument is set to TRUE if the lock would block - * @return void - * @throws Exception\RuntimeException - */ - protected function putFileContent($file, $data, $nonBlocking = false, & $wouldblock = null) - { - $options = $this->getOptions(); - $locking = $options->getFileLocking(); - $nonBlocking = $locking && $nonBlocking; - $wouldblock = null; - - $umask = $options->getUmask(); - $perm = $options->getFilePermission(); - if ($umask !== false && $perm !== false) { - $perm = $perm & ~$umask; - } - - ErrorHandler::start(); - - // if locking and non blocking is enabled -> file_put_contents can't used - if ($locking && $nonBlocking) { - $umask = ($umask !== false) ? umask($umask) : false; - - $fp = fopen($file, 'cb'); - - if ($umask) { - umask($umask); - } - - if (!$fp) { - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error opening file '{$file}'", 0, $err); - } - - if ($perm !== false && !chmod($file, $perm)) { - fclose($fp); - $oct = decoct($perm); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("chmod('{$file}', 0{$oct}) failed", 0, $err); - } - - if (!flock($fp, LOCK_EX | LOCK_NB, $wouldblock)) { - fclose($fp); - $err = ErrorHandler::stop(); - if ($wouldblock) { - return; - } else { - throw new Exception\RuntimeException("Error locking file '{$file}'", 0, $err); - } - } - - if (fwrite($fp, $data) === false) { - flock($fp, LOCK_UN); - fclose($fp); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error writing file '{$file}'", 0, $err); - } - - if (!ftruncate($fp, strlen($data))) { - flock($fp, LOCK_UN); - fclose($fp); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error truncating file '{$file}'", 0, $err); - } - - flock($fp, LOCK_UN); - fclose($fp); - - // else -> file_put_contents can be used - } else { - $flags = 0; - if ($locking) { - $flags = $flags | LOCK_EX; - } - - $umask = ($umask !== false) ? umask($umask) : false; - - $rs = file_put_contents($file, $data, $flags); - - if ($umask) { - umask($umask); - } - - if ($rs === false) { - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("Error writing file '{$file}'", 0, $err); - } - - if ($perm !== false && !chmod($file, $perm)) { - $oct = decoct($perm); - $err = ErrorHandler::stop(); - throw new Exception\RuntimeException("chmod('{$file}', 0{$oct}) failed", 0, $err); - } - } - - ErrorHandler::stop(); - } - - /** - * Unlink a file - * - * @param string $file - * @return void - * @throws Exception\RuntimeException - */ - protected function unlink($file) - { - ErrorHandler::start(); - $res = unlink($file); - $err = ErrorHandler::stop(); - - // only throw exception if file still exists after deleting - if (!$res && file_exists($file)) { - throw new Exception\RuntimeException( - "Error unlinking file '{$file}'; file still exists", - 0, - $err - ); - } - } -} diff --git a/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php b/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php deleted file mode 100755 index 447cfb3db..000000000 --- a/library/Zend/Cache/Storage/Adapter/FilesystemIterator.php +++ /dev/null @@ -1,179 +0,0 @@ -storage = $storage; - $this->globIterator = new GlobIterator($path, GlobIterator::KEY_AS_FILENAME); - $this->prefix = $prefix; - $this->prefixLength = strlen($prefix); - } - - /** - * Get storage instance - * - * @return Filesystem - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Get iterator mode - * - * @return int Value of IteratorInterface::CURRENT_AS_* - */ - public function getMode() - { - return $this->mode; - } - - /** - * Set iterator mode - * - * @param int $mode - * @return FilesystemIterator Fluent interface - */ - public function setMode($mode) - { - $this->mode = (int) $mode; - return $this; - } - - /* Iterator */ - - /** - * Get current key, value or metadata. - * - * @return mixed - */ - public function current() - { - if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { - return $this; - } - - $key = $this->key(); - - if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { - return $this->storage->getItem($key); - } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { - return $this->storage->getMetadata($key); - } - - return $key; - } - - /** - * Get current key - * - * @return string - */ - public function key() - { - $filename = $this->globIterator->key(); - - // return without namespace prefix and file suffix - return substr($filename, $this->prefixLength, -4); - } - - /** - * Move forward to next element - * - * @return void - */ - public function next() - { - $this->globIterator->next(); - } - - /** - * Checks if current position is valid - * - * @return bool - */ - public function valid() - { - try { - return $this->globIterator->valid(); - } catch (\LogicException $e) { - // @link https://bugs.php.net/bug.php?id=55701 - // GlobIterator throws LogicException with message - // 'The parent constructor was not called: the object is in an invalid state' - return false; - } - } - - /** - * Rewind the Iterator to the first element. - * - * @return bool false if the operation failed. - */ - public function rewind() - { - try { - return $this->globIterator->rewind(); - } catch (\LogicException $e) { - // @link https://bugs.php.net/bug.php?id=55701 - // GlobIterator throws LogicException with message - // 'The parent constructor was not called: the object is in an invalid state' - return false; - } - } -} diff --git a/library/Zend/Cache/Storage/Adapter/FilesystemOptions.php b/library/Zend/Cache/Storage/Adapter/FilesystemOptions.php deleted file mode 100755 index 5eabbdf3f..000000000 --- a/library/Zend/Cache/Storage/Adapter/FilesystemOptions.php +++ /dev/null @@ -1,457 +0,0 @@ -filePermission = false; - $this->dirPermission = false; - } - - parent::__construct($options); - } - - /** - * Set cache dir - * - * @param string $cacheDir - * @return FilesystemOptions - * @throws Exception\InvalidArgumentException - */ - public function setCacheDir($cacheDir) - { - if ($cacheDir !== null) { - if (!is_dir($cacheDir)) { - throw new Exception\InvalidArgumentException( - "Cache directory '{$cacheDir}' not found or not a directory" - ); - } elseif (!is_writable($cacheDir)) { - throw new Exception\InvalidArgumentException( - "Cache directory '{$cacheDir}' not writable" - ); - } elseif (!is_readable($cacheDir)) { - throw new Exception\InvalidArgumentException( - "Cache directory '{$cacheDir}' not readable" - ); - } - - $cacheDir = rtrim(realpath($cacheDir), DIRECTORY_SEPARATOR); - } else { - $cacheDir = sys_get_temp_dir(); - } - - $this->triggerOptionEvent('cache_dir', $cacheDir); - $this->cacheDir = $cacheDir; - return $this; - } - - /** - * Get cache dir - * - * @return null|string - */ - public function getCacheDir() - { - if ($this->cacheDir === null) { - $this->setCacheDir(null); - } - - return $this->cacheDir; - } - - /** - * Set clear stat cache - * - * @param bool $clearStatCache - * @return FilesystemOptions - */ - public function setClearStatCache($clearStatCache) - { - $clearStatCache = (bool) $clearStatCache; - $this->triggerOptionEvent('clear_stat_cache', $clearStatCache); - $this->clearStatCache = $clearStatCache; - return $this; - } - - /** - * Get clear stat cache - * - * @return bool - */ - public function getClearStatCache() - { - return $this->clearStatCache; - } - - /** - * Set dir level - * - * @param int $dirLevel - * @return FilesystemOptions - * @throws Exception\InvalidArgumentException - */ - public function setDirLevel($dirLevel) - { - $dirLevel = (int) $dirLevel; - if ($dirLevel < 0 || $dirLevel > 16) { - throw new Exception\InvalidArgumentException( - "Directory level '{$dirLevel}' must be between 0 and 16" - ); - } - $this->triggerOptionEvent('dir_level', $dirLevel); - $this->dirLevel = $dirLevel; - return $this; - } - - /** - * Get dir level - * - * @return int - */ - public function getDirLevel() - { - return $this->dirLevel; - } - - /** - * Set permission to create directories on unix systems - * - * @param false|string|int $dirPermission FALSE to disable explicit permission or an octal number - * @return FilesystemOptions - * @see setUmask - * @see setFilePermission - * @link http://php.net/manual/function.chmod.php - */ - public function setDirPermission($dirPermission) - { - if ($dirPermission !== false) { - if (is_string($dirPermission)) { - $dirPermission = octdec($dirPermission); - } else { - $dirPermission = (int) $dirPermission; - } - - // validate - if (($dirPermission & 0700) != 0700) { - throw new Exception\InvalidArgumentException( - 'Invalid directory permission: need permission to execute, read and write by owner' - ); - } - } - - if ($this->dirPermission !== $dirPermission) { - $this->triggerOptionEvent('dir_permission', $dirPermission); - $this->dirPermission = $dirPermission; - } - - return $this; - } - - /** - * Get permission to create directories on unix systems - * - * @return false|int - */ - public function getDirPermission() - { - return $this->dirPermission; - } - - /** - * Set file locking - * - * @param bool $fileLocking - * @return FilesystemOptions - */ - public function setFileLocking($fileLocking) - { - $fileLocking = (bool) $fileLocking; - $this->triggerOptionEvent('file_locking', $fileLocking); - $this->fileLocking = $fileLocking; - return $this; - } - - /** - * Get file locking - * - * @return bool - */ - public function getFileLocking() - { - return $this->fileLocking; - } - - /** - * Set permission to create files on unix systems - * - * @param false|string|int $filePermission FALSE to disable explicit permission or an octal number - * @return FilesystemOptions - * @see setUmask - * @see setDirPermission - * @link http://php.net/manual/function.chmod.php - */ - public function setFilePermission($filePermission) - { - if ($filePermission !== false) { - if (is_string($filePermission)) { - $filePermission = octdec($filePermission); - } else { - $filePermission = (int) $filePermission; - } - - // validate - if (($filePermission & 0600) != 0600) { - throw new Exception\InvalidArgumentException( - 'Invalid file permission: need permission to read and write by owner' - ); - } elseif ($filePermission & 0111) { - throw new Exception\InvalidArgumentException( - "Invalid file permission: Cache files shoudn't be executable" - ); - } - } - - if ($this->filePermission !== $filePermission) { - $this->triggerOptionEvent('file_permission', $filePermission); - $this->filePermission = $filePermission; - } - - return $this; - } - - /** - * Get permission to create files on unix systems - * - * @return false|int - */ - public function getFilePermission() - { - return $this->filePermission; - } - - /** - * Set namespace separator - * - * @param string $namespaceSeparator - * @return FilesystemOptions - */ - public function setNamespaceSeparator($namespaceSeparator) - { - $namespaceSeparator = (string) $namespaceSeparator; - $this->triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * Set no atime - * - * @param bool $noAtime - * @return FilesystemOptions - */ - public function setNoAtime($noAtime) - { - $noAtime = (bool) $noAtime; - $this->triggerOptionEvent('no_atime', $noAtime); - $this->noAtime = $noAtime; - return $this; - } - - /** - * Get no atime - * - * @return bool - */ - public function getNoAtime() - { - return $this->noAtime; - } - - /** - * Set no ctime - * - * @param bool $noCtime - * @return FilesystemOptions - */ - public function setNoCtime($noCtime) - { - $noCtime = (bool) $noCtime; - $this->triggerOptionEvent('no_ctime', $noCtime); - $this->noCtime = $noCtime; - return $this; - } - - /** - * Get no ctime - * - * @return bool - */ - public function getNoCtime() - { - return $this->noCtime; - } - - /** - * Set the umask to create files and directories on unix systems - * - * Note: On multithreaded webservers it's better to explicit set file and dir permission. - * - * @param false|string|int $umask FALSE to disable umask or an octal number - * @return FilesystemOptions - * @see setFilePermission - * @see setDirPermission - * @link http://php.net/manual/function.umask.php - * @link http://en.wikipedia.org/wiki/Umask - */ - public function setUmask($umask) - { - if ($umask !== false) { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int) $umask; - } - - // validate - if ($umask & 0700) { - throw new Exception\InvalidArgumentException( - 'Invalid umask: need permission to execute, read and write by owner' - ); - } - - // normalize - $umask = $umask & 0777; - } - - if ($this->umask !== $umask) { - $this->triggerOptionEvent('umask', $umask); - $this->umask = $umask; - } - - return $this; - } - - /** - * Get the umask to create files and directories on unix systems - * - * @return false|int - */ - public function getUmask() - { - return $this->umask; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/KeyListIterator.php b/library/Zend/Cache/Storage/Adapter/KeyListIterator.php deleted file mode 100755 index 86bcbe160..000000000 --- a/library/Zend/Cache/Storage/Adapter/KeyListIterator.php +++ /dev/null @@ -1,169 +0,0 @@ -storage = $storage; - $this->keys = $keys; - $this->count = count($keys); - } - - /** - * Get storage instance - * - * @return StorageInterface - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Get iterator mode - * - * @return int Value of IteratorInterface::CURRENT_AS_* - */ - public function getMode() - { - return $this->mode; - } - - /** - * Set iterator mode - * - * @param int $mode - * @return KeyListIterator Fluent interface - */ - public function setMode($mode) - { - $this->mode = (int) $mode; - return $this; - } - - /** - * Get current key, value or metadata. - * - * @return mixed - */ - public function current() - { - if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { - return $this; - } - - $key = $this->key(); - - if ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { - return $this->storage->getMetadata($key); - } elseif ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { - return $this->storage->getItem($key); - } - - return $key; - } - - /** - * Get current key - * - * @return string - */ - public function key() - { - return $this->keys[$this->position]; - } - - /** - * Checks if current position is valid - * - * @return bool - */ - public function valid() - { - return $this->position < $this->count; - } - - /** - * Move forward to next element - * - * @return void - */ - public function next() - { - $this->position++; - } - - /** - * Rewind the Iterator to the first element. - * - * @return void - */ - public function rewind() - { - $this->position = 0; - } - - /** - * Count number of items - * - * @return int - */ - public function count() - { - return $this->count; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Memcache.php b/library/Zend/Cache/Storage/Adapter/Memcache.php deleted file mode 100755 index 953e52cda..000000000 --- a/library/Zend/Cache/Storage/Adapter/Memcache.php +++ /dev/null @@ -1,574 +0,0 @@ - 0) { - throw new Exception\ExtensionNotLoadedException("Missing ext/memcache version >= 2.0.0"); - } - - parent::__construct($options); - - // reset initialized flag on update option(s) - $initialized = & $this->initialized; - $this->getEventManager()->attach('option', function ($event) use (& $initialized) { - $initialized = false; - }); - } - - /** - * Initialize the internal memcache resource - * - * @return MemcacheResource - */ - protected function getMemcacheResource() - { - if ($this->initialized) { - return $this->resourceManager->getResource($this->resourceId); - } - - $options = $this->getOptions(); - - // get resource manager and resource id - $this->resourceManager = $options->getResourceManager(); - $this->resourceId = $options->getResourceId(); - - // init namespace prefix - $this->namespacePrefix = ''; - $namespace = $options->getNamespace(); - if ($namespace !== '') { - $this->namespacePrefix = $namespace . $options->getNamespaceSeparator(); - } - - // update initialized flag - $this->initialized = true; - - return $this->resourceManager->getResource($this->resourceId); - } - - /* options */ - - /** - * Set options. - * - * @param array|Traversable|MemcacheOptions $options - * @return Memcache - * @see getOptions() - */ - public function setOptions($options) - { - if (!$options instanceof MemcacheOptions) { - $options = new MemcacheOptions($options); - } - - return parent::setOptions($options); - } - - /** - * Get options. - * - * @return MemcacheOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new MemcacheOptions()); - } - return $this->options; - } - - /** - * @param mixed $value - * @return int - */ - protected function getWriteFlag(& $value) - { - if (!$this->getOptions()->getCompression()) { - return 0; - } - // Don't compress numeric or boolean types - return (is_bool($value) || is_int($value) || is_float($value)) ? 0 : MEMCACHE_COMPRESSED; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - $memc = $this->getMemcacheResource(); - if (!$memc->flush()) { - return new Exception\RuntimeException("Memcache flush failed"); - } - return true; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - $memc = $this->getMemcacheResource(); - $stats = $memc->getExtendedStats(); - if ($stats === false) { - return new Exception\RuntimeException("Memcache getStats failed"); - } - - $mem = array_pop($stats); - return $mem['limit_maxbytes']; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $memc = $this->getMemcacheResource(); - $stats = $memc->getExtendedStats(); - if ($stats === false) { - throw new Exception\RuntimeException('Memcache getStats failed'); - } - - $mem = array_pop($stats); - return $mem['limit_maxbytes'] - $mem['bytes']; - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $memc = $this->getMemcacheResource(); - $internalKey = $this->namespacePrefix . $normalizedKey; - - $result = $memc->get($internalKey); - $success = ($result !== false); - if ($result === false) { - return null; - } - - $casToken = $result; - return $result; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $memc = $this->getMemcacheResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $result = $memc->get($normalizedKeys); - if ($result === false) { - return array(); - } - - // remove namespace prefix from result - if ($this->namespacePrefix !== '') { - $tmp = array(); - $nsPrefixLength = strlen($this->namespacePrefix); - foreach ($result as $internalKey => & $value) { - $tmp[substr($internalKey, $nsPrefixLength)] = & $value; - } - $result = $tmp; - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $memc = $this->getMemcacheResource(); - $value = $memc->get($this->namespacePrefix . $normalizedKey); - return ($value !== false); - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - */ - protected function internalHasItems(array & $normalizedKeys) - { - $memc = $this->getMemcacheResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $result = $memc->get($normalizedKeys); - if ($result === false) { - return array(); - } - - // Convert to a single list - $result = array_keys($result); - - // remove namespace prefix - if ($result && $this->namespacePrefix !== '') { - $nsPrefixLength = strlen($this->namespacePrefix); - foreach ($result as & $internalKey) { - $internalKey = substr($internalKey, $nsPrefixLength); - } - } - - return $result; - } - - /** - * Get metadata of multiple items - * - * @param array $normalizedKeys - * @return array Associative array of keys and metadata - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadatas(array & $normalizedKeys) - { - $memc = $this->getMemcacheResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $result = $memc->get($normalizedKeys); - if ($result === false) { - return array(); - } - - // remove namespace prefix and use an empty array as metadata - if ($this->namespacePrefix === '') { - foreach ($result as & $value) { - $value = array(); - } - return $result; - } - - $final = array(); - $nsPrefixLength = strlen($this->namespacePrefix); - foreach (array_keys($result) as $internalKey) { - $final[substr($internalKey, $nsPrefixLength)] = array(); - } - return $final; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcacheResource(); - $expiration = $this->expirationTime(); - $flag = $this->getWriteFlag($value); - - if (!$memc->set($this->namespacePrefix . $normalizedKey, $value, $flag, $expiration)) { - throw new Exception\RuntimeException('Memcache set value failed'); - } - - return true; - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcacheResource(); - $expiration = $this->expirationTime(); - $flag = $this->getWriteFlag($value); - - return $memc->add($this->namespacePrefix . $normalizedKey, $value, $flag, $expiration); - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcacheResource(); - $expiration = $this->expirationTime(); - $flag = $this->getWriteFlag($value); - - return $memc->replace($this->namespacePrefix . $normalizedKey, $value, $flag, $expiration); - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $memc = $this->getMemcacheResource(); - // Delete's second parameter (timeout) is deprecated and not supported. - // Values other than 0 may cause delete to fail. - // http://www.php.net/manual/memcache.delete.php - return $memc->delete($this->namespacePrefix . $normalizedKey, 0); - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcacheResource(); - $internalKey = $this->namespacePrefix . $normalizedKey; - $value = (int) $value; - $newValue = $memc->increment($internalKey, $value); - - if ($newValue !== false) { - return $newValue; - } - - // Set initial value. Don't use compression! - // http://www.php.net/manual/memcache.increment.php - $newValue = $value; - if (!$memc->add($internalKey, $newValue, 0, $this->expirationTime())) { - throw new Exception\RuntimeException('Memcache unable to add increment value'); - } - - return $newValue; - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcacheResource(); - $internalKey = $this->namespacePrefix . $normalizedKey; - $value = (int) $value; - $newValue = $memc->decrement($internalKey, $value); - - if ($newValue !== false) { - return $newValue; - } - - // Set initial value. Don't use compression! - // http://www.php.net/manual/memcache.decrement.php - $newValue = -$value; - if (!$memc->add($internalKey, $newValue, 0, $this->expirationTime())) { - throw new Exception\RuntimeException('Memcache unable to add decrement value'); - } - - return $newValue; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities !== null) { - return $this->capabilities; - } - - if (version_compare('3.0.3', phpversion('memcache')) <= 0) { - // In ext/memcache v3.0.3: - // Scalar data types (int, bool, double) are preserved by get/set. - // http://pecl.php.net/package/memcache/3.0.3 - // - // This effectively removes support for `boolean` types since - // "not found" return values are === false. - $supportedDatatypes = array( - 'NULL' => true, - 'boolean' => false, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ); - } else { - // In stable 2.x ext/memcache versions, scalar data types are - // converted to strings and must be manually cast back to original - // types by the user. - // - // ie. It is impossible to know if the saved value: (string)"1" - // was previously: (bool)true, (int)1, or (string)"1". - // Similarly, the saved value: (string)"" - // might have previously been: (bool)false or (string)"" - $supportedDatatypes = array( - 'NULL' => true, - 'boolean' => 'boolean', - 'integer' => 'integer', - 'double' => 'double', - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ); - } - - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this, - $this->capabilityMarker, - array( - 'supportedDatatypes' => $supportedDatatypes, - 'supportedMetadata' => array(), - 'minTtl' => 1, - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 255, - 'namespaceIsPrefix' => true, - ) - ); - - return $this->capabilities; - } - - /* internal */ - - /** - * Get expiration time by ttl - * - * Some storage commands involve sending an expiration value (relative to - * an item or to an operation requested by the client) to the server. In - * all such cases, the actual value sent may either be Unix time (number of - * seconds since January 1, 1970, as an integer), or a number of seconds - * starting from current time. In the latter case, this number of seconds - * may not exceed 60*60*24*30 (number of seconds in 30 days); if the - * expiration value is larger than that, the server will consider it to be - * real Unix time value rather than an offset from current time. - * - * @return int - */ - protected function expirationTime() - { - $ttl = $this->getOptions()->getTtl(); - if ($ttl > 2592000) { - return time() + $ttl; - } - return $ttl; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/MemcacheOptions.php b/library/Zend/Cache/Storage/Adapter/MemcacheOptions.php deleted file mode 100755 index 5fcdc3427..000000000 --- a/library/Zend/Cache/Storage/Adapter/MemcacheOptions.php +++ /dev/null @@ -1,284 +0,0 @@ -namespaceSeparator !== $namespaceSeparator) { - $this->triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - } - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * Set the memcache resource manager to use - * - * @param null|MemcacheResourceManager $resourceManager - * @return MemcacheOptions - */ - public function setResourceManager(MemcacheResourceManager $resourceManager = null) - { - if ($this->resourceManager !== $resourceManager) { - $this->triggerOptionEvent('resource_manager', $resourceManager); - $this->resourceManager = $resourceManager; - } - return $this; - } - - /** - * Get the memcache resource manager - * - * @return MemcacheResourceManager - */ - public function getResourceManager() - { - if (!$this->resourceManager) { - $this->resourceManager = new MemcacheResourceManager(); - } - return $this->resourceManager; - } - - /** - * Get the memcache resource id - * - * @return string - */ - public function getResourceId() - { - return $this->resourceId; - } - - /** - * Set the memcache resource id - * - * @param string $resourceId - * @return MemcacheOptions - */ - public function setResourceId($resourceId) - { - $resourceId = (string) $resourceId; - if ($this->resourceId !== $resourceId) { - $this->triggerOptionEvent('resource_id', $resourceId); - $this->resourceId = $resourceId; - } - return $this; - } - - /** - * Is compressed writes turned on? - * - * @return boolean - */ - public function getCompression() - { - return $this->compression; - } - - /** - * Set whether compressed writes are turned on or not - * - * @param boolean $compression - * @return $this - */ - public function setCompression($compression) - { - $compression = (bool) $compression; - if ($this->compression !== $compression) { - $this->triggerOptionEvent('compression', $compression); - $this->compression = $compression; - } - return $this; - } - - /** - * Sets a list of memcache servers to add on initialize - * - * @param string|array $servers list of servers - * @return MemcacheOptions - * @throws Exception\InvalidArgumentException - */ - public function setServers($servers) - { - $this->getResourceManager()->addServers($this->getResourceId(), $servers); - return $this; - } - - /** - * Get Servers - * - * @return array - */ - public function getServers() - { - return $this->getResourceManager()->getServers($this->getResourceId()); - } - - /** - * Set compress threshold - * - * @param int|string|array|\ArrayAccess|null $threshold - * @return MemcacheOptions - */ - public function setAutoCompressThreshold($threshold) - { - $this->getResourceManager()->setAutoCompressThreshold($this->getResourceId(), $threshold); - return $this; - } - - /** - * Get compress threshold - * - * @return int|null - */ - public function getAutoCompressThreshold() - { - return $this->getResourceManager()->getAutoCompressThreshold($this->getResourceId()); - } - - /** - * Set compress min savings option - * - * @param float|string|null $minSavings - * @return MemcacheOptions - */ - public function setAutoCompressMinSavings($minSavings) - { - $this->getResourceManager()->setAutoCompressMinSavings($this->getResourceId(), $minSavings); - return $this; - } - - /** - * Get compress min savings - * - * @return Exception\RuntimeException - */ - public function getAutoCompressMinSavings() - { - return $this->getResourceManager()->getAutoCompressMinSavings($this->getResourceId()); - } - - /** - * Set default server values - * - * @param array $serverDefaults - * @return MemcacheOptions - */ - public function setServerDefaults(array $serverDefaults) - { - $this->getResourceManager()->setServerDefaults($this->getResourceId(), $serverDefaults); - return $this; - } - - /** - * Get default server values - * - * @return array - */ - public function getServerDefaults() - { - return $this->getResourceManager()->getServerDefaults($this->getResourceId()); - } - - /** - * Set callback for server connection failures - * - * @param callable $callback - * @return $this - */ - public function setFailureCallback($callback) - { - $this->getResourceManager()->setFailureCallback($this->getResourceId(), $callback); - return $this; - } - - /** - * Get callback for server connection failures - * - * @return callable - */ - public function getFailureCallback() - { - return $this->getResourceManager()->getFailureCallback($this->getResourceId()); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/MemcacheResourceManager.php b/library/Zend/Cache/Storage/Adapter/MemcacheResourceManager.php deleted file mode 100755 index 1fbff1828..000000000 --- a/library/Zend/Cache/Storage/Adapter/MemcacheResourceManager.php +++ /dev/null @@ -1,646 +0,0 @@ -resources[$id]); - } - - /** - * Gets a memcache resource - * - * @param string $id - * @return MemcacheResource - * @throws Exception\RuntimeException - */ - public function getResource($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - return $resource; - } - - $memc = new MemcacheResource(); - $this->setResourceAutoCompressThreshold( - $memc, - $resource['auto_compress_threshold'], - $resource['auto_compress_min_savings'] - ); - foreach ($resource['servers'] as $server) { - $this->addServerToResource( - $memc, - $server, - $this->serverDefaults[$id], - $this->failureCallbacks[$id] - ); - } - - // buffer and return - $this->resources[$id] = $memc; - return $memc; - } - - /** - * Set a resource - * - * @param string $id - * @param array|Traversable|MemcacheResource $resource - * @return MemcacheResourceManager - */ - public function setResource($id, $resource, $failureCallback = null, $serverDefaults = array()) - { - $id = (string) $id; - - if ($serverDefaults instanceof Traversable) { - $serverDefaults = ArrayUtils::iteratorToArray($serverDefaults); - } elseif (!is_array($serverDefaults)) { - throw new Exception\InvalidArgumentException( - 'ServerDefaults must be an instance Traversable or an array' - ); - } - - if (!($resource instanceof MemcacheResource)) { - if ($resource instanceof Traversable) { - $resource = ArrayUtils::iteratorToArray($resource); - } elseif (!is_array($resource)) { - throw new Exception\InvalidArgumentException( - 'Resource must be an instance of Memcache or an array or Traversable' - ); - } - - if (isset($resource['server_defaults'])) { - $serverDefaults = array_merge($serverDefaults, $resource['server_defaults']); - unset($resource['server_defaults']); - } - - $resourceOptions = array( - 'servers' => array(), - 'auto_compress_threshold' => null, - 'auto_compress_min_savings' => null, - ); - $resource = array_merge($resourceOptions, $resource); - - // normalize and validate params - $this->normalizeAutoCompressThreshold( - $resource['auto_compress_threshold'], - $resource['auto_compress_min_savings'] - ); - $this->normalizeServers($resource['servers']); - } - - $this->normalizeServerDefaults($serverDefaults); - - $this->resources[$id] = $resource; - $this->failureCallbacks[$id] = $failureCallback; - $this->serverDefaults[$id] = $serverDefaults; - - return $this; - } - - /** - * Remove a resource - * - * @param string $id - * @return MemcacheResourceManager - */ - public function removeResource($id) - { - unset($this->resources[$id]); - return $this; - } - - /** - * Normalize compress threshold options - * - * @param int|string|array|ArrayAccess $threshold - * @param float|string $minSavings - */ - protected function normalizeAutoCompressThreshold(& $threshold, & $minSavings) - { - if (is_array($threshold) || ($threshold instanceof ArrayAccess)) { - $tmpThreshold = (isset($threshold['threshold'])) ? $threshold['threshold'] : null; - $minSavings = (isset($threshold['min_savings'])) ? $threshold['min_savings'] : $minSavings; - $threshold = $tmpThreshold; - } - if (isset($threshold)) { - $threshold = (int) $threshold; - } - if (isset($minSavings)) { - $minSavings = (float) $minSavings; - } - } - - /** - * Set compress threshold on a Memcache resource - * - * @param MemcacheResource $resource - * @param array $libOptions - */ - protected function setResourceAutoCompressThreshold(MemcacheResource $resource, $threshold, $minSavings) - { - if (!isset($threshold)) { - return; - } - if (isset($minSavings)) { - $resource->setCompressThreshold($threshold, $minSavings); - } else { - $resource->setCompressThreshold($threshold); - } - } - - /** - * Get compress threshold - * - * @param string $id - * @return int|null - * @throws \Zend\Cache\Exception\RuntimeException - */ - public function getAutoCompressThreshold($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - // Cannot get options from Memcache resource once created - throw new Exception\RuntimeException("Cannot get compress threshold once resource is created"); - } - return $resource['auto_compress_threshold']; - } - - /** - * Set compress threshold - * - * @param string $id - * @param int|string|array|ArrayAccess|null $threshold - * @param float|string|bool $minSavings - * @return MemcacheResourceManager - */ - public function setAutoCompressThreshold($id, $threshold, $minSavings = false) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'auto_compress_threshold' => $threshold, - )); - } - - $this->normalizeAutoCompressThreshold($threshold, $minSavings); - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - $this->setResourceAutoCompressThreshold($resource, $threshold, $minSavings); - } else { - $resource['auto_compress_threshold'] = $threshold; - if ($minSavings !== false) { - $resource['auto_compress_min_savings'] = $minSavings; - } - } - return $this; - } - - /** - * Get compress min savings - * - * @param string $id - * @return float|null - * @throws Exception\RuntimeException - */ - public function getAutoCompressMinSavings($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - // Cannot get options from Memcache resource once created - throw new Exception\RuntimeException("Cannot get compress min savings once resource is created"); - } - return $resource['auto_compress_min_savings']; - } - - /** - * Set compress min savings - * - * @param string $id - * @param float|string|null $minSavings - * @return MemcacheResourceManager - * @throws \Zend\Cache\Exception\RuntimeException - */ - public function setAutoCompressMinSavings($id, $minSavings) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'auto_compress_min_savings' => $minSavings, - )); - } - - $minSavings = (float) $minSavings; - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - throw new Exception\RuntimeException( - "Cannot set compress min savings without a threshold value once a resource is created" - ); - } else { - $resource['auto_compress_min_savings'] = $minSavings; - } - return $this; - } - - /** - * Set default server values - * array( - * 'persistent' => , 'weight' => , - * 'timeout' => , 'retry_interval' => , - * ) - * @param string $id - * @param array $serverDefaults - * @return MemcacheResourceManager - */ - public function setServerDefaults($id, array $serverDefaults) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'server_defaults' => $serverDefaults - )); - } - - $this->normalizeServerDefaults($serverDefaults); - $this->serverDefaults[$id] = $serverDefaults; - - return $this; - } - - /** - * Get default server values - * - * @param string $id - * @return array - * @throws Exception\RuntimeException - */ - public function getServerDefaults($id) - { - if (!isset($this->serverDefaults[$id])) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - return $this->serverDefaults[$id]; - } - - /** - * @param array $serverDefaults - * @throws Exception\InvalidArgumentException - */ - protected function normalizeServerDefaults(& $serverDefaults) - { - if (!is_array($serverDefaults) && !($serverDefaults instanceof Traversable)) { - throw new Exception\InvalidArgumentException( - "Server defaults must be an array or an instance of Traversable" - ); - } - - // Defaults - $result = array( - 'persistent' => true, - 'weight' => 1, - 'timeout' => 1, // seconds - 'retry_interval' => 15, // seconds - ); - - foreach ($serverDefaults as $key => $value) { - switch ($key) { - case 'persistent': - $value = (bool) $value; - break; - case 'weight': - case 'timeout': - case 'retry_interval': - $value = (int) $value; - break; - } - $result[$key] = $value; - } - - $serverDefaults = $result; - } - - /** - * Set callback for server connection failures - * - * @param string $id - * @param callable|null $failureCallback - * @return MemcacheResourceManager - */ - public function setFailureCallback($id, $failureCallback) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array(), $failureCallback); - } - - $this->failureCallbacks[$id] = $failureCallback; - return $this; - } - - /** - * Get callback for server connection failures - * - * @param string $id - * @return callable|null - * @throws Exception\RuntimeException - */ - public function getFailureCallback($id) - { - if (!isset($this->failureCallbacks[$id])) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - return $this->failureCallbacks[$id]; - } - - /** - * Get servers - * - * @param string $id - * @throws Exception\RuntimeException - * @return array array('host' => , 'port' => , 'weight' => ) - */ - public function getServers($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - throw new Exception\RuntimeException("Cannot get server list once resource is created"); - } - return $resource['servers']; - } - - /** - * Add servers - * - * @param string $id - * @param string|array $servers - * @return MemcacheResourceManager - */ - public function addServers($id, $servers) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'servers' => $servers - )); - } - - $this->normalizeServers($servers); - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcacheResource) { - foreach ($servers as $server) { - $this->addServerToResource( - $resource, - $server, - $this->serverDefaults[$id], - $this->failureCallbacks[$id] - ); - } - } else { - // don't add servers twice - $resource['servers'] = array_merge( - $resource['servers'], - array_udiff($servers, $resource['servers'], array($this, 'compareServers')) - ); - } - - return $this; - } - - /** - * Add one server - * - * @param string $id - * @param string|array $server - * @return MemcacheResourceManager - */ - public function addServer($id, $server) - { - return $this->addServers($id, array($server)); - } - - /** - * @param MemcacheResource $resource - * @param array $server - * @param array $serverDefaults - * @param callable|null $failureCallback - */ - protected function addServerToResource( - MemcacheResource $resource, - array $server, - array $serverDefaults, - $failureCallback - ) { - // Apply server defaults - $server = array_merge($serverDefaults, $server); - - // Reorder parameters - $params = array( - $server['host'], - $server['port'], - $server['persistent'], - $server['weight'], - $server['timeout'], - $server['retry_interval'], - $server['status'], - ); - if (isset($failureCallback)) { - $params[] = $failureCallback; - } - call_user_func_array(array($resource, 'addServer'), $params); - } - - /** - * Normalize a list of servers into the following format: - * array(array('host' => , 'port' => , 'weight' => )[, ...]) - * - * @param string|array $servers - */ - protected function normalizeServers(& $servers) - { - if (is_string($servers)) { - // Convert string into a list of servers - $servers = explode(',', $servers); - } - - $result = array(); - foreach ($servers as $server) { - $this->normalizeServer($server); - $result[$server['host'] . ':' . $server['port']] = $server; - } - - $servers = array_values($result); - } - - /** - * Normalize one server into the following format: - * array( - * 'host' => , 'port' => , 'weight' => , - * 'status' => , 'persistent' => , - * 'timeout' => , 'retry_interval' => , - * ) - * - * @param string|array $server - * @throws Exception\InvalidArgumentException - */ - protected function normalizeServer(& $server) - { - // WARNING: The order of this array is important. - // Used for converting an ordered array to a keyed array. - // Append new options, do not insert or you will break BC. - $sTmp = array( - 'host' => null, - 'port' => 11211, - 'weight' => null, - 'status' => true, - 'persistent' => null, - 'timeout' => null, - 'retry_interval' => null, - ); - - // convert a single server into an array - if ($server instanceof Traversable) { - $server = ArrayUtils::iteratorToArray($server); - } - - if (is_array($server)) { - if (isset($server[0])) { - // Convert ordered array to keyed array - // array([, [, [, [, [, [, ]]]]]]) - $server = array_combine( - array_slice(array_keys($sTmp), 0, count($server)), - $server - ); - } - $sTmp = array_merge($sTmp, $server); - } elseif (is_string($server)) { - // parse server from URI host{:?port}{?weight} - $server = trim($server); - if (strpos($server, '://') === false) { - $server = 'tcp://' . $server; - } - - $urlParts = parse_url($server); - if (!$urlParts) { - throw new Exception\InvalidArgumentException("Invalid server given"); - } - - $sTmp = array_merge($sTmp, array_intersect_key($urlParts, $sTmp)); - if (isset($urlParts['query'])) { - $query = null; - parse_str($urlParts['query'], $query); - $sTmp = array_merge($sTmp, array_intersect_key($query, $sTmp)); - } - } - - if (!$sTmp['host']) { - throw new Exception\InvalidArgumentException('Missing required server host'); - } - - // Filter values - foreach ($sTmp as $key => $value) { - if (isset($value)) { - switch ($key) { - case 'host': - $value = (string) $value; - break; - case 'status': - case 'persistent': - $value = (bool) $value; - break; - case 'port': - case 'weight': - case 'timeout': - case 'retry_interval': - $value = (int) $value; - break; - } - } - $sTmp[$key] = $value; - } - $sTmp = array_filter( - $sTmp, - function ($val) { - return isset($val); - } - ); - - $server = $sTmp; - } - - /** - * Compare 2 normalized server arrays - * (Compares only the host and the port) - * - * @param array $serverA - * @param array $serverB - * @return int - */ - protected function compareServers(array $serverA, array $serverB) - { - $keyA = $serverA['host'] . ':' . $serverA['port']; - $keyB = $serverB['host'] . ':' . $serverB['port']; - if ($keyA === $keyB) { - return 0; - } - return $keyA > $keyB ? 1 : -1; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Memcached.php b/library/Zend/Cache/Storage/Adapter/Memcached.php deleted file mode 100755 index 54bbed783..000000000 --- a/library/Zend/Cache/Storage/Adapter/Memcached.php +++ /dev/null @@ -1,703 +0,0 @@ -= 1.0.0'); - } - - parent::__construct($options); - - // reset initialized flag on update option(s) - $initialized = & $this->initialized; - $this->getEventManager()->attach('option', function ($event) use (& $initialized) { - $initialized = false; - }); - } - - /** - * Initialize the internal memcached resource - * - * @return MemcachedResource - */ - protected function getMemcachedResource() - { - if (!$this->initialized) { - $options = $this->getOptions(); - - // get resource manager and resource id - $this->resourceManager = $options->getResourceManager(); - $this->resourceId = $options->getResourceId(); - - // init namespace prefix - $namespace = $options->getNamespace(); - if ($namespace !== '') { - $this->namespacePrefix = $namespace . $options->getNamespaceSeparator(); - } else { - $this->namespacePrefix = ''; - } - - // update initialized flag - $this->initialized = true; - } - - return $this->resourceManager->getResource($this->resourceId); - } - - /* options */ - - /** - * Set options. - * - * @param array|Traversable|MemcachedOptions $options - * @return Memcached - * @see getOptions() - */ - public function setOptions($options) - { - if (!$options instanceof MemcachedOptions) { - $options = new MemcachedOptions($options); - } - - return parent::setOptions($options); - } - - /** - * Get options. - * - * @return MemcachedOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new MemcachedOptions()); - } - return $this->options; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - $memc = $this->getMemcachedResource(); - if (!$memc->flush()) { - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - return true; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - $memc = $this->getMemcachedResource(); - $stats = $memc->getStats(); - if ($stats === false) { - throw new Exception\RuntimeException($memc->getResultMessage()); - } - - $mem = array_pop($stats); - return $mem['limit_maxbytes']; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $memc = $this->getMemcachedResource(); - $stats = $memc->getStats(); - if ($stats === false) { - throw new Exception\RuntimeException($memc->getResultMessage()); - } - - $mem = array_pop($stats); - return $mem['limit_maxbytes'] - $mem['bytes']; - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $memc = $this->getMemcachedResource(); - $internalKey = $this->namespacePrefix . $normalizedKey; - - if (func_num_args() > 2) { - $result = $memc->get($internalKey, null, $casToken); - } else { - $result = $memc->get($internalKey); - } - - $success = true; - if ($result === false) { - $rsCode = $memc->getResultCode(); - if ($rsCode == MemcachedResource::RES_NOTFOUND) { - $result = null; - $success = false; - } elseif ($rsCode) { - $success = false; - throw $this->getExceptionByResultCode($rsCode); - } - } - - return $result; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $memc = $this->getMemcachedResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $result = $memc->getMulti($normalizedKeys); - if ($result === false) { - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - - // remove namespace prefix from result - if ($result && $this->namespacePrefix !== '') { - $tmp = array(); - $nsPrefixLength = strlen($this->namespacePrefix); - foreach ($result as $internalKey => & $value) { - $tmp[substr($internalKey, $nsPrefixLength)] = & $value; - } - $result = $tmp; - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $memc = $this->getMemcachedResource(); - $value = $memc->get($this->namespacePrefix . $normalizedKey); - if ($value === false) { - $rsCode = $memc->getResultCode(); - if ($rsCode == MemcachedResource::RES_SUCCESS) { - return true; - } elseif ($rsCode == MemcachedResource::RES_NOTFOUND) { - return false; - } else { - throw $this->getExceptionByResultCode($rsCode); - } - } - - return true; - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - * @throws Exception\ExceptionInterface - */ - protected function internalHasItems(array & $normalizedKeys) - { - $memc = $this->getMemcachedResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $result = $memc->getMulti($normalizedKeys); - if ($result === false) { - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - - // Convert to a simgle list - $result = array_keys($result); - - // remove namespace prefix - if ($result && $this->namespacePrefix !== '') { - $nsPrefixLength = strlen($this->namespacePrefix); - foreach ($result as & $internalKey) { - $internalKey = substr($internalKey, $nsPrefixLength); - } - } - - return $result; - } - - /** - * Get metadata of multiple items - * - * @param array $normalizedKeys - * @return array Associative array of keys and metadata - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadatas(array & $normalizedKeys) - { - $memc = $this->getMemcachedResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $result = $memc->getMulti($normalizedKeys); - if ($result === false) { - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - - // remove namespace prefix and use an empty array as metadata - if ($this->namespacePrefix !== '') { - $tmp = array(); - $nsPrefixLength = strlen($this->namespacePrefix); - foreach (array_keys($result) as $internalKey) { - $tmp[substr($internalKey, $nsPrefixLength)] = array(); - } - $result = $tmp; - } else { - foreach ($result as & $value) { - $value = array(); - } - } - - return $result; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcachedResource(); - $expiration = $this->expirationTime(); - if (!$memc->set($this->namespacePrefix . $normalizedKey, $value, $expiration)) { - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - - return true; - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $memc = $this->getMemcachedResource(); - $expiration = $this->expirationTime(); - - $namespacedKeyValuePairs = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => & $value) { - $namespacedKeyValuePairs[$this->namespacePrefix . $normalizedKey] = & $value; - } - - if (!$memc->setMulti($namespacedKeyValuePairs, $expiration)) { - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - - return array(); - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcachedResource(); - $expiration = $this->expirationTime(); - if (!$memc->add($this->namespacePrefix . $normalizedKey, $value, $expiration)) { - if ($memc->getResultCode() == MemcachedResource::RES_NOTSTORED) { - return false; - } - throw $this->getExceptionByResultCode($memc->getResultCode()); - } - - return true; - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcachedResource(); - $expiration = $this->expirationTime(); - if (!$memc->replace($this->namespacePrefix . $normalizedKey, $value, $expiration)) { - $rsCode = $memc->getResultCode(); - if ($rsCode == MemcachedResource::RES_NOTSTORED) { - return false; - } - throw $this->getExceptionByResultCode($rsCode); - } - - return true; - } - - /** - * Internal method to set an item only if token matches - * - * @param mixed $token - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - * @see getItem() - * @see setItem() - */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) - { - $memc = $this->getMemcachedResource(); - $expiration = $this->expirationTime(); - $result = $memc->cas($token, $this->namespacePrefix . $normalizedKey, $value, $expiration); - - if ($result === false) { - $rsCode = $memc->getResultCode(); - if ($rsCode !== 0 && $rsCode != MemcachedResource::RES_DATA_EXISTS) { - throw $this->getExceptionByResultCode($rsCode); - } - } - - return $result; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $memc = $this->getMemcachedResource(); - $result = $memc->delete($this->namespacePrefix . $normalizedKey); - - if ($result === false) { - $rsCode = $memc->getResultCode(); - if ($rsCode == MemcachedResource::RES_NOTFOUND) { - return false; - } elseif ($rsCode != MemcachedResource::RES_SUCCESS) { - throw $this->getExceptionByResultCode($rsCode); - } - } - - return true; - } - - /** - * Internal method to remove multiple items. - * - * @param array $normalizedKeys - * @return array Array of not removed keys - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItems(array & $normalizedKeys) - { - // support for removing multiple items at once has been added in ext/memcached-2.0.0 - if (static::$extMemcachedMajorVersion < 2) { - return parent::internalRemoveItems($normalizedKeys); - } - - $memc = $this->getMemcachedResource(); - - foreach ($normalizedKeys as & $normalizedKey) { - $normalizedKey = $this->namespacePrefix . $normalizedKey; - } - - $rsCodes = $memc->deleteMulti($normalizedKeys); - - $missingKeys = array(); - foreach ($rsCodes as $key => $rsCode) { - if ($rsCode !== true && $rsCode != MemcachedResource::RES_SUCCESS) { - if ($rsCode != MemcachedResource::RES_NOTFOUND) { - throw $this->getExceptionByResultCode($rsCode); - } - $missingKeys[] = $key; - } - } - - // remove namespace prefix - if ($missingKeys && $this->namespacePrefix !== '') { - $nsPrefixLength = strlen($this->namespacePrefix); - foreach ($missingKeys as & $missingKey) { - $missingKey = substr($missingKey, $nsPrefixLength); - } - } - - return $missingKeys; - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcachedResource(); - $internalKey = $this->namespacePrefix . $normalizedKey; - $value = (int) $value; - $newValue = $memc->increment($internalKey, $value); - - if ($newValue === false) { - $rsCode = $memc->getResultCode(); - - // initial value - if ($rsCode == MemcachedResource::RES_NOTFOUND) { - $newValue = $value; - $memc->add($internalKey, $newValue, $this->expirationTime()); - $rsCode = $memc->getResultCode(); - } - - if ($rsCode) { - throw $this->getExceptionByResultCode($rsCode); - } - } - - return $newValue; - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $memc = $this->getMemcachedResource(); - $internalKey = $this->namespacePrefix . $normalizedKey; - $value = (int) $value; - $newValue = $memc->decrement($internalKey, $value); - - if ($newValue === false) { - $rsCode = $memc->getResultCode(); - - // initial value - if ($rsCode == MemcachedResource::RES_NOTFOUND) { - $newValue = -$value; - $memc->add($internalKey, $newValue, $this->expirationTime()); - $rsCode = $memc->getResultCode(); - } - - if ($rsCode) { - throw $this->getExceptionByResultCode($rsCode); - } - } - - return $newValue; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this, - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'minTtl' => 1, - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 255, - 'namespaceIsPrefix' => true, - ) - ); - } - - return $this->capabilities; - } - - /* internal */ - - /** - * Get expiration time by ttl - * - * Some storage commands involve sending an expiration value (relative to - * an item or to an operation requested by the client) to the server. In - * all such cases, the actual value sent may either be Unix time (number of - * seconds since January 1, 1970, as an integer), or a number of seconds - * starting from current time. In the latter case, this number of seconds - * may not exceed 60*60*24*30 (number of seconds in 30 days); if the - * expiration value is larger than that, the server will consider it to be - * real Unix time value rather than an offset from current time. - * - * @return int - */ - protected function expirationTime() - { - $ttl = $this->getOptions()->getTtl(); - if ($ttl > 2592000) { - return time() + $ttl; - } - return $ttl; - } - - /** - * Generate exception based of memcached result code - * - * @param int $code - * @return Exception\RuntimeException - * @throws Exception\InvalidArgumentException On success code - */ - protected function getExceptionByResultCode($code) - { - switch ($code) { - case MemcachedResource::RES_SUCCESS: - throw new Exception\InvalidArgumentException( - "The result code '{$code}' (SUCCESS) isn't an error" - ); - - default: - return new Exception\RuntimeException($this->getMemcachedResource()->getResultMessage()); - } - } -} diff --git a/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php b/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php deleted file mode 100755 index fabf3033d..000000000 --- a/library/Zend/Cache/Storage/Adapter/MemcachedOptions.php +++ /dev/null @@ -1,319 +0,0 @@ -namespaceSeparator !== $namespaceSeparator) { - $this->triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - } - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * A memcached resource to share - * - * @param null|MemcachedResource $memcachedResource - * @return MemcachedOptions - * @deprecated Please use the resource manager instead - */ - public function setMemcachedResource(MemcachedResource $memcachedResource = null) - { - trigger_error( - 'This method is deprecated and will be removed in the feature' - . ', please use the resource manager instead', - E_USER_DEPRECATED - ); - - if ($memcachedResource !== null) { - $this->triggerOptionEvent('memcached_resource', $memcachedResource); - $resourceManager = $this->getResourceManager(); - $resourceId = $this->getResourceId(); - $resourceManager->setResource($resourceId, $memcachedResource); - } - return $this; - } - - /** - * Get memcached resource to share - * - * @return MemcachedResource - * @deprecated Please use the resource manager instead - */ - public function getMemcachedResource() - { - trigger_error( - 'This method is deprecated and will be removed in the feature' - . ', please use the resource manager instead', - E_USER_DEPRECATED - ); - - return $this->resourceManager->getResource($this->getResourceId()); - } - - /** - * Set the memcached resource manager to use - * - * @param null|MemcachedResourceManager $resourceManager - * @return MemcachedOptions - */ - public function setResourceManager(MemcachedResourceManager $resourceManager = null) - { - if ($this->resourceManager !== $resourceManager) { - $this->triggerOptionEvent('resource_manager', $resourceManager); - $this->resourceManager = $resourceManager; - } - return $this; - } - - /** - * Get the memcached resource manager - * - * @return MemcachedResourceManager - */ - public function getResourceManager() - { - if (!$this->resourceManager) { - $this->resourceManager = new MemcachedResourceManager(); - } - return $this->resourceManager; - } - - /** - * Get the memcached resource id - * - * @return string - */ - public function getResourceId() - { - return $this->resourceId; - } - - /** - * Set the memcached resource id - * - * @param string $resourceId - * @return MemcachedOptions - */ - public function setResourceId($resourceId) - { - $resourceId = (string) $resourceId; - if ($this->resourceId !== $resourceId) { - $this->triggerOptionEvent('resource_id', $resourceId); - $this->resourceId = $resourceId; - } - return $this; - } - - /** - * Get the persistent id - * - * @return string - */ - public function getPersistentId() - { - return $this->getResourceManager()->getPersistentId($this->getResourceId()); - } - - /** - * Set the persistent id - * - * @param string $persistentId - * @return MemcachedOptions - */ - public function setPersistentId($persistentId) - { - $this->triggerOptionEvent('persistent_id', $persistentId); - $this->getResourceManager()->setPersistentId($this->getResourceId(), $persistentId); - return $this; - } - - /** - * Add a server to the list - * - * @param string $host - * @param int $port - * @param int $weight - * @return MemcachedOptions - * @deprecated Please use the resource manager instead - */ - public function addServer($host, $port = 11211, $weight = 0) - { - trigger_error( - 'This method is deprecated and will be removed in the feature' - . ', please use the resource manager instead', - E_USER_DEPRECATED - ); - - $this->getResourceManager()->addServer($this->getResourceId(), array( - 'host' => $host, - 'port' => $port, - 'weight' => $weight - )); - - return $this; - } - - /** - * Set a list of memcached servers to add on initialize - * - * @param string|array $servers list of servers - * @return MemcachedOptions - * @throws Exception\InvalidArgumentException - */ - public function setServers($servers) - { - $this->getResourceManager()->setServers($this->getResourceId(), $servers); - return $this; - } - - /** - * Get Servers - * - * @return array - */ - public function getServers() - { - return $this->getResourceManager()->getServers($this->getResourceId()); - } - - /** - * Set libmemcached options - * - * @param array $libOptions - * @return MemcachedOptions - * @link http://php.net/manual/memcached.constants.php - */ - public function setLibOptions(array $libOptions) - { - $this->getResourceManager()->setLibOptions($this->getResourceId(), $libOptions); - return $this; - } - - /** - * Set libmemcached option - * - * @param string|int $key - * @param mixed $value - * @return MemcachedOptions - * @link http://php.net/manual/memcached.constants.php - * @deprecated Please use lib_options or the resource manager instead - */ - public function setLibOption($key, $value) - { - trigger_error( - 'This method is deprecated and will be removed in the feature' - . ', please use "lib_options" or the resource manager instead', - E_USER_DEPRECATED - ); - - $this->getResourceManager()->setLibOption($this->getResourceId(), $key, $value); - return $this; - } - - /** - * Get libmemcached options - * - * @return array - * @link http://php.net/manual/memcached.constants.php - */ - public function getLibOptions() - { - return $this->getResourceManager()->getLibOptions($this->getResourceId()); - } - - /** - * Get libmemcached option - * - * @param string|int $key - * @return mixed - * @link http://php.net/manual/memcached.constants.php - * @deprecated Please use lib_options or the resource manager instead - */ - public function getLibOption($key) - { - trigger_error( - 'This method is deprecated and will be removed in the feature' - . ', please use "lib_options" or the resource manager instead', - E_USER_DEPRECATED - ); - - return $this->getResourceManager()->getLibOption($this->getResourceId(), $key); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/MemcachedResourceManager.php b/library/Zend/Cache/Storage/Adapter/MemcachedResourceManager.php deleted file mode 100755 index 10edb99ae..000000000 --- a/library/Zend/Cache/Storage/Adapter/MemcachedResourceManager.php +++ /dev/null @@ -1,547 +0,0 @@ - , 'port' => , 'weight' => ) - */ - public function getServers($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - - if ($resource instanceof MemcachedResource) { - return $resource->getServerList(); - } - return $resource['servers']; - } - - /** - * Normalize one server into the following format: - * array('host' => , 'port' => , 'weight' => ) - * - * @param string|array &$server - * @throws Exception\InvalidArgumentException - */ - protected function normalizeServer(&$server) - { - $host = null; - $port = 11211; - $weight = 0; - - // convert a single server into an array - if ($server instanceof Traversable) { - $server = ArrayUtils::iteratorToArray($server); - } - - if (is_array($server)) { - // array([, [, ]]) - if (isset($server[0])) { - $host = (string) $server[0]; - $port = isset($server[1]) ? (int) $server[1] : $port; - $weight = isset($server[2]) ? (int) $server[2] : $weight; - } - - // array('host' => [, 'port' => [, 'weight' => ]]) - if (!isset($server[0]) && isset($server['host'])) { - $host = (string) $server['host']; - $port = isset($server['port']) ? (int) $server['port'] : $port; - $weight = isset($server['weight']) ? (int) $server['weight'] : $weight; - } - } else { - // parse server from URI host{:?port}{?weight} - $server = trim($server); - if (strpos($server, '://') === false) { - $server = 'tcp://' . $server; - } - - $server = parse_url($server); - if (!$server) { - throw new Exception\InvalidArgumentException("Invalid server given"); - } - - $host = $server['host']; - $port = isset($server['port']) ? (int) $server['port'] : $port; - - if (isset($server['query'])) { - $query = null; - parse_str($server['query'], $query); - if (isset($query['weight'])) { - $weight = (int) $query['weight']; - } - } - } - - if (!$host) { - throw new Exception\InvalidArgumentException('Missing required server host'); - } - - $server = array( - 'host' => $host, - 'port' => $port, - 'weight' => $weight, - ); - } - - /** - * Check if a resource exists - * - * @param string $id - * @return bool - */ - public function hasResource($id) - { - return isset($this->resources[$id]); - } - - /** - * Gets a memcached resource - * - * @param string $id - * @return MemcachedResource - * @throws Exception\RuntimeException - */ - public function getResource($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = $this->resources[$id]; - if ($resource instanceof MemcachedResource) { - return $resource; - } - - if ($resource['persistent_id'] !== '') { - $memc = new MemcachedResource($resource['persistent_id']); - } else { - $memc = new MemcachedResource(); - } - - if (method_exists($memc, 'setOptions')) { - $memc->setOptions($resource['lib_options']); - } else { - foreach ($resource['lib_options'] as $k => $v) { - $memc->setOption($k, $v); - } - } - - // merge and add servers (with persistence id servers could be added already) - $servers = array_udiff($resource['servers'], $memc->getServerList(), array($this, 'compareServers')); - if ($servers) { - $memc->addServers($servers); - } - - // buffer and return - $this->resources[$id] = $memc; - return $memc; - } - - /** - * Set a resource - * - * @param string $id - * @param array|Traversable|MemcachedResource $resource - * @return MemcachedResourceManager Fluent interface - */ - public function setResource($id, $resource) - { - $id = (string) $id; - - if (!($resource instanceof MemcachedResource)) { - if ($resource instanceof Traversable) { - $resource = ArrayUtils::iteratorToArray($resource); - } elseif (!is_array($resource)) { - throw new Exception\InvalidArgumentException( - 'Resource must be an instance of Memcached or an array or Traversable' - ); - } - - $resource = array_merge(array( - 'persistent_id' => '', - 'lib_options' => array(), - 'servers' => array(), - ), $resource); - - // normalize and validate params - $this->normalizePersistentId($resource['persistent_id']); - $this->normalizeLibOptions($resource['lib_options']); - $this->normalizeServers($resource['servers']); - } - - $this->resources[$id] = $resource; - return $this; - } - - /** - * Remove a resource - * - * @param string $id - * @return MemcachedResourceManager Fluent interface - */ - public function removeResource($id) - { - unset($this->resources[$id]); - return $this; - } - - /** - * Set the persistent id - * - * @param string $id - * @param string $persistentId - * @return MemcachedResourceManager Fluent interface - * @throws Exception\RuntimeException - */ - public function setPersistentId($id, $persistentId) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'persistent_id' => $persistentId - )); - } - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcachedResource) { - throw new Exception\RuntimeException( - "Can't change persistent id of resource {$id} after instanziation" - ); - } - - $this->normalizePersistentId($persistentId); - $resource['persistent_id'] = $persistentId; - - return $this; - } - - /** - * Get the persistent id - * - * @param string $id - * @return string - * @throws Exception\RuntimeException - */ - public function getPersistentId($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - - if ($resource instanceof MemcachedResource) { - throw new Exception\RuntimeException( - "Can't get persistent id of an instantiated memcached resource" - ); - } - - return $resource['persistent_id']; - } - - /** - * Normalize the persistent id - * - * @param string $persistentId - */ - protected function normalizePersistentId(& $persistentId) - { - $persistentId = (string) $persistentId; - } - - /** - * Set Libmemcached options - * - * @param string $id - * @param array $libOptions - * @return MemcachedResourceManager Fluent interface - */ - public function setLibOptions($id, array $libOptions) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'lib_options' => $libOptions - )); - } - - $this->normalizeLibOptions($libOptions); - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcachedResource) { - if (method_exists($resource, 'setOptions')) { - $resource->setOptions($libOptions); - } else { - foreach ($libOptions as $key => $value) { - $resource->setOption($key, $value); - } - } - } else { - $resource['lib_options'] = $libOptions; - } - - return $this; - } - - /** - * Get Libmemcached options - * - * @param string $id - * @return array - * @throws Exception\RuntimeException - */ - public function getLibOptions($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - - if ($resource instanceof MemcachedResource) { - $libOptions = array(); - $reflection = new ReflectionClass('Memcached'); - $constants = $reflection->getConstants(); - foreach ($constants as $constName => $constValue) { - if (substr($constName, 0, 4) == 'OPT_') { - $libOptions[$constValue] = $resource->getOption($constValue); - } - } - return $libOptions; - } - return $resource['lib_options']; - } - - /** - * Set one Libmemcached option - * - * @param string $id - * @param string|int $key - * @param mixed $value - * @return MemcachedResourceManager Fluent interface - */ - public function setLibOption($id, $key, $value) - { - return $this->setLibOptions($id, array($key => $value)); - } - - /** - * Get one Libmemcached option - * - * @param string $id - * @param string|int $key - * @return mixed - * @throws Exception\RuntimeException - */ - public function getLibOption($id, $key) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $this->normalizeLibOptionKey($key); - $resource = & $this->resources[$id]; - - if ($resource instanceof MemcachedResource) { - return $resource->getOption($key); - } - - return isset($resource['lib_options'][$key]) ? $resource['lib_options'][$key] : null; - } - - /** - * Normalize libmemcached options - * - * @param array|Traversable $libOptions - * @throws Exception\InvalidArgumentException - */ - protected function normalizeLibOptions(& $libOptions) - { - if (!is_array($libOptions) && !($libOptions instanceof Traversable)) { - throw new Exception\InvalidArgumentException( - "Lib-Options must be an array or an instance of Traversable" - ); - } - - $result = array(); - foreach ($libOptions as $key => $value) { - $this->normalizeLibOptionKey($key); - $result[$key] = $value; - } - - $libOptions = $result; - } - - /** - * Convert option name into it's constant value - * - * @param string|int $key - * @throws Exception\InvalidArgumentException - */ - protected function normalizeLibOptionKey(& $key) - { - // convert option name into it's constant value - if (is_string($key)) { - $const = 'Memcached::OPT_' . str_replace(array(' ', '-'), '_', strtoupper($key)); - if (!defined($const)) { - throw new Exception\InvalidArgumentException("Unknown libmemcached option '{$key}' ({$const})"); - } - $key = constant($const); - } else { - $key = (int) $key; - } - } - - /** - * Set servers - * - * $servers can be an array list or a comma separated list of servers. - * One server in the list can be descripted as follows: - * - URI: [tcp://][:][?weight=] - * - Assoc: array('host' => [, 'port' => ][, 'weight' => ]) - * - List: array([, ][, ]) - * - * @param string $id - * @param string|array $servers - * @return MemcachedResourceManager - */ - public function setServers($id, $servers) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'servers' => $servers - )); - } - - $this->normalizeServers($servers); - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcachedResource) { - // don't add servers twice - $servers = array_udiff($servers, $resource->getServerList(), array($this, 'compareServers')); - if ($servers) { - $resource->addServers($servers); - } - } else { - $resource['servers'] = $servers; - } - - return $this; - } - - /** - * Add servers - * - * @param string $id - * @param string|array $servers - * @return MemcachedResourceManager - */ - public function addServers($id, $servers) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'servers' => $servers - )); - } - - $this->normalizeServers($servers); - - $resource = & $this->resources[$id]; - if ($resource instanceof MemcachedResource) { - // don't add servers twice - $servers = array_udiff($servers, $resource->getServerList(), array($this, 'compareServers')); - if ($servers) { - $resource->addServers($servers); - } - } else { - // don't add servers twice - $resource['servers'] = array_merge( - $resource['servers'], - array_udiff($servers, $resource['servers'], array($this, 'compareServers')) - ); - } - - return $this; - } - - /** - * Add one server - * - * @param string $id - * @param string|array $server - * @return MemcachedResourceManager - */ - public function addServer($id, $server) - { - return $this->addServers($id, array($server)); - } - - /** - * Normalize a list of servers into the following format: - * array(array('host' => , 'port' => , 'weight' => )[, ...]) - * - * @param string|array $servers - */ - protected function normalizeServers(& $servers) - { - if (!is_array($servers) && !$servers instanceof Traversable) { - // Convert string into a list of servers - $servers = explode(',', $servers); - } - - $result = array(); - foreach ($servers as $server) { - $this->normalizeServer($server); - $result[$server['host'] . ':' . $server['port']] = $server; - } - - $servers = array_values($result); - } - - /** - * Compare 2 normalized server arrays - * (Compares only the host and the port) - * - * @param array $serverA - * @param array $serverB - * @return int - */ - protected function compareServers(array $serverA, array $serverB) - { - $keyA = $serverA['host'] . ':' . $serverA['port']; - $keyB = $serverB['host'] . ':' . $serverB['port']; - if ($keyA === $keyB) { - return 0; - } - return $keyA > $keyB ? 1 : -1; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Memory.php b/library/Zend/Cache/Storage/Adapter/Memory.php deleted file mode 100755 index 85aa32e6b..000000000 --- a/library/Zend/Cache/Storage/Adapter/Memory.php +++ /dev/null @@ -1,747 +0,0 @@ - => array( - * => array( - * 0 => - * 1 => - * ['tags' => ] - * ) - * ) - * ) - * - * @var array - */ - protected $data = array(); - - /** - * Set options. - * - * @param array|\Traversable|MemoryOptions $options - * @return Memory - * @see getOptions() - */ - public function setOptions($options) - { - if (!$options instanceof MemoryOptions) { - $options = new MemoryOptions($options); - } - - return parent::setOptions($options); - } - - /** - * Get options. - * - * @return MemoryOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new MemoryOptions()); - } - return $this->options; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - return $this->getOptions()->getMemoryLimit(); - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $total = $this->getOptions()->getMemoryLimit(); - $avail = $total - (float) memory_get_usage(true); - return ($avail > 0) ? $avail : 0; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return KeyListIterator - */ - public function getIterator() - { - $ns = $this->getOptions()->getNamespace(); - $keys = array(); - - if (isset($this->data[$ns])) { - foreach ($this->data[$ns] as $key => & $tmp) { - if ($this->internalHasItem($key)) { - $keys[] = $key; - } - } - } - - return new KeyListIterator($this, $keys); - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - $this->data = array(); - return true; - } - - /* ClearExpiredInterface */ - - /** - * Remove expired items - * - * @return bool - */ - public function clearExpired() - { - $ttl = $this->getOptions()->getTtl(); - if ($ttl <= 0) { - return true; - } - - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns])) { - return true; - } - - $data = & $this->data[$ns]; - foreach ($data as $key => & $item) { - if (microtime(true) >= $data[$key][1] + $ttl) { - unset($data[$key]); - } - } - - return true; - } - - /* ClearByNamespaceInterface */ - - public function clearByNamespace($namespace) - { - $namespace = (string) $namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } - - unset($this->data[$namespace]); - return true; - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @return bool - */ - public function clearByPrefix($prefix) - { - $prefix = (string) $prefix; - if ($prefix === '') { - throw new Exception\InvalidArgumentException('No prefix given'); - } - - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns])) { - return true; - } - - $prefixL = strlen($prefix); - $data = & $this->data[$ns]; - foreach ($data as $key => & $item) { - if (substr($key, 0, $prefixL) === $prefix) { - unset($data[$key]); - } - } - - return true; - } - - /* TaggableInterface */ - - /** - * Set tags to an item by given key. - * An empty array will remove all tags. - * - * @param string $key - * @param string[] $tags - * @return bool - */ - public function setTags($key, array $tags) - { - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns][$key])) { - return false; - } - - $this->data[$ns][$key]['tags'] = $tags; - return true; - } - - /** - * Get tags of an item by given key - * - * @param string $key - * @return string[]|FALSE - */ - public function getTags($key) - { - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns][$key])) { - return false; - } - - return isset($this->data[$ns][$key]['tags']) ? $this->data[$ns][$key]['tags'] : array(); - } - - /** - * Remove items matching given tags. - * - * If $disjunction only one of the given tags must match - * else all given tags must match. - * - * @param string[] $tags - * @param bool $disjunction - * @return bool - */ - public function clearByTags(array $tags, $disjunction = false) - { - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns])) { - return true; - } - - $tagCount = count($tags); - $data = & $this->data[$ns]; - foreach ($data as $key => & $item) { - if (isset($item['tags'])) { - $diff = array_diff($tags, $item['tags']); - if (($disjunction && count($diff) < $tagCount) || (!$disjunction && !$diff)) { - unset($data[$key]); - } - } - } - - return true; - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $options = $this->getOptions(); - $ns = $options->getNamespace(); - $success = isset($this->data[$ns][$normalizedKey]); - if ($success) { - $data = & $this->data[$ns][$normalizedKey]; - $ttl = $options->getTtl(); - if ($ttl && microtime(true) >= ($data[1] + $ttl)) { - $success = false; - } - } - - if (!$success) { - return null; - } - - $casToken = $data[0]; - return $data[0]; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $ns = $options->getNamespace(); - if (!isset($this->data[$ns])) { - return array(); - } - - $data = & $this->data[$ns]; - $ttl = $options->getTtl(); - $now = microtime(true); - - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if (isset($data[$normalizedKey])) { - if (!$ttl || $now < ($data[$normalizedKey][1] + $ttl)) { - $result[$normalizedKey] = $data[$normalizedKey][0]; - } - } - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - */ - protected function internalHasItem(& $normalizedKey) - { - $options = $this->getOptions(); - $ns = $options->getNamespace(); - if (!isset($this->data[$ns][$normalizedKey])) { - return false; - } - - // check if expired - $ttl = $options->getTtl(); - if ($ttl && microtime(true) >= ($this->data[$ns][$normalizedKey][1] + $ttl)) { - return false; - } - - return true; - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - */ - protected function internalHasItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $ns = $options->getNamespace(); - if (!isset($this->data[$ns])) { - return array(); - } - - $data = & $this->data[$ns]; - $ttl = $options->getTtl(); - $now = microtime(true); - - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if (isset($data[$normalizedKey])) { - if (!$ttl || $now < ($data[$normalizedKey][1] + $ttl)) { - $result[] = $normalizedKey; - } - } - } - - return $result; - } - - /** - * Get metadata of an item. - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - * - * @triggers getMetadata.pre(PreEvent) - * @triggers getMetadata.post(PostEvent) - * @triggers getMetadata.exception(ExceptionEvent) - */ - protected function internalGetMetadata(& $normalizedKey) - { - if (!$this->internalHasItem($normalizedKey)) { - return false; - } - - $ns = $this->getOptions()->getNamespace(); - return array( - 'mtime' => $this->data[$ns][$normalizedKey][1], - ); - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - - if (!$this->hasAvailableSpace()) { - $memoryLimit = $options->getMemoryLimit(); - throw new Exception\OutOfSpaceException( - "Memory usage exceeds limit ({$memoryLimit})." - ); - } - - $ns = $options->getNamespace(); - $this->data[$ns][$normalizedKey] = array($value, microtime(true)); - - return true; - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $options = $this->getOptions(); - - if (!$this->hasAvailableSpace()) { - $memoryLimit = $options->getMemoryLimit(); - throw new Exception\OutOfSpaceException( - "Memory usage exceeds limit ({$memoryLimit})." - ); - } - - $ns = $options->getNamespace(); - if (!isset($this->data[$ns])) { - $this->data[$ns] = array(); - } - - $data = & $this->data[$ns]; - $now = microtime(true); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $data[$normalizedKey] = array($value, $now); - } - - return array(); - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - - if (!$this->hasAvailableSpace()) { - $memoryLimit = $options->getMemoryLimit(); - throw new Exception\OutOfSpaceException( - "Memory usage exceeds limit ({$memoryLimit})." - ); - } - - $ns = $options->getNamespace(); - if (isset($this->data[$ns][$normalizedKey])) { - return false; - } - - $this->data[$ns][$normalizedKey] = array($value, microtime(true)); - return true; - } - - /** - * Internal method to add multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalAddItems(array & $normalizedKeyValuePairs) - { - $options = $this->getOptions(); - - if (!$this->hasAvailableSpace()) { - $memoryLimit = $options->getMemoryLimit(); - throw new Exception\OutOfSpaceException( - "Memory usage exceeds limit ({$memoryLimit})." - ); - } - - $ns = $options->getNamespace(); - if (!isset($this->data[$ns])) { - $this->data[$ns] = array(); - } - - $result = array(); - $data = & $this->data[$ns]; - $now = microtime(true); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (isset($data[$normalizedKey])) { - $result[] = $normalizedKey; - } else { - $data[$normalizedKey] = array($value, $now); - } - } - - return $result; - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns][$normalizedKey])) { - return false; - } - $this->data[$ns][$normalizedKey] = array($value, microtime(true)); - - return true; - } - - /** - * Internal method to replace multiple existing items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItems(array & $normalizedKeyValuePairs) - { - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns])) { - return array_keys($normalizedKeyValuePairs); - } - - $result = array(); - $data = & $this->data[$ns]; - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!isset($data[$normalizedKey])) { - $result[] = $normalizedKey; - } else { - $data[$normalizedKey] = array($value, microtime(true)); - } - } - - return $result; - } - - /** - * Internal method to reset lifetime of an item - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalTouchItem(& $normalizedKey) - { - $ns = $this->getOptions()->getNamespace(); - - if (!isset($this->data[$ns][$normalizedKey])) { - return false; - } - - $this->data[$ns][$normalizedKey][1] = microtime(true); - return true; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $ns = $this->getOptions()->getNamespace(); - if (!isset($this->data[$ns][$normalizedKey])) { - return false; - } - - unset($this->data[$ns][$normalizedKey]); - - // remove empty namespace - if (!$this->data[$ns]) { - unset($this->data[$ns]); - } - - return true; - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $ns = $this->getOptions()->getNamespace(); - if (isset($this->data[$ns][$normalizedKey])) { - $data = & $this->data[$ns][$normalizedKey]; - $data[0]+= $value; - $data[1] = microtime(true); - $newValue = $data[0]; - } else { - // initial value - $newValue = $value; - $this->data[$ns][$normalizedKey] = array($newValue, microtime(true)); - } - - return $newValue; - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $ns = $this->getOptions()->getNamespace(); - if (isset($this->data[$ns][$normalizedKey])) { - $data = & $this->data[$ns][$normalizedKey]; - $data[0]-= $value; - $data[1] = microtime(true); - $newValue = $data[0]; - } else { - // initial value - $newValue = -$value; - $this->data[$ns][$normalizedKey] = array($newValue, microtime(true)); - } - - return $newValue; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this, - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => true, - 'resource' => true, - ), - 'supportedMetadata' => array('mtime'), - 'minTtl' => 1, - 'maxTtl' => PHP_INT_MAX, - 'staticTtl' => false, - 'ttlPrecision' => 0.05, - 'expiredRead' => true, - 'maxKeyLength' => 0, - 'namespaceIsPrefix' => false, - 'namespaceSeparator' => '', - ) - ); - } - - return $this->capabilities; - } - - /* internal */ - - /** - * Has space available to store items? - * - * @return bool - */ - protected function hasAvailableSpace() - { - $total = $this->getOptions()->getMemoryLimit(); - - // check memory limit disabled - if ($total <= 0) { - return true; - } - - $free = $total - (float) memory_get_usage(true); - return ($free > 0); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/MemoryOptions.php b/library/Zend/Cache/Storage/Adapter/MemoryOptions.php deleted file mode 100755 index be48418c6..000000000 --- a/library/Zend/Cache/Storage/Adapter/MemoryOptions.php +++ /dev/null @@ -1,112 +0,0 @@ -normalizeMemoryLimit($memoryLimit); - - if ($this->memoryLimit != $memoryLimit) { - $this->triggerOptionEvent('memory_limit', $memoryLimit); - $this->memoryLimit = $memoryLimit; - } - - return $this; - } - - /** - * Get memory limit - * - * If the used memory of PHP exceeds this limit an OutOfSpaceException - * will be thrown. - * - * @return int - */ - public function getMemoryLimit() - { - if ($this->memoryLimit === null) { - // By default use half of PHP's memory limit if possible - $memoryLimit = $this->normalizeMemoryLimit(ini_get('memory_limit')); - if ($memoryLimit >= 0) { - $this->memoryLimit = (int) ($memoryLimit / 2); - } else { - // disable memory limit - $this->memoryLimit = 0; - } - } - - return $this->memoryLimit; - } - - /** - * Normalized a given value of memory limit into the number of bytes - * - * @param string|int $value - * @throws Exception\InvalidArgumentException - * @return int - */ - protected function normalizeMemoryLimit($value) - { - if (is_numeric($value)) { - return (int) $value; - } - - if (!preg_match('/(\-?\d+)\s*(\w*)/', ini_get('memory_limit'), $matches)) { - throw new Exception\InvalidArgumentException("Invalid memory limit '{$value}'"); - } - - $value = (int) $matches[1]; - if ($value <= 0) { - return 0; - } - - switch (strtoupper($matches[2])) { - case 'G': - $value*= 1024; - // no break - - case 'M': - $value*= 1024; - // no break - - case 'K': - $value*= 1024; - // no break - } - - return $value; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Redis.php b/library/Zend/Cache/Storage/Adapter/Redis.php deleted file mode 100755 index 1adb3d4a4..000000000 --- a/library/Zend/Cache/Storage/Adapter/Redis.php +++ /dev/null @@ -1,433 +0,0 @@ -initialized; - $this->getEventManager()->attach('option', function ($event) use (& $initialized) { - $initialized = false; - }); - } - - /** - * Get Redis resource - * - * @return RedisResource - */ - protected function getRedisResource() - { - if (!$this->initialized) { - $options = $this->getOptions(); - - // get resource manager and resource id - $this->resourceManager = $options->getResourceManager(); - $this->resourceId = $options->getResourceId(); - - // init namespace prefix - $namespace = $options->getNamespace(); - if ($namespace !== '') { - $this->namespacePrefix = $namespace . $options->getNamespaceSeparator(); - } else { - $this->namespacePrefix = ''; - } - - // update initialized flag - $this->initialized = true; - } - - return $this->resourceManager->getResource($this->resourceId); - } - - /* options */ - - /** - * Set options. - * - * @param array|Traversable|RedisOptions $options - * @return Redis - * @see getOptions() - */ - public function setOptions($options) - { - if (!$options instanceof RedisOptions) { - $options = new RedisOptions($options); - } - return parent::setOptions($options); - } - - /** - * Get options. - * - * @return RedisOptions - * @see setOptions() - */ - public function getOptions() - { - if (!$this->options) { - $this->setOptions(new RedisOptions()); - } - return $this->options; - } - - /** - * Internal method to get an item. - * - * @param string &$normalizedKey Key where to store data - * @param bool &$success If the operation was successfull - * @param mixed &$casToken Token - * @return mixed Data on success, false on key not found - * @throws Exception\RuntimeException - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $redis = $this->getRedisResource(); - try { - $value = $redis->get($this->namespacePrefix . $normalizedKey); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - - if ($value === false) { - $success = false; - return null; - } - - $success = true; - $casToken = $value; - return $value; - } - - /** - * Internal method to get multiple items. - * - * @param array &$normalizedKeys Array of keys to be obtained - * - * @return array Associative array of keys and values - * @throws Exception\RuntimeException - */ - protected function internalGetItems(array & $normalizedKeys) - { - $redis = $this->getRedisResource(); - - $namespacedKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $namespacedKeys[] = $this->namespacePrefix . $normalizedKey; - } - - try { - $results = $redis->mGet($namespacedKeys); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - //combine the key => value pairs and remove all missing values - return array_filter( - array_combine($normalizedKeys, $results), - function ($value) { - return $value !== false; - } - ); - } - - /** - * Internal method to test if an item exists. - * - * @param string &$normalizedKey Normalized key which will be checked - * - * @return bool - * @throws Exception\RuntimeException - */ - protected function internalHasItem(& $normalizedKey) - { - $redis = $this->getRedisResource(); - try { - return $redis->exists($this->namespacePrefix . $normalizedKey); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - } - - /** - * Internal method to store an item. - * - * @param string &$normalizedKey Key in Redis under which value will be saved - * @param mixed &$value Value to store under cache key - * - * @return bool - * @throws Exception\RuntimeException - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $redis = $this->getRedisResource(); - $ttl = $this->getOptions()->getTtl(); - - try { - if ($ttl) { - if ($this->resourceManager->getMajorVersion($this->resourceId) < 2) { - throw new Exception\UnsupportedMethodCallException("To use ttl you need version >= 2.0.0"); - } - $success = $redis->setex($this->namespacePrefix . $normalizedKey, $ttl, $value); - } else { - $success = $redis->set($this->namespacePrefix . $normalizedKey, $value); - } - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - - return $success; - } - - /** - * Internal method to store multiple items. - * - * @param array &$normalizedKeyValuePairs An array of normalized key/value pairs - * - * @return array Array of not stored keys - * @throws Exception\RuntimeException - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $redis = $this->getRedisResource(); - $ttl = $this->getOptions()->getTtl(); - - $namespacedKeyValuePairs = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $namespacedKeyValuePairs[$this->namespacePrefix . $normalizedKey] = $value; - } - try { - if ($ttl > 0) { - //check if ttl is supported - if ($this->resourceManager->getMajorVersion($this->resourceId) < 2) { - throw new Exception\UnsupportedMethodCallException("To use ttl you need version >= 2.0.0"); - } - //mSet does not allow ttl, so use transaction - $transaction = $redis->multi(); - foreach ($namespacedKeyValuePairs as $key => $value) { - $transaction->setex($key, $ttl, $value); - } - $success = $transaction->exec(); - } else { - $success = $redis->mSet($namespacedKeyValuePairs); - } - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - if (!$success) { - throw new Exception\RuntimeException($redis->getLastError()); - } - - return array(); - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\RuntimeException - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $redis = $this->getRedisResource(); - try { - return $redis->setnx($this->namespacePrefix . $normalizedKey, $value); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - } - - /** - * Internal method to remove an item. - * - * @param string &$normalizedKey Key which will be removed - * - * @return bool - * @throws Exception\RuntimeException - */ - protected function internalRemoveItem(& $normalizedKey) - { - $redis = $this->getRedisResource(); - try { - return (bool) $redis->delete($this->namespacePrefix . $normalizedKey); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\RuntimeException - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $redis = $this->getRedisResource(); - try { - return $redis->incrBy($this->namespacePrefix . $normalizedKey, $value); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\RuntimeException - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $redis = $this->getRedisResource(); - try { - return $redis->decrBy($this->namespacePrefix . $normalizedKey, $value); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - } - - /** - * Flush currently set DB - * - * @return bool - * @throws Exception\RuntimeException - */ - public function flush() - { - $redis = $this->getRedisResource(); - try { - return $redis->flushDB(); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - $redis = $this->getRedisResource(); - try { - $info = $redis->info(); - } catch (RedisResourceException $e) { - throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e); - } - - return $info['used_memory']; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $minTtl = $this->resourceManager->getMajorVersion($this->resourceId) < 2 ? 0 : 1; - //without serialization redis supports only strings for simple - //get/set methods - $this->capabilities = new Capabilities( - $this, - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => 'string', - 'boolean' => 'string', - 'integer' => 'string', - 'double' => 'string', - 'string' => true, - 'array' => false, - 'object' => false, - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'minTtl' => $minTtl, - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 255, - 'namespaceIsPrefix' => true, - ) - ); - } - - return $this->capabilities; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/RedisOptions.php b/library/Zend/Cache/Storage/Adapter/RedisOptions.php deleted file mode 100755 index f5e674875..000000000 --- a/library/Zend/Cache/Storage/Adapter/RedisOptions.php +++ /dev/null @@ -1,263 +0,0 @@ -namespaceSeparator !== $namespaceSeparator) { - $this->triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - } - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * Set the redis resource manager to use - * - * @param null|RedisResourceManager $resourceManager - * @return RedisOptions - */ - public function setResourceManager(RedisResourceManager $resourceManager = null) - { - if ($this->resourceManager !== $resourceManager) { - $this->triggerOptionEvent('resource_manager', $resourceManager); - $this->resourceManager = $resourceManager; - } - return $this; - } - - /** - * Get the redis resource manager - * - * @return RedisResourceManager - */ - public function getResourceManager() - { - if (!$this->resourceManager) { - $this->resourceManager = new RedisResourceManager(); - } - return $this->resourceManager; - } - - /** - * Get the redis resource id - * - * @return string - */ - public function getResourceId() - { - return $this->resourceId; - } - - /** - * Set the redis resource id - * - * @param string $resourceId - * @return RedisOptions - */ - public function setResourceId($resourceId) - { - $resourceId = (string) $resourceId; - if ($this->resourceId !== $resourceId) { - $this->triggerOptionEvent('resource_id', $resourceId); - $this->resourceId = $resourceId; - } - return $this; - } - - /** - * Get the persistent id - * - * @return string - */ - public function getPersistentId() - { - return $this->getResourceManager()->getPersistentId($this->getResourceId()); - } - - /** - * Set the persistent id - * - * @param string $persistentId - * @return RedisOptions - */ - public function setPersistentId($persistentId) - { - $this->triggerOptionEvent('persistent_id', $persistentId); - $this->getResourceManager()->setPersistentId($this->getResourceId(), $persistentId); - return $this; - } - - /** - * Set redis options - * - * @param array $libOptions - * @return RedisOptions - * @link http://github.com/nicolasff/phpredis#setoption - */ - public function setLibOptions(array $libOptions) - { - $this->triggerOptionEvent('lib_option', $libOptions); - $this->getResourceManager()->setLibOptions($this->getResourceId(), $libOptions); - return $this; - } - - /** - * Get redis options - * - * @return array - * @link http://github.com/nicolasff/phpredis#setoption - */ - public function getLibOptions() - { - return $this->getResourceManager()->getLibOptions($this->getResourceId()); - } - - /** - * Set server - * - * Server can be described as follows: - * - URI: /path/to/sock.sock - * - Assoc: array('host' => [, 'port' => [, 'timeout' => ]]) - * - List: array([, , [, ]]) - * - * @param string|array $server - * - * @return RedisOptions - */ - public function setServer($server) - { - $this->getResourceManager()->setServer($this->getResourceId(), $server); - return $this; - } - - /** - * Get server - * - * @return array array('host' => [, 'port' => [, 'timeout' => ]]) - */ - public function getServer() - { - return $this->getResourceManager()->getServer($this->getResourceId()); - } - - /** - * Set resource database number - * - * @param int $database Database number - * - * @return RedisOptions - */ - public function setDatabase($database) - { - $this->getResourceManager()->setDatabase($this->getResourceId(), $database); - return $this; - } - - /** - * Get resource database number - * - * @return int Database number - */ - public function getDatabase() - { - return $this->getResourceManager()->getDatabase($this->getResourceId()); - } - - /** - * Set resource password - * - * @param string $password Password - * - * @return RedisOptions - */ - public function setPassword($password) - { - $this->getResourceManager()->setPassword($this->getResourceId(), $password); - return $this; - } - - /** - * Get resource password - * - * @return string - */ - public function getPassword() - { - return $this->getResourceManager()->getPassword($this->getResourceId()); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/RedisResourceManager.php b/library/Zend/Cache/Storage/Adapter/RedisResourceManager.php deleted file mode 100755 index ed8ee2147..000000000 --- a/library/Zend/Cache/Storage/Adapter/RedisResourceManager.php +++ /dev/null @@ -1,645 +0,0 @@ -resources[$id]); - } - - /** - * Get redis server version - * - * @param string $id - * @return int - * @throws Exception\RuntimeException - */ - public function getMajorVersion($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - return (int) $resource['version']; - } - - /** - * Get redis server version - * - * @deprecated 2.2.2 Use getMajorVersion instead - * - * @param string $id - * @return int - * @throws Exception\RuntimeException - */ - public function getMayorVersion($id) - { - return $this->getMajorVersion($id); - } - - /** - * Get redis resource database - * - * @param string $id - * @return string - */ - public function getDatabase($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - return $resource['database']; - } - - /** - * Get redis resource password - * - * @param string $id - * @return string - */ - public function getPassword($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - return $resource['password']; - } - - /** - * Gets a redis resource - * - * @param string $id - * @return RedisResource - * @throws Exception\RuntimeException - */ - public function getResource($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - if ($resource['resource'] instanceof RedisResource) { - //in case new server was set then connect - if (!$resource['initialized']) { - $this->connect($resource); - } - $info = $resource['resource']->info(); - $resource['version'] = $info['redis_version']; - return $resource['resource']; - } - - $redis = new RedisResource(); - - $resource['resource'] = $redis; - $this->connect($resource); - - foreach ($resource['lib_options'] as $k => $v) { - $redis->setOption($k, $v); - } - - $info = $redis->info(); - $resource['version'] = $info['redis_version']; - $this->resources[$id]['resource'] = $redis; - return $redis; - } - - /** - * Get server - * @param string $id - * @throws Exception\RuntimeException - * @return array array('host' => [, 'port' => [, 'timeout' => ]]) - */ - public function getServer($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - return $resource['server']; - } - - /** - * Normalize one server into the following format: - * array('host' => [, 'port' => [, 'timeout' => ]]) - * - * @param string|array $server - * - * @throws Exception\InvalidArgumentException - */ - protected function normalizeServer(&$server) - { - $host = null; - $port = null; - $timeout = 0; - - // convert a single server into an array - if ($server instanceof Traversable) { - $server = ArrayUtils::iteratorToArray($server); - } - - if (is_array($server)) { - // array([, [, ]]) - if (isset($server[0])) { - $host = (string) $server[0]; - $port = isset($server[1]) ? (int) $server[1] : $port; - $timeout = isset($server[2]) ? (int) $server[2] : $timeout; - } - - // array('host' => [, 'port' => , ['timeout' => ]]) - if (!isset($server[0]) && isset($server['host'])) { - $host = (string) $server['host']; - $port = isset($server['port']) ? (int) $server['port'] : $port; - $timeout = isset($server['timeout']) ? (int) $server['timeout'] : $timeout; - } - } else { - // parse server from URI host{:?port} - $server = trim($server); - if (strpos($server, '/') !== 0) { - //non unix domain socket connection - $server = parse_url($server); - } else { - $server = array('host' => $server); - } - if (!$server) { - throw new Exception\InvalidArgumentException("Invalid server given"); - } - - $host = $server['host']; - $port = isset($server['port']) ? (int) $server['port'] : $port; - $timeout = isset($server['timeout']) ? (int) $server['timeout'] : $timeout; - } - - if (!$host) { - throw new Exception\InvalidArgumentException('Missing required server host'); - } - - $server = array( - 'host' => $host, - 'port' => $port, - 'timeout' => $timeout, - ); - } - - /** - * Extract password to be used on connection - * - * @param mixed $resource - * @param mixed $serverUri - * - * @return string|null - */ - protected function extractPassword($resource, $serverUri) - { - if (! empty($resource['password'])) { - return $resource['password']; - } - - if (! is_string($serverUri)) { - return null; - } - - // parse server from URI host{:?port} - $server = trim($serverUri); - - if (strpos($server, '/') === 0) { - return null; - } - - //non unix domain socket connection - $server = parse_url($server); - - return isset($server['pass']) ? $server['pass'] : null; - } - - /** - * Connects to redis server - * - * - * @param array & $resource - * - * @return null - * @throws Exception\RuntimeException - */ - protected function connect(array & $resource) - { - $server = $resource['server']; - $redis = $resource['resource']; - if ($resource['persistent_id'] !== '') { - //connect or reuse persistent connection - $success = $redis->pconnect($server['host'], $server['port'], $server['timeout'], $server['persistent_id']); - } elseif ($server['port']) { - $success = $redis->connect($server['host'], $server['port'], $server['timeout']); - } elseif ($server['timeout']) { - //connect through unix domain socket - $success = $redis->connect($server['host'], $server['timeout']); - } else { - $success = $redis->connect($server['host']); - } - - if (!$success) { - throw new Exception\RuntimeException('Could not estabilish connection with Redis instance'); - } - - $resource['initialized'] = true; - if ($resource['password']) { - $redis->auth($resource['password']); - } - $redis->select($resource['database']); - } - - /** - * Set a resource - * - * @param string $id - * @param array|Traversable|RedisResource $resource - * @return RedisResourceManager Fluent interface - */ - public function setResource($id, $resource) - { - $id = (string) $id; - //TODO: how to get back redis connection info from resource? - $defaults = array( - 'persistent_id' => '', - 'lib_options' => array(), - 'server' => array(), - 'password' => '', - 'database' => 0, - 'resource' => null, - 'initialized' => false, - 'version' => 0, - ); - if (!$resource instanceof RedisResource) { - if ($resource instanceof Traversable) { - $resource = ArrayUtils::iteratorToArray($resource); - } elseif (!is_array($resource)) { - throw new Exception\InvalidArgumentException( - 'Resource must be an instance of an array or Traversable' - ); - } - - $resource = array_merge($defaults, $resource); - // normalize and validate params - $this->normalizePersistentId($resource['persistent_id']); - $this->normalizeLibOptions($resource['lib_options']); - - // #6495 note: order is important here, as `normalizeServer` applies destructive - // transformations on $resource['server'] - $resource['password'] = $this->extractPassword($resource, $resource['server']); - - $this->normalizeServer($resource['server']); - } else { - //there are two ways of determining if redis is already initialized - //with connect function: - //1) pinging server - //2) checking undocumented property socket which is available only - //after successful connect - $resource = array_merge( - $defaults, - array( - 'resource' => $resource, - 'initialized' => isset($resource->socket), - ) - ); - } - $this->resources[$id] = $resource; - return $this; - } - - /** - * Remove a resource - * - * @param string $id - * @return RedisResourceManager Fluent interface - */ - public function removeResource($id) - { - unset($this->resources[$id]); - return $this; - } - - /** - * Set the persistent id - * - * @param string $id - * @param string $persistentId - * @return RedisResourceManager Fluent interface - * @throws Exception\RuntimeException - */ - public function setPersistentId($id, $persistentId) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'persistent_id' => $persistentId - )); - } - - $resource = & $this->resources[$id]; - if ($resource instanceof RedisResource) { - throw new Exception\RuntimeException( - "Can't change persistent id of resource {$id} after instanziation" - ); - } - - $this->normalizePersistentId($persistentId); - $resource['persistent_id'] = $persistentId; - - return $this; - } - - /** - * Get the persistent id - * - * @param string $id - * @return string - * @throws Exception\RuntimeException - */ - public function getPersistentId($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - - if ($resource instanceof RedisResource) { - throw new Exception\RuntimeException( - "Can't get persistent id of an instantiated redis resource" - ); - } - - return $resource['persistent_id']; - } - - /** - * Normalize the persistent id - * - * @param string $persistentId - */ - protected function normalizePersistentId(& $persistentId) - { - $persistentId = (string) $persistentId; - } - - /** - * Set Redis options - * - * @param string $id - * @param array $libOptions - * @return RedisResourceManager Fluent interface - */ - public function setLibOptions($id, array $libOptions) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'lib_options' => $libOptions - )); - } - - $this->normalizeLibOptions($libOptions); - $resource = & $this->resources[$id]; - - $resource['lib_options'] = $libOptions; - - if ($resource['resource'] instanceof RedisResource) { - $redis = & $resource['resource']; - if (method_exists($redis, 'setOptions')) { - $redis->setOptions($libOptions); - } else { - foreach ($libOptions as $key => $value) { - $redis->setOption($key, $value); - } - } - } - - return $this; - } - - /** - * Get Redis options - * - * @param string $id - * @return array - * @throws Exception\RuntimeException - */ - public function getLibOptions($id) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $resource = & $this->resources[$id]; - - if ($resource instanceof RedisResource) { - $libOptions = array(); - $reflection = new ReflectionClass('Redis'); - $constants = $reflection->getConstants(); - foreach ($constants as $constName => $constValue) { - if (substr($constName, 0, 4) == 'OPT_') { - $libOptions[$constValue] = $resource->getOption($constValue); - } - } - return $libOptions; - } - return $resource['lib_options']; - } - - /** - * Set one Redis option - * - * @param string $id - * @param string|int $key - * @param mixed $value - * @return RedisResourceManager Fluent interface - */ - public function setLibOption($id, $key, $value) - { - return $this->setLibOptions($id, array($key => $value)); - } - - /** - * Get one Redis option - * - * @param string $id - * @param string|int $key - * @return mixed - * @throws Exception\RuntimeException - */ - public function getLibOption($id, $key) - { - if (!$this->hasResource($id)) { - throw new Exception\RuntimeException("No resource with id '{$id}'"); - } - - $this->normalizeLibOptionKey($key); - $resource = & $this->resources[$id]; - - if ($resource instanceof RedisResource) { - return $resource->getOption($key); - } - - return isset($resource['lib_options'][$key]) ? $resource['lib_options'][$key] : null; - } - - /** - * Normalize Redis options - * - * @param array|Traversable $libOptions - * @throws Exception\InvalidArgumentException - */ - protected function normalizeLibOptions(& $libOptions) - { - if (!is_array($libOptions) && !($libOptions instanceof Traversable)) { - throw new Exception\InvalidArgumentException( - "Lib-Options must be an array or an instance of Traversable" - ); - } - - $result = array(); - foreach ($libOptions as $key => $value) { - $this->normalizeLibOptionKey($key); - $result[$key] = $value; - } - - $libOptions = $result; - } - - /** - * Convert option name into it's constant value - * - * @param string|int $key - * @throws Exception\InvalidArgumentException - */ - protected function normalizeLibOptionKey(& $key) - { - // convert option name into it's constant value - if (is_string($key)) { - $const = 'Redis::OPT_' . str_replace(array(' ', '-'), '_', strtoupper($key)); - if (!defined($const)) { - throw new Exception\InvalidArgumentException("Unknown redis option '{$key}' ({$const})"); - } - $key = constant($const); - } else { - $key = (int) $key; - } - } - - /** - * Set server - * - * Server can be described as follows: - * - URI: /path/to/sock.sock - * - Assoc: array('host' => [, 'port' => [, 'timeout' => ]]) - * - List: array([, , [, ]]) - * - * @param string $id - * @param string|array $server - * @return RedisResourceManager - */ - public function setServer($id, $server) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'server' => $server - )); - } - - $this->normalizeServer($server); - - $resource = & $this->resources[$id]; - $resource['password'] = $this->extractPassword($resource, $server); - - if ($resource['resource'] instanceof RedisResource) { - $resourceParams = array('server' => $server); - - if (! empty($resource['password'])) { - $resourceParams['password'] = $resource['password']; - } - - $this->setResource($id, $resourceParams); - } else { - $resource['server'] = $server; - } - - return $this; - } - - /** - * Set redis password - * - * @param string $id - * @param string $password - * @return RedisResource - */ - public function setPassword($id, $password) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'password' => $password, - )); - } - - $resource = & $this->resources[$id]; - $resource['password'] = $password; - $resource['initialized'] = false; - return $this; - } - - /** - * Set redis database number - * - * @param string $id - * @param int $database - * @return RedisResource - */ - public function setDatabase($id, $database) - { - if (!$this->hasResource($id)) { - return $this->setResource($id, array( - 'database' => (int) $database, - )); - } - - $resource = & $this->resources[$id]; - $resource['database'] = $database; - $resource['initialized'] = false; - return $this; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/Session.php b/library/Zend/Cache/Storage/Adapter/Session.php deleted file mode 100755 index 4603c2314..000000000 --- a/library/Zend/Cache/Storage/Adapter/Session.php +++ /dev/null @@ -1,546 +0,0 @@ -options) { - $this->setOptions(new SessionOptions()); - } - return $this->options; - } - - /** - * Get the session container - * - * @return SessionContainer - */ - protected function getSessionContainer() - { - $sessionContainer = $this->getOptions()->getSessionContainer(); - if (!$sessionContainer) { - throw new Exception\RuntimeException("No session container configured"); - } - return $sessionContainer; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return KeyListIterator - */ - public function getIterator() - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if ($cntr->offsetExists($ns)) { - $keys = array_keys($cntr->offsetGet($ns)); - } else { - $keys = array(); - } - - return new KeyListIterator($this, $keys); - } - - /* FlushableInterface */ - - /** - * Flush the whole session container - * - * @return bool - */ - public function flush() - { - $this->getSessionContainer()->exchangeArray(array()); - return true; - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @return bool - */ - public function clearByPrefix($prefix) - { - $prefix = (string) $prefix; - if ($prefix === '') { - throw new Exception\InvalidArgumentException('No prefix given'); - } - - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - return true; - } - - $data = $cntr->offsetGet($ns); - $prefixL = strlen($prefix); - foreach ($data as $key => & $item) { - if (substr($key, 0, $prefixL) === $prefix) { - unset($data[$key]); - } - } - $cntr->offsetSet($ns, $data); - - return true; - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - $success = false; - return null; - } - - $data = $cntr->offsetGet($ns); - $success = array_key_exists($normalizedKey, $data); - if (!$success) { - return null; - } - - $casToken = $value = $data[$normalizedKey]; - return $value; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - return array(); - } - - $data = $cntr->offsetGet($ns); - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if (array_key_exists($normalizedKey, $data)) { - $result[$normalizedKey] = $data[$normalizedKey]; - } - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - */ - protected function internalHasItem(& $normalizedKey) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - return false; - } - - $data = $cntr->offsetGet($ns); - return array_key_exists($normalizedKey, $data); - } - - /** - * Internal method to test multiple items. - * - * @param array $normalizedKeys - * @return array Array of found keys - */ - protected function internalHasItems(array & $normalizedKeys) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - return array(); - } - - $data = $cntr->offsetGet($ns); - $result = array(); - foreach ($normalizedKeys as $normalizedKey) { - if (array_key_exists($normalizedKey, $data)) { - $result[] = $normalizedKey; - } - } - - return $result; - } - - /** - * Get metadata of an item. - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - * - * @triggers getMetadata.pre(PreEvent) - * @triggers getMetadata.post(PostEvent) - * @triggers getMetadata.exception(ExceptionEvent) - */ - protected function internalGetMetadata(& $normalizedKey) - { - return $this->internalHasItem($normalizedKey) ? array() : false; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - $data = $cntr->offsetExists($ns) ? $cntr->offsetGet($ns) : array(); - $data[$normalizedKey] = $value; - $cntr->offsetSet($ns, $data); - return true; - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if ($cntr->offsetExists($ns)) { - $data = array_merge($cntr->offsetGet($ns), $normalizedKeyValuePairs); - } else { - $data = $normalizedKeyValuePairs; - } - $cntr->offsetSet($ns, $data); - - return array(); - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if ($cntr->offsetExists($ns)) { - $data = $cntr->offsetGet($ns); - - if (array_key_exists($normalizedKey, $data)) { - return false; - } - - $data[$normalizedKey] = $value; - } else { - $data = array($normalizedKey => $value); - } - - $cntr->offsetSet($ns, $data); - return true; - } - - /** - * Internal method to add multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalAddItems(array & $normalizedKeyValuePairs) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - $result = array(); - if ($cntr->offsetExists($ns)) { - $data = $cntr->offsetGet($ns); - - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (array_key_exists($normalizedKey, $data)) { - $result[] = $normalizedKey; - } else { - $data[$normalizedKey] = $value; - } - } - } else { - $data = $normalizedKeyValuePairs; - } - - $cntr->offsetSet($ns, $data); - return $result; - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - return false; - } - - $data = $cntr->offsetGet($ns); - if (!array_key_exists($normalizedKey, $data)) { - return false; - } - $data[$normalizedKey] = $value; - $cntr->offsetSet($ns, $data); - - return true; - } - - /** - * Internal method to replace multiple existing items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItems(array & $normalizedKeyValuePairs) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - if (!$cntr->offsetExists($ns)) { - return array_keys($normalizedKeyValuePairs); - } - - $data = $cntr->offsetGet($ns); - $result = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!array_key_exists($normalizedKey, $data)) { - $result[] = $normalizedKey; - } else { - $data[$normalizedKey] = $value; - } - } - $cntr->offsetSet($ns, $data); - - return $result; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if (!$cntr->offsetExists($ns)) { - return false; - } - - $data = $cntr->offsetGet($ns); - if (!array_key_exists($normalizedKey, $data)) { - return false; - } - - unset($data[$normalizedKey]); - - if (!$data) { - $cntr->offsetUnset($ns); - } else { - $cntr->offsetSet($ns, $data); - } - - return true; - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if ($cntr->offsetExists($ns)) { - $data = $cntr->offsetGet($ns); - } else { - $data = array(); - } - - if (array_key_exists($normalizedKey, $data)) { - $data[$normalizedKey]+= $value; - $newValue = $data[$normalizedKey]; - } else { - // initial value - $newValue = $value; - $data[$normalizedKey] = $newValue; - } - - $cntr->offsetSet($ns, $data); - return $newValue; - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $cntr = $this->getSessionContainer(); - $ns = $this->getOptions()->getNamespace(); - - if ($cntr->offsetExists($ns)) { - $data = $cntr->offsetGet($ns); - } else { - $data = array(); - } - - if (array_key_exists($normalizedKey, $data)) { - $data[$normalizedKey]-= $value; - $newValue = $data[$normalizedKey]; - } else { - // initial value - $newValue = -$value; - $data[$normalizedKey] = $newValue; - } - - $cntr->offsetSet($ns, $data); - return $newValue; - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this, - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => 'array', - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'minTtl' => 0, - 'maxKeyLength' => 0, - 'namespaceIsPrefix' => false, - 'namespaceSeparator' => '', - ) - ); - } - - return $this->capabilities; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/SessionOptions.php b/library/Zend/Cache/Storage/Adapter/SessionOptions.php deleted file mode 100755 index 8e4c6d5c9..000000000 --- a/library/Zend/Cache/Storage/Adapter/SessionOptions.php +++ /dev/null @@ -1,51 +0,0 @@ -sessionContainer != $sessionContainer) { - $this->triggerOptionEvent('session_container', $sessionContainer); - $this->sessionContainer = $sessionContainer; - } - - return $this; - } - - /** - * Get the session container - * - * @return null|SessionContainer - */ - public function getSessionContainer() - { - return $this->sessionContainer; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/WinCache.php b/library/Zend/Cache/Storage/Adapter/WinCache.php deleted file mode 100755 index b911e0400..000000000 --- a/library/Zend/Cache/Storage/Adapter/WinCache.php +++ /dev/null @@ -1,533 +0,0 @@ -options) { - $this->setOptions(new WinCacheOptions()); - } - return $this->options; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - $mem = wincache_ucache_meminfo(); - return $mem['memory_total']; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $mem = wincache_ucache_meminfo(); - return $mem['memory_free']; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - return wincache_ucache_clear(); - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $result = wincache_ucache_get($internalKey, $success); - - if ($success) { - $casToken = $result; - } else { - $result = null; - } - - return $result; - } - - /** - * Internal method to get multiple items. - * - * @param array $normalizedKeys - * @return array Associative array of keys and values - * @throws Exception\ExceptionInterface - */ - protected function internalGetItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return wincache_ucache_get($normalizedKeys); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $fetch = wincache_ucache_get($internalKeys); - - // remove namespace prefix - $prefixL = strlen($prefix); - $result = array(); - foreach ($fetch as $internalKey => & $value) { - $result[substr($internalKey, $prefixL)] = & $value; - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - return wincache_ucache_exists($prefix . $normalizedKey); - } - - /** - * Get metadata of an item. - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadata(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - $info = wincache_ucache_info(true, $internalKey); - if (isset($info['ucache_entries'][1])) { - $metadata = $info['ucache_entries'][1]; - $this->normalizeMetadata($metadata); - return $metadata; - } - - return false; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - - if (!wincache_ucache_set($internalKey, $value, $ttl)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "wincache_ucache_set('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to store multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalSetItems(array & $normalizedKeyValuePairs) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return wincache_ucache_set($normalizedKeyValuePairs, null, $options->getTtl()); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeyValuePairs = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => & $value) { - $internalKey = $prefix . $normalizedKey; - $internalKeyValuePairs[$internalKey] = & $value; - } - - $result = wincache_ucache_set($internalKeyValuePairs, null, $options->getTtl()); - - // remove key prefic - $prefixL = strlen($prefix); - foreach ($result as & $key) { - $key = substr($key, $prefixL); - } - - return $result; - } - - /** - * Add an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalAddItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - - if (!wincache_ucache_add($internalKey, $value, $ttl)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "wincache_ucache_add('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to add multiple items. - * - * @param array $normalizedKeyValuePairs - * @return array Array of not stored keys - * @throws Exception\ExceptionInterface - */ - protected function internalAddItems(array & $normalizedKeyValuePairs) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - return wincache_ucache_add($normalizedKeyValuePairs, null, $options->getTtl()); - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeyValuePairs = array(); - foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $internalKey = $prefix . $normalizedKey; - $internalKeyValuePairs[$internalKey] = $value; - } - - $result = wincache_ucache_add($internalKeyValuePairs, null, $options->getTtl()); - - // remove key prefic - $prefixL = strlen($prefix); - foreach ($result as & $key) { - $key = substr($key, $prefixL); - } - - return $result; - } - - /** - * Internal method to replace an existing item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalReplaceItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - if (!wincache_ucache_exists($internalKey)) { - return false; - } - - $ttl = $options->getTtl(); - if (!wincache_ucache_set($internalKey, $value, $ttl)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "wincache_ucache_set('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - return wincache_ucache_delete($internalKey); - } - - /** - * Internal method to remove multiple items. - * - * @param array $normalizedKeys - * @return array Array of not removed keys - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItems(array & $normalizedKeys) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - if ($namespace === '') { - $result = wincache_ucache_delete($normalizedKeys); - return ($result === false) ? $normalizedKeys : $result; - } - - $prefix = $namespace . $options->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($normalizedKeys as $normalizedKey) { - $internalKeys[] = $prefix . $normalizedKey; - } - - $result = wincache_ucache_delete($internalKeys); - if ($result === false) { - return $normalizedKeys; - } elseif ($result) { - // remove key prefix - $prefixL = strlen($prefix); - foreach ($result as & $key) { - $key = substr($key, $prefixL); - } - } - - return $result; - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - return wincache_ucache_inc($internalKey, (int) $value); - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - return wincache_ucache_dec($internalKey, (int) $value); - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $marker = new stdClass(); - $capabilities = new Capabilities( - $this, - $marker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array( - 'internal_key', 'ttl', 'hits', 'size' - ), - 'minTtl' => 1, - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - ) - ); - - // update namespace separator on change option - $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { - $params = $event->getParams(); - - if (isset($params['namespace_separator'])) { - $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); - } - }); - - $this->capabilities = $capabilities; - $this->capabilityMarker = $marker; - } - - return $this->capabilities; - } - - /* internal */ - - /** - * Normalize metadata to work with WinCache - * - * @param array $metadata - * @return void - */ - protected function normalizeMetadata(array & $metadata) - { - $metadata['internal_key'] = $metadata['key_name']; - $metadata['hits'] = $metadata['hitcount']; - $metadata['ttl'] = $metadata['ttl_seconds']; - $metadata['size'] = $metadata['value_size']; - - unset( - $metadata['key_name'], - $metadata['hitcount'], - $metadata['ttl_seconds'], - $metadata['value_size'] - ); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php b/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php deleted file mode 100755 index 8c9789ae7..000000000 --- a/library/Zend/Cache/Storage/Adapter/WinCacheOptions.php +++ /dev/null @@ -1,47 +0,0 @@ -triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/XCache.php b/library/Zend/Cache/Storage/Adapter/XCache.php deleted file mode 100755 index 18073e9fe..000000000 --- a/library/Zend/Cache/Storage/Adapter/XCache.php +++ /dev/null @@ -1,524 +0,0 @@ -options) { - $this->setOptions(new XCacheOptions()); - } - return $this->options; - } - - /* TotalSpaceCapableInterface */ - - /** - * Get total space in bytes - * - * @return int|float - */ - public function getTotalSpace() - { - if ($this->totalSpace === null) { - $this->totalSpace = 0; - - $this->initAdminAuth(); - $cnt = xcache_count(XC_TYPE_VAR); - for ($i=0; $i < $cnt; $i++) { - $info = xcache_info(XC_TYPE_VAR, $i); - $this->totalSpace+= $info['size']; - } - $this->resetAdminAuth(); - } - - return $this->totalSpace; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @return int|float - */ - public function getAvailableSpace() - { - $availableSpace = 0; - - $this->initAdminAuth(); - $cnt = xcache_count(XC_TYPE_VAR); - for ($i = 0; $i < $cnt; $i++) { - $info = xcache_info(XC_TYPE_VAR, $i); - $availableSpace+= $info['avail']; - } - $this->resetAdminAuth(); - - return $availableSpace; - } - - /* ClearByNamespaceInterface */ - - /** - * Remove items by given namespace - * - * @param string $namespace - * @return bool - */ - public function clearByNamespace($namespace) - { - $namespace = (string) $namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } - - $options = $this->getOptions(); - $prefix = $namespace . $options->getNamespaceSeparator(); - - xcache_unset_by_prefix($prefix); - return true; - } - - /* ClearByPrefixInterface */ - - /** - * Remove items matching given prefix - * - * @param string $prefix - * @return bool - */ - public function clearByPrefix($prefix) - { - $prefix = (string) $prefix; - if ($prefix === '') { - throw new Exception\InvalidArgumentException('No prefix given'); - } - - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator() . $prefix; - - xcache_unset_by_prefix($prefix); - return true; - } - - /* FlushableInterface */ - - /** - * Flush the whole storage - * - * @return bool - */ - public function flush() - { - $this->initAdminAuth(); - $cnt = xcache_count(XC_TYPE_VAR); - for ($i = 0; $i < $cnt; $i++) { - xcache_clear_cache(XC_TYPE_VAR, $i); - } - $this->resetAdminAuth(); - - return true; - } - - /* IterableInterface */ - - /** - * Get the storage iterator - * - * @return KeyListIterator - */ - public function getIterator() - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $keys = array(); - - $this->initAdminAuth(); - - if ($namespace === '') { - $cnt = xcache_count(XC_TYPE_VAR); - for ($i=0; $i < $cnt; $i++) { - $list = xcache_list(XC_TYPE_VAR, $i); - foreach ($list['cache_list'] as & $item) { - $keys[] = $item['name']; - } - } - } else { - $prefix = $namespace . $options->getNamespaceSeparator(); - $prefixL = strlen($prefix); - - $cnt = xcache_count(XC_TYPE_VAR); - for ($i=0; $i < $cnt; $i++) { - $list = xcache_list(XC_TYPE_VAR, $i); - foreach ($list['cache_list'] as & $item) { - $keys[] = substr($item['name'], $prefixL); - } - } - } - - $this->resetAdminAuth(); - - return new KeyListIterator($this, $keys); - } - - /* reading */ - - /** - * Internal method to get an item. - * - * @param string $normalizedKey - * @param bool $success - * @param mixed $casToken - * @return mixed Data on success, null on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - $result = xcache_get($internalKey); - $success = ($result !== null); - - if ($success) { - $casToken = $result; - } - - return $result; - } - - /** - * Internal method to test if an item exists. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalHasItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - return xcache_isset($prefix . $normalizedKey); - } - - /** - * Get metadata of an item. - * - * @param string $normalizedKey - * @return array|bool Metadata on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetMetadata(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - if (xcache_isset($internalKey)) { - $this->initAdminAuth(); - $cnt = xcache_count(XC_TYPE_VAR); - for ($i=0; $i < $cnt; $i++) { - $list = xcache_list(XC_TYPE_VAR, $i); - foreach ($list['cache_list'] as & $metadata) { - if ($metadata['name'] === $internalKey) { - $this->normalizeMetadata($metadata); - return $metadata; - } - } - } - $this->resetAdminAuth(); - } - - return false; - } - - /* writing */ - - /** - * Internal method to store an item. - * - * @param string $normalizedKey - * @param mixed $value - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalSetItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($options === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - - if (!xcache_set($internalKey, $value, $ttl)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "xcache_set('{$internalKey}', <{$type}>, {$ttl}) failed" - ); - } - - return true; - } - - /** - * Internal method to remove an item. - * - * @param string $normalizedKey - * @return bool - * @throws Exception\ExceptionInterface - */ - protected function internalRemoveItem(& $normalizedKey) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - - return xcache_unset($internalKey); - } - - /** - * Internal method to increment an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalIncrementItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - $value = (int) $value; - - return xcache_inc($internalKey, $value, $ttl); - } - - /** - * Internal method to decrement an item. - * - * @param string $normalizedKey - * @param int $value - * @return int|bool The new value on success, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalDecrementItem(& $normalizedKey, & $value) - { - $options = $this->getOptions(); - $namespace = $options->getNamespace(); - $prefix = ($namespace === '') ? '' : $namespace . $options->getNamespaceSeparator(); - $internalKey = $prefix . $normalizedKey; - $ttl = $options->getTtl(); - $value = (int) $value; - - return xcache_dec($internalKey, $value, $ttl); - } - - /* status */ - - /** - * Internal method to get capabilities of this adapter - * - * @return Capabilities - */ - protected function internalGetCapabilities() - { - if ($this->capabilities === null) { - $marker = new stdClass(); - $capabilities = new Capabilities( - $this, - $marker, - array( - 'supportedDatatypes' => array( - 'NULL' => false, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array( - 'internal_key', - 'size', 'refcount', 'hits', - 'ctime', 'atime', 'hvalue', - ), - 'minTtl' => 1, - 'maxTtl' => (int)ini_get('xcache.var_maxttl'), - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => true, - 'expiredRead' => false, - 'maxKeyLength' => 5182, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - ) - ); - - // update namespace separator on change option - $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { - $params = $event->getParams(); - - if (isset($params['namespace_separator'])) { - $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); - } - }); - - $this->capabilities = $capabilities; - $this->capabilityMarker = $marker; - } - - return $this->capabilities; - } - - /* internal */ - - /** - * Init authentication before calling admin functions - * - * @return void - */ - protected function initAdminAuth() - { - $options = $this->getOptions(); - - if ($options->getAdminAuth()) { - $adminUser = $options->getAdminUser(); - $adminPass = $options->getAdminPass(); - - // backup HTTP authentication properties - if (isset($_SERVER['PHP_AUTH_USER'])) { - $this->backupAuth['PHP_AUTH_USER'] = $_SERVER['PHP_AUTH_USER']; - } - if (isset($_SERVER['PHP_AUTH_PW'])) { - $this->backupAuth['PHP_AUTH_PW'] = $_SERVER['PHP_AUTH_PW']; - } - - // set authentication - $_SERVER['PHP_AUTH_USER'] = $adminUser; - $_SERVER['PHP_AUTH_PW'] = $adminPass; - } - } - - /** - * Reset authentication after calling admin functions - * - * @return void - */ - protected function resetAdminAuth() - { - unset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); - $_SERVER = $this->backupAuth + $_SERVER; - $this->backupAuth = array(); - } - - /** - * Normalize metadata to work with XCache - * - * @param array $metadata - */ - protected function normalizeMetadata(array & $metadata) - { - $metadata['internal_key'] = &$metadata['name']; - unset($metadata['name']); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/XCacheOptions.php b/library/Zend/Cache/Storage/Adapter/XCacheOptions.php deleted file mode 100755 index 4c97136b7..000000000 --- a/library/Zend/Cache/Storage/Adapter/XCacheOptions.php +++ /dev/null @@ -1,146 +0,0 @@ -triggerOptionEvent('namespace_separator', $namespaceSeparator); - $this->namespaceSeparator = $namespaceSeparator; - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * Set username to call admin functions - * - * @param null|string $adminUser - * @return XCacheOptions - */ - public function setAdminUser($adminUser) - { - $adminUser = ($adminUser === null) ? null : (string) $adminUser; - if ($this->adminUser !== $adminUser) { - $this->triggerOptionEvent('admin_user', $adminUser); - $this->adminUser = $adminUser; - } - return $this; - } - - /** - * Get username to call admin functions - * - * @return string - */ - public function getAdminUser() - { - return $this->adminUser; - } - - /** - * Enable/Disable admin authentication handling - * - * @param bool $adminAuth - * @return XCacheOptions - */ - public function setAdminAuth($adminAuth) - { - $adminAuth = (bool) $adminAuth; - if ($this->adminAuth !== $adminAuth) { - $this->triggerOptionEvent('admin_auth', $adminAuth); - $this->adminAuth = $adminAuth; - } - return $this; - } - - /** - * Get admin authentication enabled - * - * @return bool - */ - public function getAdminAuth() - { - return $this->adminAuth; - } - - /** - * Set password to call admin functions - * - * @param null|string $adminPass - * @return XCacheOptions - */ - public function setAdminPass($adminPass) - { - $adminPass = ($adminPass === null) ? null : (string) $adminPass; - if ($this->adminPass !== $adminPass) { - $this->triggerOptionEvent('admin_pass', $adminPass); - $this->adminPass = $adminPass; - } - return $this; - } - - /** - * Get password to call admin functions - * - * @return string - */ - public function getAdminPass() - { - return $this->adminPass; - } -} diff --git a/library/Zend/Cache/Storage/Adapter/ZendServerDisk.php b/library/Zend/Cache/Storage/Adapter/ZendServerDisk.php deleted file mode 100755 index c48992a59..000000000 --- a/library/Zend/Cache/Storage/Adapter/ZendServerDisk.php +++ /dev/null @@ -1,186 +0,0 @@ -totalSpace === null) { - $path = ini_get('zend_datacache.disk.save_path'); - - ErrorHandler::start(); - $total = disk_total_space($path); - $error = ErrorHandler::stop(); - if ($total === false) { - throw new Exception\RuntimeException("Can't detect total space of '{$path}'", 0, $error); - } - - $this->totalSpace = $total; - } - return $this->totalSpace; - } - - /* AvailableSpaceCapableInterface */ - - /** - * Get available space in bytes - * - * @throws Exception\RuntimeException - * @return int|float - */ - public function getAvailableSpace() - { - $path = ini_get('zend_datacache.disk.save_path'); - - ErrorHandler::start(); - $avail = disk_free_space($path); - $error = ErrorHandler::stop(); - if ($avail === false) { - throw new Exception\RuntimeException("Can't detect free space of '{$path}'", 0, $error); - } - - return $avail; - } - - /* internal */ - - /** - * Store data into Zend Data Disk Cache - * - * @param string $internalKey - * @param mixed $value - * @param int $ttl - * @return void - * @throws Exception\RuntimeException - */ - protected function zdcStore($internalKey, $value, $ttl) - { - if (!zend_disk_cache_store($internalKey, $value, $ttl)) { - $valueType = gettype($value); - throw new Exception\RuntimeException( - "zend_disk_cache_store($internalKey, <{$valueType}>, {$ttl}) failed" - ); - } - } - - /** - * Fetch a single item from Zend Data Disk Cache - * - * @param string $internalKey - * @return mixed The stored value or NULL if item wasn't found - * @throws Exception\RuntimeException - */ - protected function zdcFetch($internalKey) - { - return zend_disk_cache_fetch((string) $internalKey); - } - - /** - * Fetch multiple items from Zend Data Disk Cache - * - * @param array $internalKeys - * @return array All found items - * @throws Exception\RuntimeException - */ - protected function zdcFetchMulti(array $internalKeys) - { - $items = zend_disk_cache_fetch($internalKeys); - if ($items === false) { - throw new Exception\RuntimeException("zend_disk_cache_fetch() failed"); - } - return $items; - } - - /** - * Delete data from Zend Data Disk Cache - * - * @param string $internalKey - * @return bool - * @throws Exception\RuntimeException - */ - protected function zdcDelete($internalKey) - { - return zend_disk_cache_delete($internalKey); - } -} diff --git a/library/Zend/Cache/Storage/Adapter/ZendServerShm.php b/library/Zend/Cache/Storage/Adapter/ZendServerShm.php deleted file mode 100755 index 6b226d7c0..000000000 --- a/library/Zend/Cache/Storage/Adapter/ZendServerShm.php +++ /dev/null @@ -1,141 +0,0 @@ -, {$ttl}) failed" - ); - } - } - - /** - * Fetch a single item from Zend Data SHM Cache - * - * @param string $internalKey - * @return mixed The stored value or NULL if item wasn't found - * @throws Exception\RuntimeException - */ - protected function zdcFetch($internalKey) - { - return zend_shm_cache_fetch((string) $internalKey); - } - - /** - * Fetch multiple items from Zend Data SHM Cache - * - * @param array $internalKeys - * @return array All found items - * @throws Exception\RuntimeException - */ - protected function zdcFetchMulti(array $internalKeys) - { - $items = zend_shm_cache_fetch($internalKeys); - if ($items === false) { - throw new Exception\RuntimeException("zend_shm_cache_fetch() failed"); - } - return $items; - } - - /** - * Delete data from Zend Data SHM Cache - * - * @param string $internalKey - * @return bool - * @throws Exception\RuntimeException - */ - protected function zdcDelete($internalKey) - { - return zend_shm_cache_delete($internalKey); - } -} diff --git a/library/Zend/Cache/Storage/AdapterPluginManager.php b/library/Zend/Cache/Storage/AdapterPluginManager.php deleted file mode 100755 index 665b36c81..000000000 --- a/library/Zend/Cache/Storage/AdapterPluginManager.php +++ /dev/null @@ -1,74 +0,0 @@ - 'Zend\Cache\Storage\Adapter\Apc', - 'blackhole' => 'Zend\Cache\Storage\Adapter\BlackHole', - 'dba' => 'Zend\Cache\Storage\Adapter\Dba', - 'filesystem' => 'Zend\Cache\Storage\Adapter\Filesystem', - 'memcache' => 'Zend\Cache\Storage\Adapter\Memcache', - 'memcached' => 'Zend\Cache\Storage\Adapter\Memcached', - 'memory' => 'Zend\Cache\Storage\Adapter\Memory', - 'redis' => 'Zend\Cache\Storage\Adapter\Redis', - 'session' => 'Zend\Cache\Storage\Adapter\Session', - 'xcache' => 'Zend\Cache\Storage\Adapter\XCache', - 'wincache' => 'Zend\Cache\Storage\Adapter\WinCache', - 'zendserverdisk' => 'Zend\Cache\Storage\Adapter\ZendServerDisk', - 'zendservershm' => 'Zend\Cache\Storage\Adapter\ZendServerShm', - ); - - /** - * Do not share by default - * - * @var array - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the adapter loaded is an instance of StorageInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\RuntimeException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof StorageInterface) { - // we're okay - return; - } - - throw new Exception\RuntimeException(sprintf( - 'Plugin of type %s is invalid; must implement %s\StorageInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Cache/Storage/AvailableSpaceCapableInterface.php b/library/Zend/Cache/Storage/AvailableSpaceCapableInterface.php deleted file mode 100755 index 5088fe255..000000000 --- a/library/Zend/Cache/Storage/AvailableSpaceCapableInterface.php +++ /dev/null @@ -1,20 +0,0 @@ -storage = $storage; - $this->marker = $marker; - $this->baseCapabilities = $baseCapabilities; - - foreach ($capabilities as $name => $value) { - $this->setCapability($marker, $name, $value); - } - } - - /** - * Get the storage adapter - * - * @return StorageInterface - */ - public function getAdapter() - { - return $this->storage; - } - - /** - * Get supported datatypes - * - * @return array - */ - public function getSupportedDatatypes() - { - return $this->getCapability('supportedDatatypes', array( - 'NULL' => false, - 'boolean' => false, - 'integer' => false, - 'double' => false, - 'string' => true, - 'array' => false, - 'object' => false, - 'resource' => false, - )); - } - - /** - * Set supported datatypes - * - * @param stdClass $marker - * @param array $datatypes - * @throws Exception\InvalidArgumentException - * @return Capabilities Fluent interface - */ - public function setSupportedDatatypes(stdClass $marker, array $datatypes) - { - $allTypes = array( - 'array', - 'boolean', - 'double', - 'integer', - 'NULL', - 'object', - 'resource', - 'string', - ); - - // check/normalize datatype values - foreach ($datatypes as $type => &$toType) { - if (!in_array($type, $allTypes)) { - throw new Exception\InvalidArgumentException("Unknown datatype '{$type}'"); - } - - if (is_string($toType)) { - $toType = strtolower($toType); - if (!in_array($toType, $allTypes)) { - throw new Exception\InvalidArgumentException("Unknown datatype '{$toType}'"); - } - } else { - $toType = (bool) $toType; - } - } - - // add missing datatypes as not supported - $missingTypes = array_diff($allTypes, array_keys($datatypes)); - foreach ($missingTypes as $type) { - $datatypes[$type] = false; - } - - return $this->setCapability($marker, 'supportedDatatypes', $datatypes); - } - - /** - * Get supported metadata - * - * @return array - */ - public function getSupportedMetadata() - { - return $this->getCapability('supportedMetadata', array()); - } - - /** - * Set supported metadata - * - * @param stdClass $marker - * @param string[] $metadata - * @throws Exception\InvalidArgumentException - * @return Capabilities Fluent interface - */ - public function setSupportedMetadata(stdClass $marker, array $metadata) - { - foreach ($metadata as $name) { - if (!is_string($name)) { - throw new Exception\InvalidArgumentException('$metadata must be an array of strings'); - } - } - return $this->setCapability($marker, 'supportedMetadata', $metadata); - } - - /** - * Get minimum supported time-to-live - * - * @return int 0 means items never expire - */ - public function getMinTtl() - { - return $this->getCapability('minTtl', 0); - } - - /** - * Set minimum supported time-to-live - * - * @param stdClass $marker - * @param int $minTtl - * @throws Exception\InvalidArgumentException - * @return Capabilities Fluent interface - */ - public function setMinTtl(stdClass $marker, $minTtl) - { - $minTtl = (int) $minTtl; - if ($minTtl < 0) { - throw new Exception\InvalidArgumentException('$minTtl must be greater or equal 0'); - } - return $this->setCapability($marker, 'minTtl', $minTtl); - } - - /** - * Get maximum supported time-to-live - * - * @return int 0 means infinite - */ - public function getMaxTtl() - { - return $this->getCapability('maxTtl', 0); - } - - /** - * Set maximum supported time-to-live - * - * @param stdClass $marker - * @param int $maxTtl - * @throws Exception\InvalidArgumentException - * @return Capabilities Fluent interface - */ - public function setMaxTtl(stdClass $marker, $maxTtl) - { - $maxTtl = (int) $maxTtl; - if ($maxTtl < 0) { - throw new Exception\InvalidArgumentException('$maxTtl must be greater or equal 0'); - } - return $this->setCapability($marker, 'maxTtl', $maxTtl); - } - - /** - * Is the time-to-live handled static (on write) - * or dynamic (on read) - * - * @return bool - */ - public function getStaticTtl() - { - return $this->getCapability('staticTtl', false); - } - - /** - * Set if the time-to-live handled static (on write) or dynamic (on read) - * - * @param stdClass $marker - * @param bool $flag - * @return Capabilities Fluent interface - */ - public function setStaticTtl(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'staticTtl', (bool) $flag); - } - - /** - * Get time-to-live precision - * - * @return float - */ - public function getTtlPrecision() - { - return $this->getCapability('ttlPrecision', 1); - } - - /** - * Set time-to-live precision - * - * @param stdClass $marker - * @param float $ttlPrecision - * @throws Exception\InvalidArgumentException - * @return Capabilities Fluent interface - */ - public function setTtlPrecision(stdClass $marker, $ttlPrecision) - { - $ttlPrecision = (float) $ttlPrecision; - if ($ttlPrecision <= 0) { - throw new Exception\InvalidArgumentException('$ttlPrecision must be greater than 0'); - } - return $this->setCapability($marker, 'ttlPrecision', $ttlPrecision); - } - - /** - * Get use request time - * - * @return bool - */ - public function getUseRequestTime() - { - return $this->getCapability('useRequestTime', false); - } - - /** - * Set use request time - * - * @param stdClass $marker - * @param bool $flag - * @return Capabilities Fluent interface - */ - public function setUseRequestTime(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'useRequestTime', (bool) $flag); - } - - /** - * Get if expired items are readable - * - * @return bool - */ - public function getExpiredRead() - { - return $this->getCapability('expiredRead', false); - } - - /** - * Set if expired items are readable - * - * @param stdClass $marker - * @param bool $flag - * @return Capabilities Fluent interface - */ - public function setExpiredRead(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'expiredRead', (bool) $flag); - } - - /** - * Get maximum key lenth - * - * @return int -1 means unknown, 0 means infinite - */ - public function getMaxKeyLength() - { - return $this->getCapability('maxKeyLength', -1); - } - - /** - * Set maximum key length - * - * @param stdClass $marker - * @param int $maxKeyLength - * @throws Exception\InvalidArgumentException - * @return Capabilities Fluent interface - */ - public function setMaxKeyLength(stdClass $marker, $maxKeyLength) - { - $maxKeyLength = (int) $maxKeyLength; - if ($maxKeyLength < -1) { - throw new Exception\InvalidArgumentException('$maxKeyLength must be greater or equal than -1'); - } - return $this->setCapability($marker, 'maxKeyLength', $maxKeyLength); - } - - /** - * Get if namespace support is implemented as prefix - * - * @return bool - */ - public function getNamespaceIsPrefix() - { - return $this->getCapability('namespaceIsPrefix', true); - } - - /** - * Set if namespace support is implemented as prefix - * - * @param stdClass $marker - * @param bool $flag - * @return Capabilities Fluent interface - */ - public function setNamespaceIsPrefix(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'namespaceIsPrefix', (bool) $flag); - } - - /** - * Get namespace separator if namespace is implemented as prefix - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->getCapability('namespaceSeparator', ''); - } - - /** - * Set the namespace separator if namespace is implemented as prefix - * - * @param stdClass $marker - * @param string $separator - * @return Capabilities Fluent interface - */ - public function setNamespaceSeparator(stdClass $marker, $separator) - { - return $this->setCapability($marker, 'namespaceSeparator', (string) $separator); - } - - /** - * Get a capability - * - * @param string $property - * @param mixed $default - * @return mixed - */ - protected function getCapability($property, $default = null) - { - if ($this->$property !== null) { - return $this->$property; - } elseif ($this->baseCapabilities) { - $getMethod = 'get' . $property; - return $this->baseCapabilities->$getMethod(); - } - return $default; - } - - /** - * Change a capability - * - * @param stdClass $marker - * @param string $property - * @param mixed $value - * @return Capabilities Fluent interface - * @throws Exception\InvalidArgumentException - */ - protected function setCapability(stdClass $marker, $property, $value) - { - if ($this->marker !== $marker) { - throw new Exception\InvalidArgumentException('Invalid marker'); - } - - if ($this->$property !== $value) { - $this->$property = $value; - - // trigger event - if ($this->storage instanceof EventsCapableInterface) { - $this->storage->getEventManager()->trigger('capability', $this->storage, new ArrayObject(array( - $property => $value - ))); - } - } - - return $this; - } -} diff --git a/library/Zend/Cache/Storage/ClearByNamespaceInterface.php b/library/Zend/Cache/Storage/ClearByNamespaceInterface.php deleted file mode 100755 index 15fb4e756..000000000 --- a/library/Zend/Cache/Storage/ClearByNamespaceInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -setStorage($target); - } - - /** - * Alias of setTarget - * - * @param StorageInterface $storage - * @return Event - * @see Zend\EventManager\Event::setTarget() - */ - public function setStorage(StorageInterface $storage) - { - $this->target = $storage; - return $this; - } - - /** - * Alias of getTarget - * - * @return StorageInterface - */ - public function getStorage() - { - return $this->getTarget(); - } -} diff --git a/library/Zend/Cache/Storage/ExceptionEvent.php b/library/Zend/Cache/Storage/ExceptionEvent.php deleted file mode 100755 index e9ffb4a0c..000000000 --- a/library/Zend/Cache/Storage/ExceptionEvent.php +++ /dev/null @@ -1,91 +0,0 @@ -setException($exception); - } - - /** - * Set the exception to be thrown - * - * @param Exception $exception - * @return ExceptionEvent - */ - public function setException(Exception $exception) - { - $this->exception = $exception; - return $this; - } - - /** - * Get the exception to be thrown - * - * @return Exception - */ - public function getException() - { - return $this->exception; - } - - /** - * Throw the exception or use the result - * - * @param bool $flag - * @return ExceptionEvent - */ - public function setThrowException($flag) - { - $this->throwException = (bool) $flag; - return $this; - } - - /** - * Throw the exception or use the result - * - * @return bool - */ - public function getThrowException() - { - return $this->throwException; - } -} diff --git a/library/Zend/Cache/Storage/FlushableInterface.php b/library/Zend/Cache/Storage/FlushableInterface.php deleted file mode 100755 index 6c72541e6..000000000 --- a/library/Zend/Cache/Storage/FlushableInterface.php +++ /dev/null @@ -1,20 +0,0 @@ -options = $options; - return $this; - } - - /** - * Get all pattern options - * - * @return PluginOptions - */ - public function getOptions() - { - if (null === $this->options) { - $this->setOptions(new PluginOptions()); - } - return $this->options; - } -} diff --git a/library/Zend/Cache/Storage/Plugin/ClearExpiredByFactor.php b/library/Zend/Cache/Storage/Plugin/ClearExpiredByFactor.php deleted file mode 100755 index 0b257be77..000000000 --- a/library/Zend/Cache/Storage/Plugin/ClearExpiredByFactor.php +++ /dev/null @@ -1,49 +0,0 @@ -listeners[] = $events->attach('setItem.post', $callback, $priority); - $this->listeners[] = $events->attach('setItems.post', $callback, $priority); - $this->listeners[] = $events->attach('addItem.post', $callback, $priority); - $this->listeners[] = $events->attach('addItems.post', $callback, $priority); - } - - /** - * Clear expired items by factor after writing new item(s) - * - * @param PostEvent $event - * @return void - */ - public function clearExpiredByFactor(PostEvent $event) - { - $storage = $event->getStorage(); - if (!($storage instanceof ClearExpiredInterface)) { - return; - } - - $factor = $this->getOptions()->getClearingFactor(); - if ($factor && mt_rand(1, $factor) == 1) { - $storage->clearExpired(); - } - } -} diff --git a/library/Zend/Cache/Storage/Plugin/ExceptionHandler.php b/library/Zend/Cache/Storage/Plugin/ExceptionHandler.php deleted file mode 100755 index e6acace0c..000000000 --- a/library/Zend/Cache/Storage/Plugin/ExceptionHandler.php +++ /dev/null @@ -1,79 +0,0 @@ -listeners[] = $events->attach('getItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('getItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('hasItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('hasItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('getMetadata.exception', $callback, $priority); - $this->listeners[] = $events->attach('getMetadatas.exception', $callback, $priority); - - // write - $this->listeners[] = $events->attach('setItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('setItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('addItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('addItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('replaceItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('replaceItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('touchItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('touchItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('removeItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('removeItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('checkAndSetItem.exception', $callback, $priority); - - // increment / decrement item(s) - $this->listeners[] = $events->attach('incrementItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('incrementItems.exception', $callback, $priority); - - $this->listeners[] = $events->attach('decrementItem.exception', $callback, $priority); - $this->listeners[] = $events->attach('decrementItems.exception', $callback, $priority); - - // utility - $this->listeners[] = $events->attach('clearExpired.exception', $callback, $priority); - } - - /** - * On exception - * - * @param ExceptionEvent $event - * @return void - */ - public function onException(ExceptionEvent $event) - { - $options = $this->getOptions(); - $callback = $options->getExceptionCallback(); - if ($callback) { - call_user_func($callback, $event->getException()); - } - - $event->setThrowException($options->getThrowExceptions()); - } -} diff --git a/library/Zend/Cache/Storage/Plugin/IgnoreUserAbort.php b/library/Zend/Cache/Storage/Plugin/IgnoreUserAbort.php deleted file mode 100755 index ddec6354c..000000000 --- a/library/Zend/Cache/Storage/Plugin/IgnoreUserAbort.php +++ /dev/null @@ -1,117 +0,0 @@ -listeners[] = $events->attach('setItem.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('setItem.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('setItem.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('setItems.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('setItems.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('setItems.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('addItem.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('addItem.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('addItem.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('addItems.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('addItems.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('addItems.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('replaceItem.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('replaceItem.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('replaceItem.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('replaceItems.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('replaceItems.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('replaceItems.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('checkAndSetItem.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('checkAndSetItem.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('checkAndSetItem.exception', $cbOnAfter, $priority); - - // increment / decrement item(s) - $this->listeners[] = $events->attach('incrementItem.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('incrementItem.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('incrementItem.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('incrementItems.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('incrementItems.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('incrementItems.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('decrementItem.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('decrementItem.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('decrementItem.exception', $cbOnAfter, $priority); - - $this->listeners[] = $events->attach('decrementItems.pre', $cbOnBefore, $priority); - $this->listeners[] = $events->attach('decrementItems.post', $cbOnAfter, $priority); - $this->listeners[] = $events->attach('decrementItems.exception', $cbOnAfter, $priority); - } - - /** - * Activate ignore_user_abort if not already done - * and save the target who activated it. - * - * @param Event $event - * @return void - */ - public function onBefore(Event $event) - { - if ($this->activatedTarget === null && !ignore_user_abort(true)) { - $this->activatedTarget = $event->getTarget(); - } - } - - /** - * Reset ignore_user_abort if it's activated and if it's the same target - * who activated it. - * - * If exit_on_abort is enabled and the connection has been aborted - * exit the script. - * - * @param Event $event - * @return void - */ - public function onAfter(Event $event) - { - if ($this->activatedTarget === $event->getTarget()) { - // exit if connection aborted - if ($this->getOptions()->getExitOnAbort() && connection_aborted()) { - exit; - } - - // reset ignore_user_abort - ignore_user_abort(false); - - // remove activated target - $this->activatedTarget = null; - } - } -} diff --git a/library/Zend/Cache/Storage/Plugin/OptimizeByFactor.php b/library/Zend/Cache/Storage/Plugin/OptimizeByFactor.php deleted file mode 100755 index 42643df7a..000000000 --- a/library/Zend/Cache/Storage/Plugin/OptimizeByFactor.php +++ /dev/null @@ -1,46 +0,0 @@ -listeners[] = $events->attach('removeItem.post', $callback, $priority); - $this->listeners[] = $events->attach('removeItems.post', $callback, $priority); - } - - /** - * Optimize by factor on a success _RESULT_ - * - * @param PostEvent $event - * @return void - */ - public function optimizeByFactor(PostEvent $event) - { - $storage = $event->getStorage(); - if (!($storage instanceof OptimizableInterface)) { - return; - } - - $factor = $this->getOptions()->getOptimizingFactor(); - if ($factor && mt_rand(1, $factor) == 1) { - $storage->optimize(); - } - } -} diff --git a/library/Zend/Cache/Storage/Plugin/PluginInterface.php b/library/Zend/Cache/Storage/Plugin/PluginInterface.php deleted file mode 100755 index af3d007ca..000000000 --- a/library/Zend/Cache/Storage/Plugin/PluginInterface.php +++ /dev/null @@ -1,30 +0,0 @@ -clearingFactor = $this->normalizeFactor($clearingFactor); - return $this; - } - - /** - * Get automatic clearing factor - * - * Used by: - * - ClearExpiredByFactor - * - * @return int - */ - public function getClearingFactor() - { - return $this->clearingFactor; - } - - /** - * Set callback to call on intercepted exception - * - * Used by: - * - ExceptionHandler - * - * @param callable $exceptionCallback - * @throws Exception\InvalidArgumentException - * @return PluginOptions - */ - public function setExceptionCallback($exceptionCallback) - { - if ($exceptionCallback !== null && !is_callable($exceptionCallback, true)) { - throw new Exception\InvalidArgumentException('Not a valid callback'); - } - $this->exceptionCallback = $exceptionCallback; - return $this; - } - - /** - * Get callback to call on intercepted exception - * - * Used by: - * - ExceptionHandler - * - * @return callable - */ - public function getExceptionCallback() - { - return $this->exceptionCallback; - } - - /** - * Exit if connection aborted and ignore_user_abort is disabled. - * - * @param bool $exitOnAbort - * @return PluginOptions - */ - public function setExitOnAbort($exitOnAbort) - { - $this->exitOnAbort = (bool) $exitOnAbort; - return $this; - } - - /** - * Exit if connection aborted and ignore_user_abort is disabled. - * - * @return bool - */ - public function getExitOnAbort() - { - return $this->exitOnAbort; - } - - /** - * Set automatic optimizing factor - * - * Used by: - * - OptimizeByFactor - * - * @param int $optimizingFactor - * @return PluginOptions - */ - public function setOptimizingFactor($optimizingFactor) - { - $this->optimizingFactor = $this->normalizeFactor($optimizingFactor); - return $this; - } - - /** - * Set automatic optimizing factor - * - * Used by: - * - OptimizeByFactor - * - * @return int - */ - public function getOptimizingFactor() - { - return $this->optimizingFactor; - } - - /** - * Set serializer - * - * Used by: - * - Serializer - * - * @param string|SerializerAdapter $serializer - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setSerializer($serializer) - { - if (!is_string($serializer) && !$serializer instanceof SerializerAdapter) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects either a string serializer name or Zend\Serializer\Adapter\AdapterInterface instance; ' - . 'received "%s"', - __METHOD__, - (is_object($serializer) ? get_class($serializer) : gettype($serializer)) - )); - } - $this->serializer = $serializer; - return $this; - } - - /** - * Get serializer - * - * Used by: - * - Serializer - * - * @return SerializerAdapter - */ - public function getSerializer() - { - if (!$this->serializer instanceof SerializerAdapter) { - // use default serializer - if (!$this->serializer) { - $this->setSerializer(SerializerFactory::getDefaultAdapter()); - // instantiate by class name + serializer_options - } else { - $options = $this->getSerializerOptions(); - $this->setSerializer(SerializerFactory::factory($this->serializer, $options)); - } - } - return $this->serializer; - } - - /** - * Set configuration options for instantiating a serializer adapter - * - * Used by: - * - Serializer - * - * @param mixed $serializerOptions - * @return PluginOptions - */ - public function setSerializerOptions($serializerOptions) - { - $this->serializerOptions = $serializerOptions; - return $this; - } - - /** - * Get configuration options for instantiating a serializer adapter - * - * Used by: - * - Serializer - * - * @return array - */ - public function getSerializerOptions() - { - return $this->serializerOptions; - } - - /** - * Set flag indicating we should re-throw exceptions - * - * Used by: - * - ExceptionHandler - * - * @param bool $throwExceptions - * @return PluginOptions - */ - public function setThrowExceptions($throwExceptions) - { - $this->throwExceptions = (bool) $throwExceptions; - return $this; - } - - /** - * Should we re-throw exceptions? - * - * Used by: - * - ExceptionHandler - * - * @return bool - */ - public function getThrowExceptions() - { - return $this->throwExceptions; - } - - /** - * Normalize a factor - * - * Cast to int and ensure we have a value greater than zero. - * - * @param int $factor - * @return int - * @throws Exception\InvalidArgumentException - */ - protected function normalizeFactor($factor) - { - $factor = (int) $factor; - if ($factor < 0) { - throw new Exception\InvalidArgumentException( - "Invalid factor '{$factor}': must be greater or equal 0" - ); - } - return $factor; - } -} diff --git a/library/Zend/Cache/Storage/Plugin/Serializer.php b/library/Zend/Cache/Storage/Plugin/Serializer.php deleted file mode 100755 index c785e751e..000000000 --- a/library/Zend/Cache/Storage/Plugin/Serializer.php +++ /dev/null @@ -1,259 +0,0 @@ -listeners[] = $events->attach('getItem.post', array($this, 'onReadItemPost'), $postPriority); - $this->listeners[] = $events->attach('getItems.post', array($this, 'onReadItemsPost'), $postPriority); - - // write - $this->listeners[] = $events->attach('setItem.pre', array($this, 'onWriteItemPre'), $prePriority); - $this->listeners[] = $events->attach('setItems.pre', array($this, 'onWriteItemsPre'), $prePriority); - - $this->listeners[] = $events->attach('addItem.pre', array($this, 'onWriteItemPre'), $prePriority); - $this->listeners[] = $events->attach('addItems.pre', array($this, 'onWriteItemsPre'), $prePriority); - - $this->listeners[] = $events->attach('replaceItem.pre', array($this, 'onWriteItemPre'), $prePriority); - $this->listeners[] = $events->attach('replaceItems.pre', array($this, 'onWriteItemsPre'), $prePriority); - - $this->listeners[] = $events->attach('checkAndSetItem.pre', array($this, 'onWriteItemPre'), $prePriority); - - // increment / decrement item(s) - $this->listeners[] = $events->attach('incrementItem.pre', array($this, 'onIncrementItemPre'), $prePriority); - $this->listeners[] = $events->attach('incrementItems.pre', array($this, 'onIncrementItemsPre'), $prePriority); - - $this->listeners[] = $events->attach('decrementItem.pre', array($this, 'onDecrementItemPre'), $prePriority); - $this->listeners[] = $events->attach('decrementItems.pre', array($this, 'onDecrementItemsPre'), $prePriority); - - // overwrite capabilities - $this->listeners[] = $events->attach('getCapabilities.post', array($this, 'onGetCapabilitiesPost'), $postPriority); - } - - /** - * On read item post - * - * @param PostEvent $event - * @return void - */ - public function onReadItemPost(PostEvent $event) - { - $serializer = $this->getOptions()->getSerializer(); - $result = $event->getResult(); - $result = $serializer->unserialize($result); - $event->setResult($result); - } - - /** - * On read items post - * - * @param PostEvent $event - * @return void - */ - public function onReadItemsPost(PostEvent $event) - { - $serializer = $this->getOptions()->getSerializer(); - $result = $event->getResult(); - foreach ($result as &$value) { - $value = $serializer->unserialize($value); - } - $event->setResult($result); - } - - /** - * On write item pre - * - * @param Event $event - * @return void - */ - public function onWriteItemPre(Event $event) - { - $serializer = $this->getOptions()->getSerializer(); - $params = $event->getParams(); - $params['value'] = $serializer->serialize($params['value']); - } - - /** - * On write items pre - * - * @param Event $event - * @return void - */ - public function onWriteItemsPre(Event $event) - { - $serializer = $this->getOptions()->getSerializer(); - $params = $event->getParams(); - foreach ($params['keyValuePairs'] as &$value) { - $value = $serializer->serialize($value); - } - } - - /** - * On increment item pre - * - * @param Event $event - * @return mixed - */ - public function onIncrementItemPre(Event $event) - { - $storage = $event->getTarget(); - $params = $event->getParams(); - $casToken = null; - $success = null; - $oldValue = $storage->getItem($params['key'], $success, $casToken); - $newValue = $oldValue + $params['value']; - - if ($success) { - $storage->checkAndSetItem($casToken, $params['key'], $oldValue + $params['value']); - $result = $newValue; - } else { - $result = false; - } - - $event->stopPropagation(true); - return $result; - } - - /** - * On increment items pre - * - * @param Event $event - * @return mixed - */ - public function onIncrementItemsPre(Event $event) - { - $storage = $event->getTarget(); - $params = $event->getParams(); - $keyValuePairs = $storage->getItems(array_keys($params['keyValuePairs'])); - foreach ($params['keyValuePairs'] as $key => & $value) { - if (isset($keyValuePairs[$key])) { - $keyValuePairs[$key]+= $value; - } else { - $keyValuePairs[$key] = $value; - } - } - - $failedKeys = $storage->setItems($keyValuePairs); - foreach ($failedKeys as $failedKey) { - unset($keyValuePairs[$failedKey]); - } - - $event->stopPropagation(true); - return $keyValuePairs; - } - - /** - * On decrement item pre - * - * @param Event $event - * @return mixed - */ - public function onDecrementItemPre(Event $event) - { - $storage = $event->getTarget(); - $params = $event->getParams(); - $success = null; - $casToken = null; - $oldValue = $storage->getItem($params['key'], $success, $casToken); - $newValue = $oldValue - $params['value']; - - if ($success) { - $storage->checkAndSetItem($casToken, $params['key'], $oldValue + $params['value']); - $result = $newValue; - } else { - $result = false; - } - - $event->stopPropagation(true); - return $result; - } - - /** - * On decrement items pre - * - * @param Event $event - * @return mixed - */ - public function onDecrementItemsPre(Event $event) - { - $storage = $event->getTarget(); - $params = $event->getParams(); - $keyValuePairs = $storage->getItems(array_keys($params['keyValuePairs'])); - foreach ($params['keyValuePairs'] as $key => &$value) { - if (isset($keyValuePairs[$key])) { - $keyValuePairs[$key]-= $value; - } else { - $keyValuePairs[$key] = -$value; - } - } - - $failedKeys = $storage->setItems($keyValuePairs); - foreach ($failedKeys as $failedKey) { - unset($keyValuePairs[$failedKey]); - } - - $event->stopPropagation(true); - return $keyValuePairs; - } - - /** - * On get capabilities - * - * @param PostEvent $event - * @return void - */ - public function onGetCapabilitiesPost(PostEvent $event) - { - $baseCapabilities = $event->getResult(); - $index = spl_object_hash($baseCapabilities); - - if (!isset($this->capabilities[$index])) { - $this->capabilities[$index] = new Capabilities( - $baseCapabilities->getAdapter(), - new stdClass(), // marker - array('supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - )), - $baseCapabilities - ); - } - - $event->setResult($this->capabilities[$index]); - } -} diff --git a/library/Zend/Cache/Storage/PluginManager.php b/library/Zend/Cache/Storage/PluginManager.php deleted file mode 100755 index a799a37d3..000000000 --- a/library/Zend/Cache/Storage/PluginManager.php +++ /dev/null @@ -1,66 +0,0 @@ - 'Zend\Cache\Storage\Plugin\ClearExpiredByFactor', - 'exceptionhandler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', - 'ignoreuserabort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', - 'optimizebyfactor' => 'Zend\Cache\Storage\Plugin\OptimizeByFactor', - 'serializer' => 'Zend\Cache\Storage\Plugin\Serializer', - ); - - /** - * Do not share by default - * - * @var array - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the plugin loaded is an instance of Plugin\PluginInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\RuntimeException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Plugin\PluginInterface) { - // we're okay - return; - } - - throw new Exception\RuntimeException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Plugin\PluginInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Cache/Storage/PostEvent.php b/library/Zend/Cache/Storage/PostEvent.php deleted file mode 100755 index 9302b0814..000000000 --- a/library/Zend/Cache/Storage/PostEvent.php +++ /dev/null @@ -1,60 +0,0 @@ -setResult($result); - } - - /** - * Set the result/return value - * - * @param mixed $value - * @return PostEvent - */ - public function setResult(& $value) - { - $this->result = & $value; - return $this; - } - - /** - * Get the result/return value - * - * @return mixed - */ - public function & getResult() - { - return $this->result; - } -} diff --git a/library/Zend/Cache/Storage/StorageInterface.php b/library/Zend/Cache/Storage/StorageInterface.php deleted file mode 100755 index c89ca5bef..000000000 --- a/library/Zend/Cache/Storage/StorageInterface.php +++ /dev/null @@ -1,246 +0,0 @@ - $v) { - $pluginPrio = 1; // default priority - - if (is_string($k)) { - if (!is_array($v)) { - throw new Exception\InvalidArgumentException( - "'plugins.{$k}' needs to be an array" - ); - } - $pluginName = $k; - $pluginOptions = $v; - } elseif (is_array($v)) { - if (!isset($v['name'])) { - throw new Exception\InvalidArgumentException("Invalid plugins[{$k}] or missing plugins[{$k}].name"); - } - $pluginName = (string) $v['name']; - - if (isset($v['options'])) { - $pluginOptions = $v['options']; - } else { - $pluginOptions = array(); - } - - if (isset($v['priority'])) { - $pluginPrio = $v['priority']; - } - } else { - $pluginName = $v; - $pluginOptions = array(); - } - - $plugin = static::pluginFactory($pluginName, $pluginOptions); - $adapter->addPlugin($plugin, $pluginPrio); - } - } - - return $adapter; - } - - /** - * Instantiate a storage adapter - * - * @param string|Storage\StorageInterface $adapterName - * @param array|Traversable|Storage\Adapter\AdapterOptions $options - * @return Storage\StorageInterface - * @throws Exception\RuntimeException - */ - public static function adapterFactory($adapterName, $options = array()) - { - if ($adapterName instanceof Storage\StorageInterface) { - // $adapterName is already an adapter object - $adapter = $adapterName; - } else { - $adapter = static::getAdapterPluginManager()->get($adapterName); - } - - if ($options) { - $adapter->setOptions($options); - } - - return $adapter; - } - - /** - * Get the adapter plugin manager - * - * @return Storage\AdapterPluginManager - */ - public static function getAdapterPluginManager() - { - if (static::$adapters === null) { - static::$adapters = new Storage\AdapterPluginManager(); - } - return static::$adapters; - } - - /** - * Change the adapter plugin manager - * - * @param Storage\AdapterPluginManager $adapters - * @return void - */ - public static function setAdapterPluginManager(Storage\AdapterPluginManager $adapters) - { - static::$adapters = $adapters; - } - - /** - * Resets the internal adapter plugin manager - * - * @return void - */ - public static function resetAdapterPluginManager() - { - static::$adapters = null; - } - - /** - * Instantiate a storage plugin - * - * @param string|Storage\Plugin\PluginInterface $pluginName - * @param array|Traversable|Storage\Plugin\PluginOptions $options - * @return Storage\Plugin\PluginInterface - * @throws Exception\RuntimeException - */ - public static function pluginFactory($pluginName, $options = array()) - { - if ($pluginName instanceof Storage\Plugin\PluginInterface) { - // $pluginName is already a plugin object - $plugin = $pluginName; - } else { - $plugin = static::getPluginManager()->get($pluginName); - } - - if (!$options instanceof Storage\Plugin\PluginOptions) { - $options = new Storage\Plugin\PluginOptions($options); - } - - if ($options) { - $plugin->setOptions($options); - } - - return $plugin; - } - - /** - * Get the plugin manager - * - * @return Storage\PluginManager - */ - public static function getPluginManager() - { - if (static::$plugins === null) { - static::$plugins = new Storage\PluginManager(); - } - return static::$plugins; - } - - /** - * Change the plugin manager - * - * @param Storage\PluginManager $plugins - * @return void - */ - public static function setPluginManager(Storage\PluginManager $plugins) - { - static::$plugins = $plugins; - } - - /** - * Resets the internal plugin manager - * - * @return void - */ - public static function resetPluginManager() - { - static::$plugins = null; - } -} diff --git a/library/Zend/Cache/composer.json b/library/Zend/Cache/composer.json deleted file mode 100755 index 3d20dff9a..000000000 --- a/library/Zend/Cache/composer.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "zendframework/zend-cache", - "description": "provides a generic way to cache any data", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "cache" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Cache\\": "" - } - }, - "target-dir": "Zend/Cache", - "require": { - "php": ">=5.3.23", - "zendframework/zend-stdlib": "self.version", - "zendframework/zend-servicemanager": "self.version", - "zendframework/zend-serializer": "self.version", - "zendframework/zend-eventmanager": "self.version" - }, - "require-dev": { - "zendframework/zend-session": "self.version" - }, - "suggest": { - "zendframework/zend-serializer": "Zend\\Serializer component", - "zendframework/zend-session": "Zend\\Session component", - "ext-apc": "APC >= 3.1.6 to use the APC storage adapter", - "ext-dba": "DBA, to use the DBA storage adapter", - "ext-memcached": "Memcached >= 1.0.0 to use the Memcached storage adapter", - "ext-wincache": "WinCache, to use the WinCache storage adapter" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Captcha/AbstractAdapter.php b/library/Zend/Captcha/AbstractAdapter.php deleted file mode 100755 index 11784d69e..000000000 --- a/library/Zend/Captcha/AbstractAdapter.php +++ /dev/null @@ -1,135 +0,0 @@ -name; - } - - /** - * Set name - * - * @param string $name - * @return AbstractAdapter - */ - public function setName($name) - { - $this->name = $name; - return $this; - } - - /** - * Set single option for the object - * - * @param string $key - * @param string $value - * @return AbstractAdapter - */ - public function setOption($key, $value) - { - if (in_array(strtolower($key), $this->skipOptions)) { - return $this; - } - - $method = 'set' . ucfirst($key); - if (method_exists($this, $method)) { - // Setter exists; use it - $this->$method($value); - $this->options[$key] = $value; - } elseif (property_exists($this, $key)) { - // Assume it's metadata - $this->$key = $value; - $this->options[$key] = $value; - } - return $this; - } - - /** - * Set object state from options array - * - * @param array|Traversable $options - * @throws Exception\InvalidArgumentException - * @return AbstractAdapter - */ - public function setOptions($options = array()) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable'); - } - - foreach ($options as $key => $value) { - $this->setOption($key, $value); - } - return $this; - } - - /** - * Retrieve options representing object state - * - * @return array - */ - public function getOptions() - { - return $this->options; - } - - /** - * Get helper name used to render captcha - * - * By default, return empty string, indicating no helper needed. - * - * @return string - */ - public function getHelperName() - { - return ''; - } -} diff --git a/library/Zend/Captcha/AbstractWord.php b/library/Zend/Captcha/AbstractWord.php deleted file mode 100755 index 5ad803661..000000000 --- a/library/Zend/Captcha/AbstractWord.php +++ /dev/null @@ -1,407 +0,0 @@ - 'Empty captcha value', - self::MISSING_ID => 'Captcha ID field is missing', - self::BAD_CAPTCHA => 'Captcha value is wrong', - ); - - /** - * Length of the word to generate - * - * @var int - */ - protected $wordlen = 8; - - /** - * Retrieve session class to utilize - * - * @return string - */ - public function getSessionClass() - { - return $this->sessionClass; - } - - /** - * Set session class for persistence - * - * @param string $sessionClass - * @return AbstractWord - */ - public function setSessionClass($sessionClass) - { - $this->sessionClass = $sessionClass; - return $this; - } - - /** - * Retrieve word length to use when generating captcha - * - * @return int - */ - public function getWordlen() - { - return $this->wordlen; - } - - /** - * Set word length of captcha - * - * @param int $wordlen - * @return AbstractWord - */ - public function setWordlen($wordlen) - { - $this->wordlen = $wordlen; - return $this; - } - - /** - * Retrieve captcha ID - * - * @return string - */ - public function getId() - { - if (null === $this->id) { - $this->setId($this->generateRandomId()); - } - return $this->id; - } - - /** - * Set captcha identifier - * - * @param string $id - * @return AbstractWord - */ - protected function setId($id) - { - $this->id = $id; - return $this; - } - - /** - * Set timeout for session token - * - * @param int $ttl - * @return AbstractWord - */ - public function setTimeout($ttl) - { - $this->timeout = (int) $ttl; - return $this; - } - - /** - * Get session token timeout - * - * @return int - */ - public function getTimeout() - { - return $this->timeout; - } - - /** - * Sets if session should be preserved on generate() - * - * @param bool $keepSession Should session be kept on generate()? - * @return AbstractWord - */ - public function setKeepSession($keepSession) - { - $this->keepSession = $keepSession; - return $this; - } - - /** - * Numbers should be included in the pattern? - * - * @return bool - */ - public function getUseNumbers() - { - return $this->useNumbers; - } - - /** - * Set if numbers should be included in the pattern - * - * @param bool $useNumbers numbers should be included in the pattern? - * @return AbstractWord - */ - public function setUseNumbers($useNumbers) - { - $this->useNumbers = $useNumbers; - return $this; - } - - /** - * Get session object - * - * @throws Exception\InvalidArgumentException - * @return Container - */ - public function getSession() - { - if (!isset($this->session) || (null === $this->session)) { - $id = $this->getId(); - if (!class_exists($this->sessionClass)) { - throw new Exception\InvalidArgumentException("Session class $this->sessionClass not found"); - } - $this->session = new $this->sessionClass('Zend_Form_Captcha_' . $id); - $this->session->setExpirationHops(1, null); - $this->session->setExpirationSeconds($this->getTimeout()); - } - return $this->session; - } - - /** - * Set session namespace object - * - * @param Container $session - * @return AbstractWord - */ - public function setSession(Container $session) - { - $this->session = $session; - if ($session) { - $this->keepSession = true; - } - return $this; - } - - /** - * Get captcha word - * - * @return string - */ - public function getWord() - { - if (empty($this->word)) { - $session = $this->getSession(); - $this->word = $session->word; - } - return $this->word; - } - - /** - * Set captcha word - * - * @param string $word - * @return AbstractWord - */ - protected function setWord($word) - { - $session = $this->getSession(); - $session->word = $word; - $this->word = $word; - return $this; - } - - /** - * Generate new random word - * - * @return string - */ - protected function generateWord() - { - $word = ''; - $wordLen = $this->getWordLen(); - $vowels = $this->useNumbers ? static::$VN : static::$V; - $consonants = $this->useNumbers ? static::$CN : static::$C; - - for ($i=0; $i < $wordLen; $i = $i + 2) { - // generate word with mix of vowels and consonants - $consonant = $consonants[array_rand($consonants)]; - $vowel = $vowels[array_rand($vowels)]; - $word .= $consonant . $vowel; - } - - if (strlen($word) > $wordLen) { - $word = substr($word, 0, $wordLen); - } - - return $word; - } - - /** - * Generate new session ID and new word - * - * @return string session ID - */ - public function generate() - { - if (!$this->keepSession) { - $this->session = null; - } - $id = $this->generateRandomId(); - $this->setId($id); - $word = $this->generateWord(); - $this->setWord($word); - return $id; - } - - /** - * Generate a random identifier - * - * @return string - */ - protected function generateRandomId() - { - return md5(Rand::getBytes(32)); - } - - /** - * Validate the word - * - * @see Zend\Validator\ValidatorInterface::isValid() - * @param mixed $value - * @param mixed $context - * @return bool - */ - public function isValid($value, $context = null) - { - if (!is_array($value)) { - if (!is_array($context)) { - $this->error(self::MISSING_VALUE); - return false; - } - $value = $context; - } - - $name = $this->getName(); - - if (isset($value[$name])) { - $value = $value[$name]; - } - - if (!isset($value['input'])) { - $this->error(self::MISSING_VALUE); - return false; - } - $input = strtolower($value['input']); - $this->setValue($input); - - if (!isset($value['id'])) { - $this->error(self::MISSING_ID); - return false; - } - - $this->id = $value['id']; - if ($input !== $this->getWord()) { - $this->error(self::BAD_CAPTCHA); - return false; - } - - return true; - } - - /** - * Get helper name used to render captcha - * - * @return string - */ - public function getHelperName() - { - return 'captcha/word'; - } -} diff --git a/library/Zend/Captcha/AdapterInterface.php b/library/Zend/Captcha/AdapterInterface.php deleted file mode 100755 index 227daa5c7..000000000 --- a/library/Zend/Captcha/AdapterInterface.php +++ /dev/null @@ -1,49 +0,0 @@ -label = $label; - } - - /** - * Retrieve the label for the CAPTCHA - * @return string - */ - public function getLabel() - { - return $this->label; - } - - /** - * Retrieve optional view helper name to use when rendering this captcha - * - * @return string - */ - public function getHelperName() - { - return 'captcha/dumb'; - } -} diff --git a/library/Zend/Captcha/Exception/DomainException.php b/library/Zend/Captcha/Exception/DomainException.php deleted file mode 100755 index ac900097b..000000000 --- a/library/Zend/Captcha/Exception/DomainException.php +++ /dev/null @@ -1,14 +0,0 @@ - 'Zend\Captcha\Dumb', - 'figlet' => 'Zend\Captcha\Figlet', - 'image' => 'Zend\Captcha\Image', - 'recaptcha' => 'Zend\Captcha\ReCaptcha', - ); - - /** - * Create a captcha adapter instance - * - * @param array|Traversable $options - * @return AdapterInterface - * @throws Exception\InvalidArgumentException for a non-array, non-Traversable $options - * @throws Exception\DomainException if class is missing or invalid - */ - public static function factory($options) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (!is_array($options)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable argument; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - if (!isset($options['class'])) { - throw new Exception\DomainException(sprintf( - '%s expects a "class" attribute in the options; none provided', - __METHOD__ - )); - } - - $class = $options['class']; - if (isset(static::$classMap[strtolower($class)])) { - $class = static::$classMap[strtolower($class)]; - } - if (!class_exists($class)) { - throw new Exception\DomainException(sprintf( - '%s expects the "class" attribute to resolve to an existing class; received "%s"', - __METHOD__, - $class - )); - } - - unset($options['class']); - - if (isset($options['options'])) { - $options = $options['options']; - } - $captcha = new $class($options); - - if (!$captcha instanceof AdapterInterface) { - throw new Exception\DomainException(sprintf( - '%s expects the "class" attribute to resolve to a valid Zend\Captcha\AdapterInterface instance; received "%s"', - __METHOD__, - $class - )); - } - - return $captcha; - } -} diff --git a/library/Zend/Captcha/Figlet.php b/library/Zend/Captcha/Figlet.php deleted file mode 100755 index 002f5f307..000000000 --- a/library/Zend/Captcha/Figlet.php +++ /dev/null @@ -1,69 +0,0 @@ -figlet = new FigletManager($options); - } - - /** - * Retrieve the composed figlet manager - * - * @return FigletManager - */ - public function getFiglet() - { - return $this->figlet; - } - - /** - * Generate new captcha - * - * @return string - */ - public function generate() - { - $this->useNumbers = false; - return parent::generate(); - } - - /** - * Get helper name used to render captcha - * - * @return string - */ - public function getHelperName() - { - return 'captcha/figlet'; - } -} diff --git a/library/Zend/Captcha/Image.php b/library/Zend/Captcha/Image.php deleted file mode 100755 index 7f91b9128..000000000 --- a/library/Zend/Captcha/Image.php +++ /dev/null @@ -1,628 +0,0 @@ -imgAlt; - } - - /** - * @return string - */ - public function getStartImage() - { - return $this->startImage; - } - - /** - * @return int - */ - public function getDotNoiseLevel() - { - return $this->dotNoiseLevel; - } - - /** - * @return int - */ - public function getLineNoiseLevel() - { - return $this->lineNoiseLevel; - } - - /** - * Get captcha expiration - * - * @return int - */ - public function getExpiration() - { - return $this->expiration; - } - - /** - * Get garbage collection frequency - * - * @return int - */ - public function getGcFreq() - { - return $this->gcFreq; - } - - /** - * Get font to use when generating captcha - * - * @return string - */ - public function getFont() - { - return $this->font; - } - - /** - * Get font size - * - * @return int - */ - public function getFontSize() - { - return $this->fsize; - } - - /** - * Get captcha image height - * - * @return int - */ - public function getHeight() - { - return $this->height; - } - - /** - * Get captcha image directory - * - * @return string - */ - public function getImgDir() - { - return $this->imgDir; - } - - /** - * Get captcha image base URL - * - * @return string - */ - public function getImgUrl() - { - return $this->imgUrl; - } - - /** - * Get captcha image file suffix - * - * @return string - */ - public function getSuffix() - { - return $this->suffix; - } - - /** - * Get captcha image width - * - * @return int - */ - public function getWidth() - { - return $this->width; - } - - /** - * @param string $startImage - * @return Image - */ - public function setStartImage($startImage) - { - $this->startImage = $startImage; - return $this; - } - - /** - * @param int $dotNoiseLevel - * @return Image - */ - public function setDotNoiseLevel($dotNoiseLevel) - { - $this->dotNoiseLevel = $dotNoiseLevel; - return $this; - } - - /** - * @param int $lineNoiseLevel - * @return Image - */ - public function setLineNoiseLevel($lineNoiseLevel) - { - $this->lineNoiseLevel = $lineNoiseLevel; - return $this; - } - - /** - * Set captcha expiration - * - * @param int $expiration - * @return Image - */ - public function setExpiration($expiration) - { - $this->expiration = $expiration; - return $this; - } - - /** - * Set garbage collection frequency - * - * @param int $gcFreq - * @return Image - */ - public function setGcFreq($gcFreq) - { - $this->gcFreq = $gcFreq; - return $this; - } - - /** - * Set captcha font - * - * @param string $font - * @return Image - */ - public function setFont($font) - { - $this->font = $font; - return $this; - } - - /** - * Set captcha font size - * - * @param int $fsize - * @return Image - */ - public function setFontSize($fsize) - { - $this->fsize = $fsize; - return $this; - } - - /** - * Set captcha image height - * - * @param int $height - * @return Image - */ - public function setHeight($height) - { - $this->height = $height; - return $this; - } - - /** - * Set captcha image storage directory - * - * @param string $imgDir - * @return Image - */ - public function setImgDir($imgDir) - { - $this->imgDir = rtrim($imgDir, "/\\") . '/'; - return $this; - } - - /** - * Set captcha image base URL - * - * @param string $imgUrl - * @return Image - */ - public function setImgUrl($imgUrl) - { - $this->imgUrl = rtrim($imgUrl, "/\\") . '/'; - return $this; - } - - /** - * @param string $imgAlt - * @return Image - */ - public function setImgAlt($imgAlt) - { - $this->imgAlt = $imgAlt; - return $this; - } - - /** - * Set captcha image filename suffix - * - * @param string $suffix - * @return Image - */ - public function setSuffix($suffix) - { - $this->suffix = $suffix; - return $this; - } - - /** - * Set captcha image width - * - * @param int $width - * @return Image - */ - public function setWidth($width) - { - $this->width = $width; - return $this; - } - - /** - * Generate random frequency - * - * @return float - */ - protected function randomFreq() - { - return mt_rand(700000, 1000000) / 15000000; - } - - /** - * Generate random phase - * - * @return float - */ - protected function randomPhase() - { - // random phase from 0 to pi - return mt_rand(0, 3141592) / 1000000; - } - - /** - * Generate random character size - * - * @return int - */ - protected function randomSize() - { - return mt_rand(300, 700) / 100; - } - - /** - * Generate captcha - * - * @return string captcha ID - */ - public function generate() - { - $id = parent::generate(); - $tries = 5; - - // If there's already such file, try creating a new ID - while ($tries-- && file_exists($this->getImgDir() . $id . $this->getSuffix())) { - $id = $this->generateRandomId(); - $this->setId($id); - } - $this->generateImage($id, $this->getWord()); - - if (mt_rand(1, $this->getGcFreq()) == 1) { - $this->gc(); - } - - return $id; - } - - /** - * Generate image captcha - * - * Override this function if you want different image generator - * Wave transform from http://www.captcha.ru/captchas/multiwave/ - * - * @param string $id Captcha ID - * @param string $word Captcha word - * @throws Exception\NoFontProvidedException if no font was set - * @throws Exception\ImageNotLoadableException if start image cannot be loaded - */ - protected function generateImage($id, $word) - { - $font = $this->getFont(); - - if (empty($font)) { - throw new Exception\NoFontProvidedException('Image CAPTCHA requires font'); - } - - $w = $this->getWidth(); - $h = $this->getHeight(); - $fsize = $this->getFontSize(); - - $imgFile = $this->getImgDir() . $id . $this->getSuffix(); - - if (empty($this->startImage)) { - $img = imagecreatetruecolor($w, $h); - } else { - // Potential error is change to exception - ErrorHandler::start(); - $img = imagecreatefrompng($this->startImage); - $error = ErrorHandler::stop(); - if (!$img || $error) { - throw new Exception\ImageNotLoadableException( - "Can not load start image '{$this->startImage}'", - 0, - $error - ); - } - $w = imagesx($img); - $h = imagesy($img); - } - - $textColor = imagecolorallocate($img, 0, 0, 0); - $bgColor = imagecolorallocate($img, 255, 255, 255); - imagefilledrectangle($img, 0, 0, $w-1, $h-1, $bgColor); - $textbox = imageftbbox($fsize, 0, $font, $word); - $x = ($w - ($textbox[2] - $textbox[0])) / 2; - $y = ($h - ($textbox[7] - $textbox[1])) / 2; - imagefttext($img, $fsize, 0, $x, $y, $textColor, $font, $word); - - // generate noise - for ($i=0; $i < $this->dotNoiseLevel; $i++) { - imagefilledellipse($img, mt_rand(0, $w), mt_rand(0, $h), 2, 2, $textColor); - } - for ($i=0; $i < $this->lineNoiseLevel; $i++) { - imageline($img, mt_rand(0, $w), mt_rand(0, $h), mt_rand(0, $w), mt_rand(0, $h), $textColor); - } - - // transformed image - $img2 = imagecreatetruecolor($w, $h); - $bgColor = imagecolorallocate($img2, 255, 255, 255); - imagefilledrectangle($img2, 0, 0, $w-1, $h-1, $bgColor); - - // apply wave transforms - $freq1 = $this->randomFreq(); - $freq2 = $this->randomFreq(); - $freq3 = $this->randomFreq(); - $freq4 = $this->randomFreq(); - - $ph1 = $this->randomPhase(); - $ph2 = $this->randomPhase(); - $ph3 = $this->randomPhase(); - $ph4 = $this->randomPhase(); - - $szx = $this->randomSize(); - $szy = $this->randomSize(); - - for ($x = 0; $x < $w; $x++) { - for ($y = 0; $y < $h; $y++) { - $sx = $x + (sin($x*$freq1 + $ph1) + sin($y*$freq3 + $ph3)) * $szx; - $sy = $y + (sin($x*$freq2 + $ph2) + sin($y*$freq4 + $ph4)) * $szy; - - if ($sx < 0 || $sy < 0 || $sx >= $w - 1 || $sy >= $h - 1) { - continue; - } else { - $color = (imagecolorat($img, $sx, $sy) >> 16) & 0xFF; - $colorX = (imagecolorat($img, $sx + 1, $sy) >> 16) & 0xFF; - $colorY = (imagecolorat($img, $sx, $sy + 1) >> 16) & 0xFF; - $colorXY = (imagecolorat($img, $sx + 1, $sy + 1) >> 16) & 0xFF; - } - - if ($color == 255 && $colorX == 255 && $colorY == 255 && $colorXY == 255) { - // ignore background - continue; - } elseif ($color == 0 && $colorX == 0 && $colorY == 0 && $colorXY == 0) { - // transfer inside of the image as-is - $newcolor = 0; - } else { - // do antialiasing for border items - $fracX = $sx - floor($sx); - $fracY = $sy - floor($sy); - $fracX1 = 1 - $fracX; - $fracY1 = 1 - $fracY; - - $newcolor = $color * $fracX1 * $fracY1 - + $colorX * $fracX * $fracY1 - + $colorY * $fracX1 * $fracY - + $colorXY * $fracX * $fracY; - } - - imagesetpixel($img2, $x, $y, imagecolorallocate($img2, $newcolor, $newcolor, $newcolor)); - } - } - - // generate noise - for ($i=0; $i<$this->dotNoiseLevel; $i++) { - imagefilledellipse($img2, mt_rand(0, $w), mt_rand(0, $h), 2, 2, $textColor); - } - - for ($i=0; $i<$this->lineNoiseLevel; $i++) { - imageline($img2, mt_rand(0, $w), mt_rand(0, $h), mt_rand(0, $w), mt_rand(0, $h), $textColor); - } - - imagepng($img2, $imgFile); - imagedestroy($img); - imagedestroy($img2); - } - - /** - * Remove old files from image directory - * - */ - protected function gc() - { - $expire = time() - $this->getExpiration(); - $imgdir = $this->getImgDir(); - if (!$imgdir || strlen($imgdir) < 2) { - // safety guard - return; - } - - $suffixLength = strlen($this->suffix); - foreach (new DirectoryIterator($imgdir) as $file) { - if (!$file->isDot() && !$file->isDir()) { - if (file_exists($file->getPathname()) && $file->getMTime() < $expire) { - // only deletes files ending with $this->suffix - if (substr($file->getFilename(), -($suffixLength)) == $this->suffix) { - unlink($file->getPathname()); - } - } - } - } - } - - /** - * Get helper name used to render captcha - * - * @return string - */ - public function getHelperName() - { - return 'captcha/image'; - } -} diff --git a/library/Zend/Captcha/README.md b/library/Zend/Captcha/README.md deleted file mode 100755 index 1240158c5..000000000 --- a/library/Zend/Captcha/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Captcha Component from ZF2 -========================== - -This is the Captcha component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Captcha/ReCaptcha.php b/library/Zend/Captcha/ReCaptcha.php deleted file mode 100755 index 7e5c01934..000000000 --- a/library/Zend/Captcha/ReCaptcha.php +++ /dev/null @@ -1,247 +0,0 @@ - 'Missing captcha fields', - self::ERR_CAPTCHA => 'Failed to validate captcha', - self::BAD_CAPTCHA => 'Captcha value is wrong: %value%', - ); - - /** - * Retrieve ReCaptcha Private key - * - * @return string - */ - public function getPrivkey() - { - return $this->getService()->getPrivateKey(); - } - - /** - * Retrieve ReCaptcha Public key - * - * @return string - */ - public function getPubkey() - { - return $this->getService()->getPublicKey(); - } - - /** - * Set ReCaptcha Private key - * - * @param string $privkey - * @return ReCaptcha - */ - public function setPrivkey($privkey) - { - $this->getService()->setPrivateKey($privkey); - return $this; - } - - /** - * Set ReCaptcha public key - * - * @param string $pubkey - * @return ReCaptcha - */ - public function setPubkey($pubkey) - { - $this->getService()->setPublicKey($pubkey); - return $this; - } - - /** - * Constructor - * - * @param null|array|Traversable $options - */ - public function __construct($options = null) - { - $this->setService(new ReCaptchaService()); - $this->serviceParams = $this->getService()->getParams(); - $this->serviceOptions = $this->getService()->getOptions(); - - parent::__construct($options); - - if (!empty($options)) { - if (array_key_exists('private_key', $options)) { - $this->getService()->setPrivateKey($options['private_key']); - } - if (array_key_exists('public_key', $options)) { - $this->getService()->setPublicKey($options['public_key']); - } - $this->setOptions($options); - } - } - - /** - * Set service object - * - * @param ReCaptchaService $service - * @return ReCaptcha - */ - public function setService(ReCaptchaService $service) - { - $this->service = $service; - return $this; - } - - /** - * Retrieve ReCaptcha service object - * - * @return ReCaptchaService - */ - public function getService() - { - return $this->service; - } - - /** - * Set option - * - * If option is a service parameter, proxies to the service. The same - * goes for any service options (distinct from service params) - * - * @param string $key - * @param mixed $value - * @return ReCaptcha - */ - public function setOption($key, $value) - { - $service = $this->getService(); - if (isset($this->serviceParams[$key])) { - $service->setParam($key, $value); - return $this; - } - if (isset($this->serviceOptions[$key])) { - $service->setOption($key, $value); - return $this; - } - return parent::setOption($key, $value); - } - - /** - * Generate captcha - * - * @see AbstractAdapter::generate() - * @return string - */ - public function generate() - { - return ""; - } - - /** - * Validate captcha - * - * @see \Zend\Validator\ValidatorInterface::isValid() - * @param mixed $value - * @param mixed $context - * @return bool - */ - public function isValid($value, $context = null) - { - if (!is_array($value) && !is_array($context)) { - $this->error(self::MISSING_VALUE); - return false; - } - - if (!is_array($value) && is_array($context)) { - $value = $context; - } - - if (empty($value[$this->CHALLENGE]) || empty($value[$this->RESPONSE])) { - $this->error(self::MISSING_VALUE); - return false; - } - - $service = $this->getService(); - - $res = $service->verify($value[$this->CHALLENGE], $value[$this->RESPONSE]); - - if (!$res) { - $this->error(self::ERR_CAPTCHA); - return false; - } - - if (!$res->isValid()) { - $this->error(self::BAD_CAPTCHA, $res->getErrorCode()); - $service->setParam('error', $res->getErrorCode()); - return false; - } - - return true; - } - - /** - * Get helper name used to render captcha - * - * @return string - */ - public function getHelperName() - { - return "captcha/recaptcha"; - } -} diff --git a/library/Zend/Captcha/composer.json b/library/Zend/Captcha/composer.json deleted file mode 100755 index fec1684fe..000000000 --- a/library/Zend/Captcha/composer.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "zendframework/zend-captcha", - "description": " ", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "captcha" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Captcha\\": "" - } - }, - "target-dir": "Zend/Captcha", - "require": { - "php": ">=5.3.23", - "zendframework/zend-math": "self.version", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-session": "self.version", - "zendframework/zend-text": "self.version", - "zendframework/zend-validator": "self.version", - "zendframework/zendservice-recaptcha": "*" - }, - "suggest": { - "zendframework/zend-resources": "Translations of captcha messages", - "zendframework/zend-session": "Zend\\Session component", - "zendframework/zend-text": "Zend\\Text component", - "zendframework/zend-validator": "Zend\\Validator component", - "zendframework/zendservice-recaptcha": "ZendService\\ReCaptcha component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Code/Annotation/AnnotationCollection.php b/library/Zend/Code/Annotation/AnnotationCollection.php deleted file mode 100755 index 7b9aa51da..000000000 --- a/library/Zend/Code/Annotation/AnnotationCollection.php +++ /dev/null @@ -1,32 +0,0 @@ -setIdentifiers(array( - __CLASS__, - get_class($this), - )); - $this->events = $events; - - return $this; - } - - /** - * Retrieve event manager - * - * Lazy loads an instance if none registered. - * - * @return EventManagerInterface - */ - public function getEventManager() - { - if (null === $this->events) { - $this->setEventManager(new EventManager()); - } - - return $this->events; - } - - /** - * Attach a parser to listen to the createAnnotation event - * - * @param ParserInterface $parser - * @return AnnotationManager - */ - public function attach(ParserInterface $parser) - { - $this->getEventManager() - ->attach(self::EVENT_CREATE_ANNOTATION, array($parser, 'onCreateAnnotation')); - - return $this; - } - - /** - * Create Annotation - * - * @param string[] $annotationData - * @return false|\stdClass - */ - public function createAnnotation(array $annotationData) - { - $event = new Event(); - $event->setName(self::EVENT_CREATE_ANNOTATION); - $event->setTarget($this); - $event->setParams(array( - 'class' => $annotationData[0], - 'content' => $annotationData[1], - 'raw' => $annotationData[2], - )); - - $eventManager = $this->getEventManager(); - $results = $eventManager->trigger($event, function ($r) { - return (is_object($r)); - }); - - $annotation = $results->last(); - - return (is_object($annotation) ? $annotation : false); - } -} diff --git a/library/Zend/Code/Annotation/Parser/DoctrineAnnotationParser.php b/library/Zend/Code/Annotation/Parser/DoctrineAnnotationParser.php deleted file mode 100755 index 5168e3278..000000000 --- a/library/Zend/Code/Annotation/Parser/DoctrineAnnotationParser.php +++ /dev/null @@ -1,153 +0,0 @@ -docParser = $docParser; - return $this; - } - - /** - * Retrieve the DocParser instance - * - * If none is registered, lazy-loads a new instance. - * - * @return DocParser - */ - public function getDocParser() - { - if (!$this->docParser instanceof DocParser) { - $this->setDocParser(new DocParser()); - } - - return $this->docParser; - } - - /** - * Handle annotation creation - * - * @param EventInterface $e - * @return false|\stdClass - */ - public function onCreateAnnotation(EventInterface $e) - { - $annotationClass = $e->getParam('class', false); - if (!$annotationClass) { - return false; - } - - if (!isset($this->allowedAnnotations[$annotationClass])) { - return false; - } - - $annotationString = $e->getParam('raw', false); - if (!$annotationString) { - return false; - } - - // Annotation classes provided by the AnnotationScanner are already - // resolved to fully-qualified class names. Adding the global namespace - // prefix allows the Doctrine annotation parser to locate the annotation - // class correctly. - $annotationString = preg_replace('/^(@)/', '$1\\', $annotationString); - - $parser = $this->getDocParser(); - $annotations = $parser->parse($annotationString); - if (empty($annotations)) { - return false; - } - - $annotation = array_shift($annotations); - if (!is_object($annotation)) { - return false; - } - - return $annotation; - } - - /** - * Specify an allowed annotation class - * - * @param string $annotation - * @return DoctrineAnnotationParser - */ - public function registerAnnotation($annotation) - { - $this->allowedAnnotations[$annotation] = true; - return $this; - } - - /** - * Set many allowed annotations at once - * - * @param array|Traversable $annotations Array or traversable object of - * annotation class names - * @throws Exception\InvalidArgumentException - * @return DoctrineAnnotationParser - */ - public function registerAnnotations($annotations) - { - if (!is_array($annotations) && !$annotations instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an array or Traversable; received "%s"', - __METHOD__, - (is_object($annotations) ? get_class($annotations) : gettype($annotations)) - )); - } - - foreach ($annotations as $annotation) { - $this->allowedAnnotations[$annotation] = true; - } - - return $this; - } -} diff --git a/library/Zend/Code/Annotation/Parser/GenericAnnotationParser.php b/library/Zend/Code/Annotation/Parser/GenericAnnotationParser.php deleted file mode 100755 index b3f756624..000000000 --- a/library/Zend/Code/Annotation/Parser/GenericAnnotationParser.php +++ /dev/null @@ -1,224 +0,0 @@ -getParam('class', false); - if (!$class || !$this->hasAnnotation($class)) { - return false; - } - - $content = $e->getParam('content', ''); - $content = trim($content, '()'); - - if ($this->hasAlias($class)) { - $class = $this->resolveAlias($class); - } - - $index = array_search($class, $this->annotationNames); - $annotation = $this->annotations[$index]; - - $newAnnotation = clone $annotation; - if ($content) { - $newAnnotation->initialize($content); - } - - return $newAnnotation; - } - - /** - * Register annotations - * - * @param string|AnnotationInterface $annotation String class name of an - * AnnotationInterface implementation, or actual instance - * @return GenericAnnotationParser - * @throws Exception\InvalidArgumentException - */ - public function registerAnnotation($annotation) - { - $class = false; - if (is_string($annotation) && class_exists($annotation)) { - $class = $annotation; - $annotation = new $annotation(); - } - - if (!$annotation instanceof AnnotationInterface) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an instance of %s\AnnotationInterface; received "%s"', - __METHOD__, - __NAMESPACE__, - (is_object($annotation) ? get_class($annotation) : gettype($annotation)) - )); - } - - $class = $class ?: get_class($annotation); - - if (in_array($class, $this->annotationNames)) { - throw new Exception\InvalidArgumentException(sprintf( - 'An annotation for this class %s already exists', - $class - )); - } - - $this->annotations[] = $annotation; - $this->annotationNames[] = $class; - } - - /** - * Register many annotations at once - * - * @param array|Traversable $annotations - * @throws Exception\InvalidArgumentException - * @return GenericAnnotationParser - */ - public function registerAnnotations($annotations) - { - if (!is_array($annotations) && !$annotations instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an array or Traversable; received "%s"', - __METHOD__, - (is_object($annotations) ? get_class($annotations) : gettype($annotations)) - )); - } - - foreach ($annotations as $annotation) { - $this->registerAnnotation($annotation); - } - - return $this; - } - - /** - * Checks if the manager has annotations for a class - * - * @param string $class - * @return bool - */ - public function hasAnnotation($class) - { - if (in_array($class, $this->annotationNames)) { - return true; - } - - if ($this->hasAlias($class)) { - return true; - } - - return false; - } - - /** - * Alias an annotation name - * - * @param string $alias - * @param string $class May be either a registered annotation name or another alias - * @throws Exception\InvalidArgumentException - * @return GenericAnnotationParser - */ - public function setAlias($alias, $class) - { - if (!in_array($class, $this->annotationNames) && !$this->hasAlias($class)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: Cannot alias "%s" to "%s", as class "%s" is not currently a registered annotation or alias', - __METHOD__, - $alias, - $class, - $class - )); - } - - $alias = $this->normalizeAlias($alias); - $this->aliases[$alias] = $class; - - return $this; - } - - /** - * Normalize an alias name - * - * @param string $alias - * @return string - */ - protected function normalizeAlias($alias) - { - return strtolower(str_replace(array('-', '_', ' ', '\\', '/'), '', $alias)); - } - - /** - * Do we have an alias by the provided name? - * - * @param string $alias - * @return bool - */ - protected function hasAlias($alias) - { - $alias = $this->normalizeAlias($alias); - - return (isset($this->aliases[$alias])); - } - - /** - * Resolve an alias to a class name - * - * @param string $alias - * @return string - */ - protected function resolveAlias($alias) - { - do { - $normalized = $this->normalizeAlias($alias); - $class = $this->aliases[$normalized]; - } while ($this->hasAlias($class)); - - return $class; - } -} diff --git a/library/Zend/Code/Annotation/Parser/ParserInterface.php b/library/Zend/Code/Annotation/Parser/ParserInterface.php deleted file mode 100755 index bb6746e80..000000000 --- a/library/Zend/Code/Annotation/Parser/ParserInterface.php +++ /dev/null @@ -1,39 +0,0 @@ -setOptions($options); - } - } - - /** - * @param bool $isSourceDirty - * @return AbstractGenerator - */ - public function setSourceDirty($isSourceDirty = true) - { - $this->isSourceDirty = (bool) $isSourceDirty; - return $this; - } - - /** - * @return bool - */ - public function isSourceDirty() - { - return $this->isSourceDirty; - } - - /** - * @param string $indentation - * @return AbstractGenerator - */ - public function setIndentation($indentation) - { - $this->indentation = (string) $indentation; - return $this; - } - - /** - * @return string - */ - public function getIndentation() - { - return $this->indentation; - } - - /** - * @param string $sourceContent - * @return AbstractGenerator - */ - public function setSourceContent($sourceContent) - { - $this->sourceContent = (string) $sourceContent; - return $this; - } - - /** - * @return string - */ - public function getSourceContent() - { - return $this->sourceContent; - } - - /** - * @param array|Traversable $options - * @throws Exception\InvalidArgumentException - * @return AbstractGenerator - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable object; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $optionName => $optionValue) { - $methodName = 'set' . $optionName; - if (method_exists($this, $methodName)) { - $this->{$methodName}($optionValue); - } - } - - return $this; - } -} diff --git a/library/Zend/Code/Generator/AbstractMemberGenerator.php b/library/Zend/Code/Generator/AbstractMemberGenerator.php deleted file mode 100755 index dec0d8dc0..000000000 --- a/library/Zend/Code/Generator/AbstractMemberGenerator.php +++ /dev/null @@ -1,224 +0,0 @@ -flags = $flags; - - return $this; - } - - /** - * @param int $flag - * @return AbstractMemberGenerator - */ - public function addFlag($flag) - { - $this->setFlags($this->flags | $flag); - return $this; - } - - /** - * @param int $flag - * @return AbstractMemberGenerator - */ - public function removeFlag($flag) - { - $this->setFlags($this->flags & ~$flag); - return $this; - } - - /** - * @param bool $isAbstract - * @return AbstractMemberGenerator - */ - public function setAbstract($isAbstract) - { - return (($isAbstract) ? $this->addFlag(self::FLAG_ABSTRACT) : $this->removeFlag(self::FLAG_ABSTRACT)); - } - - /** - * @return bool - */ - public function isAbstract() - { - return (bool) ($this->flags & self::FLAG_ABSTRACT); - } - - /** - * @param bool $isFinal - * @return AbstractMemberGenerator - */ - public function setFinal($isFinal) - { - return (($isFinal) ? $this->addFlag(self::FLAG_FINAL) : $this->removeFlag(self::FLAG_FINAL)); - } - - /** - * @return bool - */ - public function isFinal() - { - return (bool) ($this->flags & self::FLAG_FINAL); - } - - /** - * @param bool $isStatic - * @return AbstractMemberGenerator - */ - public function setStatic($isStatic) - { - return (($isStatic) ? $this->addFlag(self::FLAG_STATIC) : $this->removeFlag(self::FLAG_STATIC)); - } - - /** - * @return bool - */ - public function isStatic() - { - return (bool) ($this->flags & self::FLAG_STATIC); // is FLAG_STATIC in flags - } - - /** - * @param string $visibility - * @return AbstractMemberGenerator - */ - public function setVisibility($visibility) - { - switch ($visibility) { - case self::VISIBILITY_PUBLIC: - $this->removeFlag(self::FLAG_PRIVATE | self::FLAG_PROTECTED); // remove both - $this->addFlag(self::FLAG_PUBLIC); - break; - case self::VISIBILITY_PROTECTED: - $this->removeFlag(self::FLAG_PUBLIC | self::FLAG_PRIVATE); // remove both - $this->addFlag(self::FLAG_PROTECTED); - break; - case self::VISIBILITY_PRIVATE: - $this->removeFlag(self::FLAG_PUBLIC | self::FLAG_PROTECTED); // remove both - $this->addFlag(self::FLAG_PRIVATE); - break; - } - - return $this; - } - - /** - * @return string - */ - public function getVisibility() - { - switch (true) { - case ($this->flags & self::FLAG_PROTECTED): - return self::VISIBILITY_PROTECTED; - case ($this->flags & self::FLAG_PRIVATE): - return self::VISIBILITY_PRIVATE; - default: - return self::VISIBILITY_PUBLIC; - } - } - - /** - * @param string $name - * @return AbstractMemberGenerator - */ - public function setName($name) - { - $this->name = (string) $name; - return $this; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param DocBlockGenerator|string $docBlock - * @throws Exception\InvalidArgumentException - * @return AbstractMemberGenerator - */ - public function setDocBlock($docBlock) - { - if (is_string($docBlock)) { - $docBlock = new DocBlockGenerator($docBlock); - } elseif (!$docBlock instanceof DocBlockGenerator) { - throw new Exception\InvalidArgumentException(sprintf( - '%s is expecting either a string, array or an instance of %s\DocBlockGenerator', - __METHOD__, - __NAMESPACE__ - )); - } - - $this->docBlock = $docBlock; - - return $this; - } - - /** - * @return DocBlockGenerator - */ - public function getDocBlock() - { - return $this->docBlock; - } -} diff --git a/library/Zend/Code/Generator/BodyGenerator.php b/library/Zend/Code/Generator/BodyGenerator.php deleted file mode 100755 index 4851e5ca4..000000000 --- a/library/Zend/Code/Generator/BodyGenerator.php +++ /dev/null @@ -1,44 +0,0 @@ -content = (string) $content; - return $this; - } - - /** - * @return string - */ - public function getContent() - { - return $this->content; - } - - /** - * @return string - */ - public function generate() - { - return $this->getContent(); - } -} diff --git a/library/Zend/Code/Generator/ClassGenerator.php b/library/Zend/Code/Generator/ClassGenerator.php deleted file mode 100755 index e84558746..000000000 --- a/library/Zend/Code/Generator/ClassGenerator.php +++ /dev/null @@ -1,747 +0,0 @@ -getName()); - - $cg->setSourceContent($cg->getSourceContent()); - $cg->setSourceDirty(false); - - if ($classReflection->getDocComment() != '') { - $cg->setDocBlock(DocBlockGenerator::fromReflection($classReflection->getDocBlock())); - } - - $cg->setAbstract($classReflection->isAbstract()); - - // set the namespace - if ($classReflection->inNamespace()) { - $cg->setNamespaceName($classReflection->getNamespaceName()); - } - - /* @var \Zend\Code\Reflection\ClassReflection $parentClass */ - $parentClass = $classReflection->getParentClass(); - if ($parentClass) { - $cg->setExtendedClass($parentClass->getName()); - $interfaces = array_diff($classReflection->getInterfaces(), $parentClass->getInterfaces()); - } else { - $interfaces = $classReflection->getInterfaces(); - } - - $interfaceNames = array(); - foreach ($interfaces as $interface) { - /* @var \Zend\Code\Reflection\ClassReflection $interface */ - $interfaceNames[] = $interface->getName(); - } - - $cg->setImplementedInterfaces($interfaceNames); - - $properties = array(); - foreach ($classReflection->getProperties() as $reflectionProperty) { - if ($reflectionProperty->getDeclaringClass()->getName() == $classReflection->getName()) { - $properties[] = PropertyGenerator::fromReflection($reflectionProperty); - } - } - $cg->addProperties($properties); - - $methods = array(); - foreach ($classReflection->getMethods() as $reflectionMethod) { - $className = ($cg->getNamespaceName())? $cg->getNamespaceName() . "\\" . $cg->getName() : $cg->getName(); - if ($reflectionMethod->getDeclaringClass()->getName() == $className) { - $methods[] = MethodGenerator::fromReflection($reflectionMethod); - } - } - $cg->addMethods($methods); - - return $cg; - } - - /** - * Generate from array - * - * @configkey name string [required] Class Name - * @configkey filegenerator FileGenerator File generator that holds this class - * @configkey namespacename string The namespace for this class - * @configkey docblock string The docblock information - * @configkey flags int Flags, one of ClassGenerator::FLAG_ABSTRACT ClassGenerator::FLAG_FINAL - * @configkey extendedclass string Class which this class is extending - * @configkey implementedinterfaces - * @configkey properties - * @configkey methods - * - * @throws Exception\InvalidArgumentException - * @param array $array - * @return ClassGenerator - */ - public static function fromArray(array $array) - { - if (!isset($array['name'])) { - throw new Exception\InvalidArgumentException( - 'Class generator requires that a name is provided for this object' - ); - } - - $cg = new static($array['name']); - foreach ($array as $name => $value) { - // normalize key - switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { - case 'containingfile': - $cg->setContainingFileGenerator($value); - break; - case 'namespacename': - $cg->setNamespaceName($value); - break; - case 'docblock': - $docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value); - $cg->setDocBlock($docBlock); - break; - case 'flags': - $cg->setFlags($value); - break; - case 'extendedclass': - $cg->setExtendedClass($value); - break; - case 'implementedinterfaces': - $cg->setImplementedInterfaces($value); - break; - case 'properties': - $cg->addProperties($value); - break; - case 'methods': - $cg->addMethods($value); - break; - } - } - - return $cg; - } - - /** - * @param string $name - * @param string $namespaceName - * @param array|string $flags - * @param string $extends - * @param array $interfaces - * @param array $properties - * @param array $methods - * @param DocBlockGenerator $docBlock - */ - public function __construct( - $name = null, - $namespaceName = null, - $flags = null, - $extends = null, - $interfaces = array(), - $properties = array(), - $methods = array(), - $docBlock = null - ) { - if ($name !== null) { - $this->setName($name); - } - if ($namespaceName !== null) { - $this->setNamespaceName($namespaceName); - } - if ($flags !== null) { - $this->setFlags($flags); - } - if ($properties !== array()) { - $this->addProperties($properties); - } - if ($extends !== null) { - $this->setExtendedClass($extends); - } - if (is_array($interfaces)) { - $this->setImplementedInterfaces($interfaces); - } - if ($methods !== array()) { - $this->addMethods($methods); - } - if ($docBlock !== null) { - $this->setDocBlock($docBlock); - } - } - - /** - * @param string $name - * @return ClassGenerator - */ - public function setName($name) - { - if (strstr($name, '\\')) { - $namespace = substr($name, 0, strrpos($name, '\\')); - $name = substr($name, strrpos($name, '\\') + 1); - $this->setNamespaceName($namespace); - } - - $this->name = $name; - return $this; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $namespaceName - * @return ClassGenerator - */ - public function setNamespaceName($namespaceName) - { - $this->namespaceName = $namespaceName; - return $this; - } - - /** - * @return string - */ - public function getNamespaceName() - { - return $this->namespaceName; - } - - /** - * @param FileGenerator $fileGenerator - * @return ClassGenerator - */ - public function setContainingFileGenerator(FileGenerator $fileGenerator) - { - $this->containingFileGenerator = $fileGenerator; - return $this; - } - - /** - * @return FileGenerator - */ - public function getContainingFileGenerator() - { - return $this->containingFileGenerator; - } - - /** - * @param DocBlockGenerator $docBlock - * @return ClassGenerator - */ - public function setDocBlock(DocBlockGenerator $docBlock) - { - $this->docBlock = $docBlock; - return $this; - } - - /** - * @return DocBlockGenerator - */ - public function getDocBlock() - { - return $this->docBlock; - } - - /** - * @param array|string $flags - * @return ClassGenerator - */ - public function setFlags($flags) - { - if (is_array($flags)) { - $flagsArray = $flags; - $flags = 0x00; - foreach ($flagsArray as $flag) { - $flags |= $flag; - } - } - // check that visibility is one of three - $this->flags = $flags; - - return $this; - } - - /** - * @param string $flag - * @return ClassGenerator - */ - public function addFlag($flag) - { - $this->setFlags($this->flags | $flag); - return $this; - } - - /** - * @param string $flag - * @return ClassGenerator - */ - public function removeFlag($flag) - { - $this->setFlags($this->flags & ~$flag); - return $this; - } - - /** - * @param bool $isAbstract - * @return ClassGenerator - */ - public function setAbstract($isAbstract) - { - return (($isAbstract) ? $this->addFlag(self::FLAG_ABSTRACT) : $this->removeFlag(self::FLAG_ABSTRACT)); - } - - /** - * @return bool - */ - public function isAbstract() - { - return (bool) ($this->flags & self::FLAG_ABSTRACT); - } - - /** - * @param bool $isFinal - * @return ClassGenerator - */ - public function setFinal($isFinal) - { - return (($isFinal) ? $this->addFlag(self::FLAG_FINAL) : $this->removeFlag(self::FLAG_FINAL)); - } - - /** - * @return bool - */ - public function isFinal() - { - return ($this->flags & self::FLAG_FINAL); - } - - /** - * @param string $extendedClass - * @return ClassGenerator - */ - public function setExtendedClass($extendedClass) - { - $this->extendedClass = $extendedClass; - return $this; - } - - /** - * @return string - */ - public function getExtendedClass() - { - return $this->extendedClass; - } - - /** - * @param array $implementedInterfaces - * @return ClassGenerator - */ - public function setImplementedInterfaces(array $implementedInterfaces) - { - $this->implementedInterfaces = $implementedInterfaces; - return $this; - } - - /** - * @return array - */ - public function getImplementedInterfaces() - { - return $this->implementedInterfaces; - } - - /** - * @param array $properties - * @return ClassGenerator - */ - public function addProperties(array $properties) - { - foreach ($properties as $property) { - if ($property instanceof PropertyGenerator) { - $this->addPropertyFromGenerator($property); - } else { - if (is_string($property)) { - $this->addProperty($property); - } elseif (is_array($property)) { - call_user_func_array(array($this, 'addProperty'), $property); - } - } - } - - return $this; - } - - /** - * Add Property from scalars - * - * @param string $name - * @param string|array $defaultValue - * @param int $flags - * @throws Exception\InvalidArgumentException - * @return ClassGenerator - */ - public function addProperty($name, $defaultValue = null, $flags = PropertyGenerator::FLAG_PUBLIC) - { - if (!is_string($name)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects string for name', - __METHOD__ - )); - } - - return $this->addPropertyFromGenerator(new PropertyGenerator($name, $defaultValue, $flags)); - } - - /** - * Add property from PropertyGenerator - * - * @param PropertyGenerator $property - * @throws Exception\InvalidArgumentException - * @return ClassGenerator - */ - public function addPropertyFromGenerator(PropertyGenerator $property) - { - $propertyName = $property->getName(); - - if (isset($this->properties[$propertyName])) { - throw new Exception\InvalidArgumentException(sprintf( - 'A property by name %s already exists in this class.', - $propertyName - )); - } - - $this->properties[$propertyName] = $property; - return $this; - } - - /** - * Add a class to "use" classes - * - * @param string $use - * @param string|null $useAlias - * @return ClassGenerator - */ - public function addUse($use, $useAlias = null) - { - if (!empty($useAlias)) { - $use .= ' as ' . $useAlias; - } - - $this->uses[$use] = $use; - return $this; - } - - /** - * @return PropertyGenerator[] - */ - public function getProperties() - { - return $this->properties; - } - - /** - * @param string $propertyName - * @return PropertyGenerator|false - */ - public function getProperty($propertyName) - { - foreach ($this->getProperties() as $property) { - if ($property->getName() == $propertyName) { - return $property; - } - } - - return false; - } - - /** - * Returns the "use" classes - * - * @return array - */ - public function getUses() - { - return array_values($this->uses); - } - - /** - * @param string $propertyName - * @return bool - */ - public function hasProperty($propertyName) - { - return isset($this->properties[$propertyName]); - } - - /** - * @param array $methods - * @return ClassGenerator - */ - public function addMethods(array $methods) - { - foreach ($methods as $method) { - if ($method instanceof MethodGenerator) { - $this->addMethodFromGenerator($method); - } else { - if (is_string($method)) { - $this->addMethod($method); - } elseif (is_array($method)) { - call_user_func_array(array($this, 'addMethod'), $method); - } - } - } - - return $this; - } - - /** - * Add Method from scalars - * - * @param string $name - * @param array $parameters - * @param int $flags - * @param string $body - * @param string $docBlock - * @throws Exception\InvalidArgumentException - * @return ClassGenerator - */ - public function addMethod( - $name = null, - array $parameters = array(), - $flags = MethodGenerator::FLAG_PUBLIC, - $body = null, - $docBlock = null - ) { - if (!is_string($name)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects string for name', - __METHOD__ - )); - } - - return $this->addMethodFromGenerator(new MethodGenerator($name, $parameters, $flags, $body, $docBlock)); - } - - /** - * Add Method from MethodGenerator - * - * @param MethodGenerator $method - * @throws Exception\InvalidArgumentException - * @return ClassGenerator - */ - public function addMethodFromGenerator(MethodGenerator $method) - { - $methodName = $method->getName(); - - if ($this->hasMethod($methodName)) { - throw new Exception\InvalidArgumentException(sprintf( - 'A method by name %s already exists in this class.', - $methodName - )); - } - - $this->methods[strtolower($methodName)] = $method; - return $this; - } - - /** - * @return MethodGenerator[] - */ - public function getMethods() - { - return $this->methods; - } - - /** - * @param string $methodName - * @return MethodGenerator|false - */ - public function getMethod($methodName) - { - return $this->hasMethod($methodName) ? $this->methods[strtolower($methodName)] : false; - } - - /** - * @param string $methodName - * @return ClassGenerator - */ - public function removeMethod($methodName) - { - if ($this->hasMethod($methodName)) { - unset($this->methods[strtolower($methodName)]); - } - - return $this; - } - - /** - * @param string $methodName - * @return bool - */ - public function hasMethod($methodName) - { - return isset($this->methods[strtolower($methodName)]); - } - - /** - * @return bool - */ - public function isSourceDirty() - { - if (($docBlock = $this->getDocBlock()) && $docBlock->isSourceDirty()) { - return true; - } - - foreach ($this->getProperties() as $property) { - if ($property->isSourceDirty()) { - return true; - } - } - - foreach ($this->getMethods() as $method) { - if ($method->isSourceDirty()) { - return true; - } - } - - return parent::isSourceDirty(); - } - - /** - * @return string - */ - public function generate() - { - if (!$this->isSourceDirty()) { - $output = $this->getSourceContent(); - if (!empty($output)) { - return $output; - } - } - - $output = ''; - - if (null !== ($namespace = $this->getNamespaceName())) { - $output .= 'namespace ' . $namespace . ';' . self::LINE_FEED . self::LINE_FEED; - } - - $uses = $this->getUses(); - if (!empty($uses)) { - foreach ($uses as $use) { - $output .= 'use ' . $use . ';' . self::LINE_FEED; - } - $output .= self::LINE_FEED; - } - - if (null !== ($docBlock = $this->getDocBlock())) { - $docBlock->setIndentation(''); - $output .= $docBlock->generate(); - } - - if ($this->isAbstract()) { - $output .= 'abstract '; - } - - $output .= 'class ' . $this->getName(); - - if (!empty($this->extendedClass)) { - $output .= ' extends ' . $this->extendedClass; - } - - $implemented = $this->getImplementedInterfaces(); - if (!empty($implemented)) { - $output .= ' implements ' . implode(', ', $implemented); - } - - $output .= self::LINE_FEED . '{' . self::LINE_FEED . self::LINE_FEED; - - $properties = $this->getProperties(); - if (!empty($properties)) { - foreach ($properties as $property) { - $output .= $property->generate() . self::LINE_FEED . self::LINE_FEED; - } - } - - $methods = $this->getMethods(); - if (!empty($methods)) { - foreach ($methods as $method) { - $output .= $method->generate() . self::LINE_FEED; - } - } - - $output .= self::LINE_FEED . '}' . self::LINE_FEED; - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag.php b/library/Zend/Code/Generator/DocBlock/Tag.php deleted file mode 100755 index 58bd045e0..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag.php +++ /dev/null @@ -1,50 +0,0 @@ -initializeDefaultTags(); - return $tagManager->createTagFromReflection($reflectionTag); - } - - /** - * @param string $description - * @return Tag - * @deprecated Deprecated in 2.3. Use GenericTag::setContent() instead - */ - public function setDescription($description) - { - return $this->setContent($description); - } - - /** - * @return string - * @deprecated Deprecated in 2.3. Use GenericTag::getContent() instead - */ - public function getDescription() - { - return $this->getContent(); - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/AbstractTypeableTag.php b/library/Zend/Code/Generator/DocBlock/Tag/AbstractTypeableTag.php deleted file mode 100755 index 1ecf5dc07..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/AbstractTypeableTag.php +++ /dev/null @@ -1,96 +0,0 @@ -setTypes($types); - } - - if (!empty($description)) { - $this->setDescription($description); - } - } - - /** - * @param string $description - * @return ReturnTag - */ - public function setDescription($description) - { - $this->description = $description; - return $this; - } - - /** - * @return string - */ - public function getDescription() - { - return $this->description; - } - - /** - * Array of types or string with types delimited by pipe (|) - * e.g. array('int', 'null') or "int|null" - * - * @param array|string $types - * @return ReturnTag - */ - public function setTypes($types) - { - if (is_string($types)) { - $types = explode('|', $types); - } - $this->types = $types; - return $this; - } - - /** - * @return array - */ - public function getTypes() - { - return $this->types; - } - - /** - * @param string $delimiter - * @return string - */ - public function getTypesAsString($delimiter = '|') - { - return implode($delimiter, $this->types); - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/AuthorTag.php b/library/Zend/Code/Generator/DocBlock/Tag/AuthorTag.php deleted file mode 100755 index 333912dca..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/AuthorTag.php +++ /dev/null @@ -1,110 +0,0 @@ -setAuthorName($authorName); - } - - if (!empty($authorEmail)) { - $this->setAuthorEmail($authorEmail); - } - } - - /** - * @param ReflectionTagInterface $reflectionTag - * @return ReturnTag - * @deprecated Deprecated in 2.3. Use TagManager::createTagFromReflection() instead - */ - public static function fromReflection(ReflectionTagInterface $reflectionTag) - { - $tagManager = new TagManager(); - $tagManager->initializeDefaultTags(); - return $tagManager->createTagFromReflection($reflectionTag); - } - - /** - * @return string - */ - public function getName() - { - return 'author'; - } - - /** - * @param string $authorEmail - * @return AuthorTag - */ - public function setAuthorEmail($authorEmail) - { - $this->authorEmail = $authorEmail; - return $this; - } - - /** - * @return string - */ - public function getAuthorEmail() - { - return $this->authorEmail; - } - - /** - * @param string $authorName - * @return AuthorTag - */ - public function setAuthorName($authorName) - { - $this->authorName = $authorName; - return $this; - } - - /** - * @return string - */ - public function getAuthorName() - { - return $this->authorName; - } - - /** - * @return string - */ - public function generate() - { - $output = '@author' - . ((!empty($this->authorName)) ? ' ' . $this->authorName : '') - . ((!empty($this->authorEmail)) ? ' <' . $this->authorEmail . '>' : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/GenericTag.php b/library/Zend/Code/Generator/DocBlock/Tag/GenericTag.php deleted file mode 100755 index 4ff98d9f7..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/GenericTag.php +++ /dev/null @@ -1,88 +0,0 @@ -setName($name); - } - - if (!empty($content)) { - $this->setContent($content); - } - } - - /** - * @param string $name - * @return GenericTag - */ - public function setName($name) - { - $this->name = ltrim($name, '@'); - return $this; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $content - * @return GenericTag - */ - public function setContent($content) - { - $this->content = $content; - return $this; - } - - /** - * @return string - */ - public function getContent() - { - return $this->content; - } - - /** - * @return string - */ - public function generate() - { - $output = '@' . $this->name - . ((!empty($this->content)) ? ' ' . $this->content : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/LicenseTag.php b/library/Zend/Code/Generator/DocBlock/Tag/LicenseTag.php deleted file mode 100755 index 91a974152..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/LicenseTag.php +++ /dev/null @@ -1,110 +0,0 @@ -setUrl($url); - } - - if (!empty($licenseName)) { - $this->setLicenseName($licenseName); - } - } - - /** - * @param ReflectionTagInterface $reflectionTag - * @return ReturnTag - * @deprecated Deprecated in 2.3. Use TagManager::createTagFromReflection() instead - */ - public static function fromReflection(ReflectionTagInterface $reflectionTag) - { - $tagManager = new TagManager(); - $tagManager->initializeDefaultTags(); - return $tagManager->createTagFromReflection($reflectionTag); - } - - /** - * @return string - */ - public function getName() - { - return 'license'; - } - - /** - * @param string $url - * @return LicenseTag - */ - public function setUrl($url) - { - $this->url = $url; - return $this; - } - - /** - * @return string - */ - public function getUrl() - { - return $this->url; - } - - /** - * @param string $name - * @return LicenseTag - */ - public function setLicenseName($name) - { - $this->licenseName = $name; - return $this; - } - - /** - * @return string - */ - public function getLicenseName() - { - return $this->licenseName; - } - - /** - * @return string - */ - public function generate() - { - $output = '@license' - . ((!empty($this->url)) ? ' ' . $this->url : '') - . ((!empty($this->licenseName)) ? ' ' . $this->licenseName : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/MethodTag.php b/library/Zend/Code/Generator/DocBlock/Tag/MethodTag.php deleted file mode 100755 index e3c84c4ca..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/MethodTag.php +++ /dev/null @@ -1,98 +0,0 @@ -setMethodName($methodName); - } - - $this->setIsStatic((bool) $isStatic); - - parent::__construct($types, $description); - } - - /** - * @return string - */ - public function getName() - { - return 'method'; - } - - /** - * @param boolean $isStatic - * @return MethodTag - */ - public function setIsStatic($isStatic) - { - $this->isStatic = $isStatic; - return $this; - } - - /** - * @return boolean - */ - public function isStatic() - { - return $this->isStatic; - } - - /** - * @param string $methodName - * @return MethodTag - */ - public function setMethodName($methodName) - { - $this->methodName = rtrim($methodName, ')('); - return $this; - } - - /** - * @return string - */ - public function getMethodName() - { - return $this->methodName; - } - - /** - * @return string - */ - public function generate() - { - $output = '@method' - . (($this->isStatic) ? ' static' : '') - . ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '') - . ((!empty($this->methodName)) ? ' ' . $this->methodName . '()' : '') - . ((!empty($this->description)) ? ' ' . $this->description : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php b/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php deleted file mode 100755 index 75d8f86cb..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/ParamTag.php +++ /dev/null @@ -1,124 +0,0 @@ -setVariableName($variableName); - } - - parent::__construct($types, $description); - } - - /** - * @param ReflectionTagInterface $reflectionTag - * @return ReturnTag - * @deprecated Deprecated in 2.3. Use TagManager::createTagFromReflection() instead - */ - public static function fromReflection(ReflectionTagInterface $reflectionTag) - { - $tagManager = new TagManager(); - $tagManager->initializeDefaultTags(); - return $tagManager->createTagFromReflection($reflectionTag); - } - - /** - * @return string - */ - public function getName() - { - return 'param'; - } - - /** - * @param string $variableName - * @return ParamTag - */ - public function setVariableName($variableName) - { - $this->variableName = ltrim($variableName, '$'); - return $this; - } - - /** - * @return string - */ - public function getVariableName() - { - return $this->variableName; - } - - /** - * @param string $datatype - * @return ReturnTag - * @deprecated Deprecated in 2.3. Use setTypes() instead - */ - public function setDatatype($datatype) - { - return $this->setTypes($datatype); - } - - /** - * @return string - * @deprecated Deprecated in 2.3. Use getTypes() or getTypesAsString() instead - */ - public function getDatatype() - { - return $this->getTypesAsString(); - } - - /** - * @param string $paramName - * @return ParamTag - * @deprecated Deprecated in 2.3. Use setVariableName() instead - */ - public function setParamName($paramName) - { - return $this->setVariableName($paramName); - } - - /** - * @return string - * @deprecated Deprecated in 2.3. Use getVariableName() instead - */ - public function getParamName() - { - return $this->getVariableName(); - } - - /** - * @return string - */ - public function generate() - { - $output = '@param' - . ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '') - . ((!empty($this->variableName)) ? ' $' . $this->variableName : '') - . ((!empty($this->description)) ? ' ' . $this->description : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/PropertyTag.php b/library/Zend/Code/Generator/DocBlock/Tag/PropertyTag.php deleted file mode 100755 index 26699a897..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/PropertyTag.php +++ /dev/null @@ -1,71 +0,0 @@ -setPropertyName($propertyName); - } - - parent::__construct($types, $description); - } - - /** - * @return string - */ - public function getName() - { - return 'property'; - } - - /** - * @param string $propertyName - * @return self - */ - public function setPropertyName($propertyName) - { - $this->propertyName = ltrim($propertyName, '$'); - return $this; - } - - /** - * @return string - */ - public function getPropertyName() - { - return $this->propertyName; - } - - /** - * @return string - */ - public function generate() - { - $output = '@property' - . ((!empty($this->types)) ? ' ' . $this->getTypesAsString() : '') - . ((!empty($this->propertyName)) ? ' $' . $this->propertyName : '') - . ((!empty($this->description)) ? ' ' . $this->description : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/ReturnTag.php b/library/Zend/Code/Generator/DocBlock/Tag/ReturnTag.php deleted file mode 100755 index f3b356ebb..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/ReturnTag.php +++ /dev/null @@ -1,67 +0,0 @@ -initializeDefaultTags(); - return $tagManager->createTagFromReflection($reflectionTag); - } - - /** - * @return string - */ - public function getName() - { - return 'return'; - } - - /** - * @param string $datatype - * @return ReturnTag - * @deprecated Deprecated in 2.3. Use setTypes() instead - */ - public function setDatatype($datatype) - { - return $this->setTypes($datatype); - } - - /** - * @return string - * @deprecated Deprecated in 2.3. Use getTypes() or getTypesAsString() instead - */ - public function getDatatype() - { - return $this->getTypesAsString(); - } - - /** - * @return string - */ - public function generate() - { - $output = '@return ' - . $this->getTypesAsString() - . ((!empty($this->description)) ? ' ' . $this->description : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/Tag/TagInterface.php b/library/Zend/Code/Generator/DocBlock/Tag/TagInterface.php deleted file mode 100755 index 4d4ef3fcd..000000000 --- a/library/Zend/Code/Generator/DocBlock/Tag/TagInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -types)) ? ' ' . $this->getTypesAsString() : '') - . ((!empty($this->description)) ? ' ' . $this->description : ''); - - return $output; - } -} diff --git a/library/Zend/Code/Generator/DocBlock/TagManager.php b/library/Zend/Code/Generator/DocBlock/TagManager.php deleted file mode 100755 index 4ff3a2bc6..000000000 --- a/library/Zend/Code/Generator/DocBlock/TagManager.php +++ /dev/null @@ -1,69 +0,0 @@ -addPrototype(new Tag\ParamTag()); - $this->addPrototype(new Tag\ReturnTag()); - $this->addPrototype(new Tag\MethodTag()); - $this->addPrototype(new Tag\PropertyTag()); - $this->addPrototype(new Tag\AuthorTag()); - $this->addPrototype(new Tag\LicenseTag()); - $this->addPrototype(new Tag\ThrowsTag()); - $this->setGenericPrototype(new Tag\GenericTag()); - } - - /** - * @param ReflectionTagInterface $reflectionTag - * @return TagInterface - */ - public function createTagFromReflection(ReflectionTagInterface $reflectionTag) - { - $tagName = $reflectionTag->getName(); - - /* @var TagInterface $newTag */ - $newTag = $this->getClonedPrototype($tagName); - - // transport any properties via accessors and mutators from reflection to codegen object - $reflectionClass = new \ReflectionClass($reflectionTag); - foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - if (substr($method->getName(), 0, 3) == 'get') { - $propertyName = substr($method->getName(), 3); - if (method_exists($newTag, 'set' . $propertyName)) { - $newTag->{'set' . $propertyName}($reflectionTag->{'get' . $propertyName}()); - } - } elseif (substr($method->getName(), 0, 2) == 'is') { - $propertyName = ucfirst($method->getName()); - if (method_exists($newTag, 'set' . $propertyName)) { - $newTag->{'set' . $propertyName}($reflectionTag->{$method->getName()}()); - } - } - } - return $newTag; - } -} diff --git a/library/Zend/Code/Generator/DocBlockGenerator.php b/library/Zend/Code/Generator/DocBlockGenerator.php deleted file mode 100755 index e983fa6b1..000000000 --- a/library/Zend/Code/Generator/DocBlockGenerator.php +++ /dev/null @@ -1,274 +0,0 @@ -setSourceContent($reflectionDocBlock->getContents()); - $docBlock->setSourceDirty(false); - - $docBlock->setShortDescription($reflectionDocBlock->getShortDescription()); - $docBlock->setLongDescription($reflectionDocBlock->getLongDescription()); - - foreach ($reflectionDocBlock->getTags() as $tag) { - $docBlock->setTag(self::getTagManager()->createTagFromReflection($tag)); - } - - return $docBlock; - } - - /** - * Generate from array - * - * @configkey shortdescription string The short description for this doc block - * @configkey longdescription string The long description for this doc block - * @configkey tags array - * - * @throws Exception\InvalidArgumentException - * @param array $array - * @return DocBlockGenerator - */ - public static function fromArray(array $array) - { - $docBlock = new static(); - - foreach ($array as $name => $value) { - // normalize key - switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { - case 'shortdescription': - $docBlock->setShortDescription($value); - break; - case 'longdescription': - $docBlock->setLongDescription($value); - break; - case 'tags': - $docBlock->setTags($value); - break; - } - } - - return $docBlock; - } - - protected static function getTagManager() - { - if (!isset(static::$tagManager)) { - static::$tagManager = new TagManager(); - static::$tagManager->initializeDefaultTags(); - } - return static::$tagManager; - } - - /** - * @param string $shortDescription - * @param string $longDescription - * @param array $tags - */ - public function __construct($shortDescription = null, $longDescription = null, array $tags = array()) - { - if ($shortDescription) { - $this->setShortDescription($shortDescription); - } - if ($longDescription) { - $this->setLongDescription($longDescription); - } - if (is_array($tags) && $tags) { - $this->setTags($tags); - } - } - - /** - * @param string $shortDescription - * @return DocBlockGenerator - */ - public function setShortDescription($shortDescription) - { - $this->shortDescription = $shortDescription; - return $this; - } - - /** - * @return string - */ - public function getShortDescription() - { - return $this->shortDescription; - } - - /** - * @param string $longDescription - * @return DocBlockGenerator - */ - public function setLongDescription($longDescription) - { - $this->longDescription = $longDescription; - return $this; - } - - /** - * @return string - */ - public function getLongDescription() - { - return $this->longDescription; - } - - /** - * @param array $tags - * @return DocBlockGenerator - */ - public function setTags(array $tags) - { - foreach ($tags as $tag) { - $this->setTag($tag); - } - - return $this; - } - - /** - * @param array|TagInterface $tag - * @throws Exception\InvalidArgumentException - * @return DocBlockGenerator - */ - public function setTag($tag) - { - if (is_array($tag)) { - // use deprecated Tag class for backward compatiblity to old array-keys - $genericTag = new Tag(); - $genericTag->setOptions($tag); - $tag = $genericTag; - } elseif (!$tag instanceof TagInterface) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects either an array of method options or an instance of %s\DocBlock\Tag\TagInterface', - __METHOD__, - __NAMESPACE__ - )); - } - - $this->tags[] = $tag; - return $this; - } - - /** - * @return TagInterface[] - */ - public function getTags() - { - return $this->tags; - } - - /** - * @param bool $value - * @return DocBlockGenerator - */ - public function setWordWrap($value) - { - $this->wordwrap = (bool) $value; - return $this; - } - - /** - * @return bool - */ - public function getWordWrap() - { - return $this->wordwrap; - } - - /** - * @return string - */ - public function generate() - { - if (!$this->isSourceDirty()) { - return $this->docCommentize(trim($this->getSourceContent())); - } - - $output = ''; - if (null !== ($sd = $this->getShortDescription())) { - $output .= $sd . self::LINE_FEED . self::LINE_FEED; - } - if (null !== ($ld = $this->getLongDescription())) { - $output .= $ld . self::LINE_FEED . self::LINE_FEED; - } - - /* @var $tag GeneratorInterface */ - foreach ($this->getTags() as $tag) { - $output .= $tag->generate() . self::LINE_FEED; - } - - return $this->docCommentize(trim($output)); - } - - /** - * @param string $content - * @return string - */ - protected function docCommentize($content) - { - $indent = $this->getIndentation(); - $output = $indent . '/**' . self::LINE_FEED; - $content = $this->getWordWrap() == true ? wordwrap($content, 80, self::LINE_FEED) : $content; - $lines = explode(self::LINE_FEED, $content); - foreach ($lines as $line) { - $output .= $indent . ' *'; - if ($line) { - $output .= " $line"; - } - $output .= self::LINE_FEED; - } - $output .= $indent . ' */' . self::LINE_FEED; - - return $output; - } -} diff --git a/library/Zend/Code/Generator/Exception/ExceptionInterface.php b/library/Zend/Code/Generator/Exception/ExceptionInterface.php deleted file mode 100755 index d6abfd426..000000000 --- a/library/Zend/Code/Generator/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -setOptions($options); - } - } - - /** - * Use this if you intend on generating code generation objects based on the same file. - * This will keep previous changes to the file in tact during the same PHP process - * - * @param string $filePath - * @param bool $includeIfNotAlreadyIncluded - * @throws ReflectionException\InvalidArgumentException If file does not exists - * @throws ReflectionException\RuntimeException If file exists but is not included or required - * @return FileGenerator - */ - public static function fromReflectedFileName($filePath, $includeIfNotAlreadyIncluded = true) - { - $fileReflector = new FileReflection($filePath, $includeIfNotAlreadyIncluded); - $codeGenerator = static::fromReflection($fileReflector); - - return $codeGenerator; - } - - /** - * @param FileReflection $fileReflection - * @return FileGenerator - */ - public static function fromReflection(FileReflection $fileReflection) - { - $file = new static(); - - $file->setSourceContent($fileReflection->getContents()); - $file->setSourceDirty(false); - - $body = $fileReflection->getContents(); - - $uses = $fileReflection->getUses(); - - foreach ($fileReflection->getClasses() as $class) { - $phpClass = ClassGenerator::fromReflection($class); - $phpClass->setContainingFileGenerator($file); - - foreach ($uses as $fileUse) { - $phpClass->addUse($fileUse['use'], $fileUse['as']); - } - - $file->setClass($phpClass); - } - - $namespace = $fileReflection->getNamespace(); - - if ($namespace != '') { - $file->setNamespace($namespace); - } - - if ($uses) { - $file->setUses($uses); - } - - if (($fileReflection->getDocComment() != '')) { - $docBlock = $fileReflection->getDocBlock(); - $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); - } - - return $file; - } - - /** - * @param array $values - * @return FileGenerator - */ - public static function fromArray(array $values) - { - $fileGenerator = new static; - foreach ($values as $name => $value) { - switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { - case 'filename': - $fileGenerator->setFilename($value); - continue; - case 'class': - $fileGenerator->setClass(($value instanceof ClassGenerator) ? $value : ClassGenerator::fromArray($value)); - continue; - case 'requiredfiles': - $fileGenerator->setRequiredFiles($value); - continue; - default: - if (property_exists($fileGenerator, $name)) { - $fileGenerator->{$name} = $value; - } elseif (method_exists($fileGenerator, 'set' . $name)) { - $fileGenerator->{'set' . $name}($value); - } - } - } - - return $fileGenerator; - } - - /** - * @param DocBlockGenerator|string $docBlock - * @throws Exception\InvalidArgumentException - * @return FileGenerator - */ - public function setDocBlock($docBlock) - { - if (is_string($docBlock)) { - $docBlock = array('shortDescription' => $docBlock); - } - - if (is_array($docBlock)) { - $docBlock = new DocBlockGenerator($docBlock); - } elseif (!$docBlock instanceof DocBlockGenerator) { - throw new Exception\InvalidArgumentException(sprintf( - '%s is expecting either a string, array or an instance of %s\DocBlockGenerator', - __METHOD__, - __NAMESPACE__ - )); - } - - $this->docBlock = $docBlock; - return $this; - } - - /** - * @return DocBlockGenerator - */ - public function getDocBlock() - { - return $this->docBlock; - } - - /** - * @param array $requiredFiles - * @return FileGenerator - */ - public function setRequiredFiles(array $requiredFiles) - { - $this->requiredFiles = $requiredFiles; - return $this; - } - - /** - * @return array - */ - public function getRequiredFiles() - { - return $this->requiredFiles; - } - - /** - * @return string - */ - public function getNamespace() - { - return $this->namespace; - } - - /** - * @param string $namespace - * @return FileGenerator - */ - public function setNamespace($namespace) - { - $this->namespace = (string) $namespace; - return $this; - } - - /** - * Returns an array with the first element the use statement, second is the as part. - * If $withResolvedAs is set to true, there will be a third element that is the - * "resolved" as statement, as the second part is not required in use statements - * - * @param bool $withResolvedAs - * @return array - */ - public function getUses($withResolvedAs = false) - { - $uses = $this->uses; - if ($withResolvedAs) { - for ($useIndex = 0, $count = count($uses); $useIndex < $count; $useIndex++) { - if ($uses[$useIndex][1] == '') { - if (($lastSeparator = strrpos($uses[$useIndex][0], '\\')) !== false) { - $uses[$useIndex][2] = substr($uses[$useIndex][0], $lastSeparator + 1); - } else { - $uses[$useIndex][2] = $uses[$useIndex][0]; - } - } else { - $uses[$useIndex][2] = $uses[$useIndex][1]; - } - } - } - - return $uses; - } - - /** - * @param array $uses - * @return FileGenerator - */ - public function setUses(array $uses) - { - foreach ($uses as $use) { - $use = (array) $use; - if (array_key_exists('use', $use) && array_key_exists('as', $use)) { - $import = $use['use']; - $alias = $use['as']; - } elseif (count($use) == 2) { - list($import, $alias) = $use; - } else { - $import = current($use); - $alias = null; - } - $this->setUse($import, $alias); - } - return $this; - } - - /** - * @param string $use - * @param null|string $as - * @return FileGenerator - */ - public function setUse($use, $as = null) - { - if (!in_array(array($use, $as), $this->uses)) { - $this->uses[] = array($use, $as); - } - return $this; - } - - /** - * @param array $classes - * @return FileGenerator - */ - public function setClasses(array $classes) - { - foreach ($classes as $class) { - $this->setClass($class); - } - - return $this; - } - - /** - * @param string $name - * @return ClassGenerator - */ - public function getClass($name = null) - { - if ($name == null) { - reset($this->classes); - - return current($this->classes); - } - - return $this->classes[(string) $name]; - } - - /** - * @param array|string|ClassGenerator $class - * @throws Exception\InvalidArgumentException - * @return FileGenerator - */ - public function setClass($class) - { - if (is_array($class)) { - $class = ClassGenerator::fromArray($class); - } elseif (is_string($class)) { - $class = new ClassGenerator($class); - } elseif (!$class instanceof ClassGenerator) { - throw new Exception\InvalidArgumentException(sprintf( - '%s is expecting either a string, array or an instance of %s\ClassGenerator', - __METHOD__, - __NAMESPACE__ - )); - } - - // @todo check for dup here - $className = $class->getName(); - $this->classes[$className] = $class; - - return $this; - } - - /** - * @param string $filename - * @return FileGenerator - */ - public function setFilename($filename) - { - $this->filename = (string) $filename; - return $this; - } - - /** - * @return string - */ - public function getFilename() - { - return $this->filename; - } - - /** - * @return ClassGenerator[] - */ - public function getClasses() - { - return $this->classes; - } - - /** - * @param string $body - * @return FileGenerator - */ - public function setBody($body) - { - $this->body = (string) $body; - return $this; - } - - /** - * @return string - */ - public function getBody() - { - return $this->body; - } - - /** - * @return bool - */ - public function isSourceDirty() - { - $docBlock = $this->getDocBlock(); - if ($docBlock && $docBlock->isSourceDirty()) { - return true; - } - - foreach ($this->classes as $class) { - if ($class->isSourceDirty()) { - return true; - } - } - - return parent::isSourceDirty(); - } - - /** - * @return string - */ - public function generate() - { - if ($this->isSourceDirty() === false) { - return $this->sourceContent; - } - - $output = ''; - - // @note body gets populated when FileGenerator created - // from a file. @see fromReflection and may also be set - // via FileGenerator::setBody - $body = $this->getBody(); - - // start with the body (if there), or open tag - if (preg_match('#(?:\s*)<\?php#', $body) == false) { - $output = 'getDocBlock())) { - $docBlock->setIndentation(''); - - if (preg_match('#/\* Zend_Code_Generator_FileGenerator-DocBlockMarker \*/#m', $output)) { - $output = preg_replace('#/\* Zend_Code_Generator_FileGenerator-DocBlockMarker \*/#m', $docBlock->generate(), $output, 1); - } else { - $output .= $docBlock->generate() . self::LINE_FEED; - } - } - - // newline - $output .= self::LINE_FEED; - - // namespace, if any - $namespace = $this->getNamespace(); - if ($namespace) { - $namespace = sprintf('namespace %s;%s', $namespace, str_repeat(self::LINE_FEED, 2)); - if (preg_match('#/\* Zend_Code_Generator_FileGenerator-NamespaceMarker \*/#m', $output)) { - $output = preg_replace('#/\* Zend_Code_Generator_FileGenerator-NamespaceMarker \*/#m', $namespace, - $output, 1); - } else { - $output .= $namespace; - } - } - - // process required files - // @todo marker replacement for required files - $requiredFiles = $this->getRequiredFiles(); - if (!empty($requiredFiles)) { - foreach ($requiredFiles as $requiredFile) { - $output .= 'require_once \'' . $requiredFile . '\';' . self::LINE_FEED; - } - - $output .= self::LINE_FEED; - } - - $classes = $this->getClasses(); - $classUses = array(); - //build uses array - foreach ($classes as $class) { - //check for duplicate use statements - $uses = $class->getUses(); - if (!empty($uses) && is_array($uses)) { - $classUses = array_merge($classUses, $uses); - } - } - - // process import statements - $uses = $this->getUses(); - if (!empty($uses)) { - $useOutput = ''; - - foreach ($uses as $use) { - list($import, $alias) = $use; - if (null === $alias) { - $tempOutput = sprintf('%s', $import); - } else { - $tempOutput = sprintf('%s as %s', $import, $alias); - } - - //don't duplicate use statements - if (!in_array($tempOutput, $classUses)) { - $useOutput .= "use ". $tempOutput .";"; - $useOutput .= self::LINE_FEED; - } - } - $useOutput .= self::LINE_FEED; - - if (preg_match('#/\* Zend_Code_Generator_FileGenerator-UseMarker \*/#m', $output)) { - $output = preg_replace('#/\* Zend_Code_Generator_FileGenerator-UseMarker \*/#m', $useOutput, - $output, 1); - } else { - $output .= $useOutput; - } - } - - // process classes - if (!empty($classes)) { - foreach ($classes as $class) { - $regex = str_replace('&', $class->getName(), '/\* Zend_Code_Generator_Php_File-ClassMarker: \{[A-Za-z0-9\\\]+?&\} \*/'); - if (preg_match('#' . $regex . '#m', $output)) { - $output = preg_replace('#' . $regex . '#', $class->generate(), $output, 1); - } else { - if ($namespace) { - $class->setNamespaceName(null); - } - $output .= $class->generate() . self::LINE_FEED; - } - } - } - - if (!empty($body)) { - // add an extra space between classes and - if (!empty($classes)) { - $output .= self::LINE_FEED; - } - - $output .= $body; - } - - return $output; - } - - /** - * @return FileGenerator - * @throws Exception\RuntimeException - */ - public function write() - { - if ($this->filename == '' || !is_writable(dirname($this->filename))) { - throw new Exception\RuntimeException('This code generator object is not writable.'); - } - file_put_contents($this->filename, $this->generate()); - - return $this; - } -} diff --git a/library/Zend/Code/Generator/FileGeneratorRegistry.php b/library/Zend/Code/Generator/FileGeneratorRegistry.php deleted file mode 100755 index 164cc5254..000000000 --- a/library/Zend/Code/Generator/FileGeneratorRegistry.php +++ /dev/null @@ -1,44 +0,0 @@ -getFilename(); - } - - if ($fileName == '') { - throw new RuntimeException('FileName does not exist.'); - } - - // cannot use realpath since the file might not exist, but we do need to have the index - // in the same DIRECTORY_SEPARATOR that realpath would use: - $fileName = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $fileName); - - static::$fileCodeGenerators[$fileName] = $fileCodeGenerator; - } -} diff --git a/library/Zend/Code/Generator/GeneratorInterface.php b/library/Zend/Code/Generator/GeneratorInterface.php deleted file mode 100755 index 77e1eb8c8..000000000 --- a/library/Zend/Code/Generator/GeneratorInterface.php +++ /dev/null @@ -1,15 +0,0 @@ -setSourceContent($reflectionMethod->getContents(false)); - $method->setSourceDirty(false); - - if ($reflectionMethod->getDocComment() != '') { - $method->setDocBlock(DocBlockGenerator::fromReflection($reflectionMethod->getDocBlock())); - } - - $method->setFinal($reflectionMethod->isFinal()); - - if ($reflectionMethod->isPrivate()) { - $method->setVisibility(self::VISIBILITY_PRIVATE); - } elseif ($reflectionMethod->isProtected()) { - $method->setVisibility(self::VISIBILITY_PROTECTED); - } else { - $method->setVisibility(self::VISIBILITY_PUBLIC); - } - - $method->setStatic($reflectionMethod->isStatic()); - - $method->setName($reflectionMethod->getName()); - - foreach ($reflectionMethod->getParameters() as $reflectionParameter) { - $method->setParameter(ParameterGenerator::fromReflection($reflectionParameter)); - } - - $method->setBody($reflectionMethod->getBody()); - - return $method; - } - - /** - * Generate from array - * - * @configkey name string [required] Class Name - * @configkey docblock string The docblock information - * @configkey flags int Flags, one of MethodGenerator::FLAG_ABSTRACT MethodGenerator::FLAG_FINAL - * @configkey parameters string Class which this class is extending - * @configkey body string - * @configkey abstract bool - * @configkey final bool - * @configkey static bool - * @configkey visibility string - * - * @throws Exception\InvalidArgumentException - * @param array $array - * @return MethodGenerator - */ - public static function fromArray(array $array) - { - if (!isset($array['name'])) { - throw new Exception\InvalidArgumentException( - 'Method generator requires that a name is provided for this object' - ); - } - - $method = new static($array['name']); - foreach ($array as $name => $value) { - // normalize key - switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { - case 'docblock': - $docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value); - $method->setDocBlock($docBlock); - break; - case 'flags': - $method->setFlags($value); - break; - case 'parameters': - $method->setParameters($value); - break; - case 'body': - $method->setBody($value); - break; - case 'abstract': - $method->setAbstract($value); - break; - case 'final': - $method->setFinal($value); - break; - case 'static': - $method->setStatic($value); - break; - case 'visibility': - $method->setVisibility($value); - break; - } - } - - return $method; - } - - /** - * @param string $name - * @param array $parameters - * @param int $flags - * @param string $body - * @param DocBlockGenerator|string $docBlock - */ - public function __construct( - $name = null, - array $parameters = array(), - $flags = self::FLAG_PUBLIC, - $body = null, - $docBlock = null - ) { - if ($name) { - $this->setName($name); - } - if ($parameters) { - $this->setParameters($parameters); - } - if ($flags !== self::FLAG_PUBLIC) { - $this->setFlags($flags); - } - if ($body) { - $this->setBody($body); - } - if ($docBlock) { - $this->setDocBlock($docBlock); - } - } - - /** - * @param array $parameters - * @return MethodGenerator - */ - public function setParameters(array $parameters) - { - foreach ($parameters as $parameter) { - $this->setParameter($parameter); - } - - return $this; - } - - /** - * @param ParameterGenerator|string $parameter - * @throws Exception\InvalidArgumentException - * @return MethodGenerator - */ - public function setParameter($parameter) - { - if (is_string($parameter)) { - $parameter = new ParameterGenerator($parameter); - } elseif (!$parameter instanceof ParameterGenerator) { - throw new Exception\InvalidArgumentException(sprintf( - '%s is expecting either a string, array or an instance of %s\ParameterGenerator', - __METHOD__, - __NAMESPACE__ - )); - } - - $parameterName = $parameter->getName(); - - $this->parameters[$parameterName] = $parameter; - - return $this; - } - - /** - * @return ParameterGenerator[] - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * @param string $body - * @return MethodGenerator - */ - public function setBody($body) - { - $this->body = $body; - return $this; - } - - /** - * @return string - */ - public function getBody() - { - return $this->body; - } - - /** - * @return string - */ - public function generate() - { - $output = ''; - - $indent = $this->getIndentation(); - - if (($docBlock = $this->getDocBlock()) !== null) { - $docBlock->setIndentation($indent); - $output .= $docBlock->generate(); - } - - $output .= $indent; - - if ($this->isAbstract()) { - $output .= 'abstract '; - } else { - $output .= (($this->isFinal()) ? 'final ' : ''); - } - - $output .= $this->getVisibility() - . (($this->isStatic()) ? ' static' : '') - . ' function ' . $this->getName() . '('; - - $parameters = $this->getParameters(); - if (!empty($parameters)) { - foreach ($parameters as $parameter) { - $parameterOutput[] = $parameter->generate(); - } - - $output .= implode(', ', $parameterOutput); - } - - $output .= ')'; - - if ($this->isAbstract()) { - return $output . ';'; - } - - $output .= self::LINE_FEED . $indent . '{' . self::LINE_FEED; - - if ($this->body) { - $output .= preg_replace('#^((?![a-zA-Z0-9_-]+;).+?)$#m', $indent . $indent . '$1', trim($this->body)) - . self::LINE_FEED; - } - - $output .= $indent . '}' . self::LINE_FEED; - - return $output; - } - - public function __toString() - { - return $this->generate(); - } -} diff --git a/library/Zend/Code/Generator/ParameterGenerator.php b/library/Zend/Code/Generator/ParameterGenerator.php deleted file mode 100755 index 30fad22c0..000000000 --- a/library/Zend/Code/Generator/ParameterGenerator.php +++ /dev/null @@ -1,300 +0,0 @@ -setName($reflectionParameter->getName()); - - if ($reflectionParameter->isArray()) { - $param->setType('array'); - } elseif (method_exists($reflectionParameter, 'isCallable') && $reflectionParameter->isCallable()) { - $param->setType('callable'); - } else { - $typeClass = $reflectionParameter->getClass(); - if ($typeClass) { - $parameterType = $typeClass->getName(); - $currentNamespace = $reflectionParameter->getDeclaringClass()->getNamespaceName(); - - if (!empty($currentNamespace) && substr($parameterType, 0, strlen($currentNamespace)) == $currentNamespace) { - $parameterType = substr($parameterType, strlen($currentNamespace) + 1); - } else { - $parameterType = '\\' . trim($parameterType, '\\'); - } - - $param->setType($parameterType); - } - } - - $param->setPosition($reflectionParameter->getPosition()); - - if ($reflectionParameter->isOptional()) { - $param->setDefaultValue($reflectionParameter->getDefaultValue()); - } - $param->setPassedByReference($reflectionParameter->isPassedByReference()); - - return $param; - } - - /** - * Generate from array - * - * @configkey name string [required] Class Name - * @configkey type string - * @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator - * @configkey passedbyreference bool - * @configkey position int - * @configkey sourcedirty bool - * @configkey indentation string - * @configkey sourcecontent string - * - * @throws Exception\InvalidArgumentException - * @param array $array - * @return ParameterGenerator - */ - public static function fromArray(array $array) - { - if (!isset($array['name'])) { - throw new Exception\InvalidArgumentException( - 'Paramerer generator requires that a name is provided for this object' - ); - } - - $param = new static($array['name']); - foreach ($array as $name => $value) { - // normalize key - switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { - case 'type': - $param->setType($value); - break; - case 'defaultvalue': - $param->setDefaultValue($value); - break; - case 'passedbyreference': - $param->setPassedByReference($value); - break; - case 'position': - $param->setPosition($value); - break; - case 'sourcedirty': - $param->setSourceDirty($value); - break; - case 'indentation': - $param->setIndentation($value); - break; - case 'sourcecontent': - $param->setSourceContent($value); - break; - } - } - - return $param; - } - - /** - * @param string $name - * @param string $type - * @param mixed $defaultValue - * @param int $position - * @param bool $passByReference - */ - public function __construct( - $name = null, - $type = null, - $defaultValue = null, - $position = null, - $passByReference = false - ) { - if (null !== $name) { - $this->setName($name); - } - if (null !== $type) { - $this->setType($type); - } - if (null !== $defaultValue) { - $this->setDefaultValue($defaultValue); - } - if (null !== $position) { - $this->setPosition($position); - } - if (false !== $passByReference) { - $this->setPassedByReference(true); - } - } - - /** - * @param string $type - * @return ParameterGenerator - */ - public function setType($type) - { - $this->type = (string) $type; - return $this; - } - - /** - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * @param string $name - * @return ParameterGenerator - */ - public function setName($name) - { - $this->name = (string) $name; - return $this; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Set the default value of the parameter. - * - * Certain variables are difficult to express - * - * @param null|bool|string|int|float|array|ValueGenerator $defaultValue - * @return ParameterGenerator - */ - public function setDefaultValue($defaultValue) - { - if (!($defaultValue instanceof ValueGenerator)) { - $defaultValue = new ValueGenerator($defaultValue); - } - $this->defaultValue = $defaultValue; - - return $this; - } - - /** - * @return string - */ - public function getDefaultValue() - { - return $this->defaultValue; - } - - /** - * @param int $position - * @return ParameterGenerator - */ - public function setPosition($position) - { - $this->position = (int) $position; - return $this; - } - - /** - * @return int - */ - public function getPosition() - { - return $this->position; - } - - /** - * @return bool - */ - public function getPassedByReference() - { - return $this->passedByReference; - } - - /** - * @param bool $passedByReference - * @return ParameterGenerator - */ - public function setPassedByReference($passedByReference) - { - $this->passedByReference = (bool) $passedByReference; - return $this; - } - - /** - * @return string - */ - public function generate() - { - $output = ''; - - if ($this->type && !in_array($this->type, static::$simple)) { - $output .= $this->type . ' '; - } - - if (true === $this->passedByReference) { - $output .= '&'; - } - - $output .= '$' . $this->name; - - if ($this->defaultValue !== null) { - $output .= ' = '; - if (is_string($this->defaultValue)) { - $output .= ValueGenerator::escape($this->defaultValue); - } elseif ($this->defaultValue instanceof ValueGenerator) { - $this->defaultValue->setOutputMode(ValueGenerator::OUTPUT_SINGLE_LINE); - $output .= $this->defaultValue; - } else { - $output .= $this->defaultValue; - } - } - - return $output; - } -} diff --git a/library/Zend/Code/Generator/PropertyGenerator.php b/library/Zend/Code/Generator/PropertyGenerator.php deleted file mode 100755 index 36735ad37..000000000 --- a/library/Zend/Code/Generator/PropertyGenerator.php +++ /dev/null @@ -1,226 +0,0 @@ -setName($reflectionProperty->getName()); - - $allDefaultProperties = $reflectionProperty->getDeclaringClass()->getDefaultProperties(); - - $property->setDefaultValue($allDefaultProperties[$reflectionProperty->getName()]); - - if ($reflectionProperty->getDocComment() != '') { - $property->setDocBlock(DocBlockGenerator::fromReflection($reflectionProperty->getDocBlock())); - } - - if ($reflectionProperty->isStatic()) { - $property->setStatic(true); - } - - if ($reflectionProperty->isPrivate()) { - $property->setVisibility(self::VISIBILITY_PRIVATE); - } elseif ($reflectionProperty->isProtected()) { - $property->setVisibility(self::VISIBILITY_PROTECTED); - } else { - $property->setVisibility(self::VISIBILITY_PUBLIC); - } - - $property->setSourceDirty(false); - - return $property; - } - - /** - * Generate from array - * - * @configkey name string [required] Class Name - * @configkey const bool - * @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator - * @configkey flags int - * @configkey abstract bool - * @configkey final bool - * @configkey static bool - * @configkey visibility string - * - * @throws Exception\InvalidArgumentException - * @param array $array - * @return PropertyGenerator - */ - public static function fromArray(array $array) - { - if (!isset($array['name'])) { - throw new Exception\InvalidArgumentException( - 'Property generator requires that a name is provided for this object' - ); - } - - $property = new static($array['name']); - foreach ($array as $name => $value) { - // normalize key - switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { - case 'const': - $property->setConst($value); - break; - case 'defaultvalue': - $property->setDefaultValue($value); - break; - case 'docblock': - $docBlock = ($value instanceof DocBlockGenerator) ? $value : DocBlockGenerator::fromArray($value); - $property->setDocBlock($docBlock); - break; - case 'flags': - $property->setFlags($value); - break; - case 'abstract': - $property->setAbstract($value); - break; - case 'final': - $property->setFinal($value); - break; - case 'static': - $property->setStatic($value); - break; - case 'visibility': - $property->setVisibility($value); - break; - } - } - - return $property; - } - - /** - * @param string $name - * @param PropertyValueGenerator|string|array $defaultValue - * @param int $flags - */ - public function __construct($name = null, $defaultValue = null, $flags = self::FLAG_PUBLIC) - { - if (null !== $name) { - $this->setName($name); - } - if (null !== $defaultValue) { - $this->setDefaultValue($defaultValue); - } - if ($flags !== self::FLAG_PUBLIC) { - $this->setFlags($flags); - } - } - - /** - * @param bool $const - * @return PropertyGenerator - */ - public function setConst($const) - { - if ($const) { - $this->removeFlag(self::FLAG_PUBLIC | self::FLAG_PRIVATE | self::FLAG_PROTECTED); - $this->setFlags(self::FLAG_CONSTANT); - } else { - $this->removeFlag(self::FLAG_CONSTANT); - } - - return $this; - } - - /** - * @return bool - */ - public function isConst() - { - return (bool) ($this->flags & self::FLAG_CONSTANT); - } - - /** - * @param PropertyValueGenerator|mixed $defaultValue - * @param string $defaultValueType - * @param string $defaultValueOutputMode - * - * @return PropertyGenerator - */ - public function setDefaultValue($defaultValue, $defaultValueType = PropertyValueGenerator::TYPE_AUTO, $defaultValueOutputMode = PropertyValueGenerator::OUTPUT_MULTIPLE_LINE) - { - if (!($defaultValue instanceof PropertyValueGenerator)) { - $defaultValue = new PropertyValueGenerator($defaultValue, $defaultValueType, $defaultValueOutputMode); - } - - $this->defaultValue = $defaultValue; - - return $this; - } - - /** - * @return PropertyValueGenerator - */ - public function getDefaultValue() - { - return $this->defaultValue; - } - - /** - * @throws Exception\RuntimeException - * @return string - */ - public function generate() - { - $name = $this->getName(); - $defaultValue = $this->getDefaultValue(); - - $output = ''; - - if (($docBlock = $this->getDocBlock()) !== null) { - $docBlock->setIndentation(' '); - $output .= $docBlock->generate(); - } - - if ($this->isConst()) { - if ($defaultValue != null && !$defaultValue->isValidConstantType()) { - throw new Exception\RuntimeException(sprintf( - 'The property %s is said to be ' - . 'constant but does not have a valid constant value.', - $this->name - )); - } - $output .= $this->indentation . 'const ' . $name . ' = ' - . (($defaultValue !== null) ? $defaultValue->generate() : 'null;'); - } else { - $output .= $this->indentation - . $this->getVisibility() - . (($this->isStatic()) ? ' static' : '') - . ' $' . $name . ' = ' - . (($defaultValue !== null) ? $defaultValue->generate() : 'null;'); - } - - return $output; - } -} diff --git a/library/Zend/Code/Generator/PropertyValueGenerator.php b/library/Zend/Code/Generator/PropertyValueGenerator.php deleted file mode 100755 index f36fc8c1f..000000000 --- a/library/Zend/Code/Generator/PropertyValueGenerator.php +++ /dev/null @@ -1,23 +0,0 @@ -setValue($value); - } - if ($type !== self::TYPE_AUTO) { - $this->setType($type); - } - if ($outputMode !== self::OUTPUT_MULTIPLE_LINE) { - $this->setOutputMode($outputMode); - } - if ($constants !== null) { - $this->constants = $constants; - } else { - $this->constants = new ArrayObject(); - } - } - - /** - * Init constant list by defined and magic constants - */ - public function initEnvironmentConstants() - { - $constants = array( - '__DIR__', - '__FILE__', - '__LINE__', - '__CLASS__', - '__TRAIT__', - '__METHOD__', - '__FUNCTION__', - '__NAMESPACE__', - '::' - ); - $constants = array_merge($constants, array_keys(get_defined_constants()), $this->constants->getArrayCopy()); - $this->constants->exchangeArray($constants); - } - - /** - * Add constant to list - * - * @param string $constant - * - * @return $this - */ - public function addConstant($constant) - { - $this->constants->append($constant); - - return $this; - } - - /** - * Delete constant from constant list - * - * @param string $constant - * - * @return bool - */ - public function deleteConstant($constant) - { - if (($index = array_search($constant, $this->constants->getArrayCopy())) !== false) { - $this->constants->offsetUnset($index); - } - - return $index !== false; - } - - /** - * Return constant list - * - * @return ArrayObject - */ - public function getConstants() - { - return $this->constants; - } - - /** - * @return bool - */ - public function isValidConstantType() - { - if ($this->type == self::TYPE_AUTO) { - $type = $this->getAutoDeterminedType($this->value); - } else { - $type = $this->type; - } - - // valid types for constants - $scalarTypes = array( - self::TYPE_BOOLEAN, - self::TYPE_BOOL, - self::TYPE_NUMBER, - self::TYPE_INTEGER, - self::TYPE_INT, - self::TYPE_FLOAT, - self::TYPE_DOUBLE, - self::TYPE_STRING, - self::TYPE_CONSTANT, - self::TYPE_NULL - ); - - return in_array($type, $scalarTypes); - } - - /** - * @param mixed $value - * @return ValueGenerator - */ - public function setValue($value) - { - $this->value = $value; - return $this; - } - - /** - * @return mixed - */ - public function getValue() - { - return $this->value; - } - - /** - * @param string $type - * @return ValueGenerator - */ - public function setType($type) - { - $this->type = (string) $type; - return $this; - } - - /** - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * @param int $arrayDepth - * @return ValueGenerator - */ - public function setArrayDepth($arrayDepth) - { - $this->arrayDepth = (int) $arrayDepth; - return $this; - } - - /** - * @return int - */ - public function getArrayDepth() - { - return $this->arrayDepth; - } - - /** - * @param string $type - * @return string - */ - protected function getValidatedType($type) - { - $types = array( - self::TYPE_AUTO, - self::TYPE_BOOLEAN, - self::TYPE_BOOL, - self::TYPE_NUMBER, - self::TYPE_INTEGER, - self::TYPE_INT, - self::TYPE_FLOAT, - self::TYPE_DOUBLE, - self::TYPE_STRING, - self::TYPE_ARRAY, - self::TYPE_CONSTANT, - self::TYPE_NULL, - self::TYPE_OBJECT, - self::TYPE_OTHER - ); - - if (in_array($type, $types)) { - return $type; - } - - return self::TYPE_AUTO; - } - - /** - * @param mixed $value - * @return string - */ - public function getAutoDeterminedType($value) - { - switch (gettype($value)) { - case 'boolean': - return self::TYPE_BOOLEAN; - case 'string': - foreach ($this->constants as $constant) { - if (strpos($value, $constant) !== false) { - return self::TYPE_CONSTANT; - } - } - return self::TYPE_STRING; - case 'double': - case 'float': - case 'integer': - return self::TYPE_NUMBER; - case 'array': - return self::TYPE_ARRAY; - case 'NULL': - return self::TYPE_NULL; - case 'object': - case 'resource': - case 'unknown type': - default: - return self::TYPE_OTHER; - } - } - - /** - * @throws Exception\RuntimeException - * @return string - */ - public function generate() - { - $type = $this->type; - - if ($type != self::TYPE_AUTO) { - $type = $this->getValidatedType($type); - } - - $value = $this->value; - - if ($type == self::TYPE_AUTO) { - $type = $this->getAutoDeterminedType($value); - } - - if ($type == self::TYPE_ARRAY) { - foreach ($value as &$curValue) { - if ($curValue instanceof self) { - continue; - } - $curValue = new self($curValue, self::TYPE_AUTO, self::OUTPUT_MULTIPLE_LINE, $this->getConstants()); - } - } - - $output = ''; - - switch ($type) { - case self::TYPE_BOOLEAN: - case self::TYPE_BOOL: - $output .= ($value ? 'true' : 'false'); - break; - case self::TYPE_STRING: - $output .= self::escape($value); - break; - case self::TYPE_NULL: - $output .= 'null'; - break; - case self::TYPE_NUMBER: - case self::TYPE_INTEGER: - case self::TYPE_INT: - case self::TYPE_FLOAT: - case self::TYPE_DOUBLE: - case self::TYPE_CONSTANT: - $output .= $value; - break; - case self::TYPE_ARRAY: - $output .= 'array('; - if ($this->outputMode == self::OUTPUT_MULTIPLE_LINE) { - $output .= self::LINE_FEED . str_repeat($this->indentation, $this->arrayDepth + 1); - } - $outputParts = array(); - $noKeyIndex = 0; - foreach ($value as $n => $v) { - /* @var $v ValueGenerator */ - $v->setArrayDepth($this->arrayDepth + 1); - $partV = $v->generate(); - $short = false; - if (is_int($n)) { - if ($n === $noKeyIndex) { - $short = true; - $noKeyIndex++; - } else { - $noKeyIndex = max($n + 1, $noKeyIndex); - } - } - - if ($short) { - $outputParts[] = $partV; - } else { - $outputParts[] = (is_int($n) ? $n : self::escape($n)) . ' => ' . $partV; - } - } - $padding = ($this->outputMode == self::OUTPUT_MULTIPLE_LINE) - ? self::LINE_FEED . str_repeat($this->indentation, $this->arrayDepth + 1) - : ' '; - $output .= implode(',' . $padding, $outputParts); - if ($this->outputMode == self::OUTPUT_MULTIPLE_LINE) { - $output .= self::LINE_FEED . str_repeat($this->indentation, $this->arrayDepth); - } - $output .= ')'; - break; - case self::TYPE_OTHER: - default: - throw new Exception\RuntimeException( - sprintf('Type "%s" is unknown or cannot be used as property default value.', get_class($value)) - ); - } - - return $output; - } - - /** - * Quotes value for PHP code. - * - * @param string $input Raw string. - * @param bool $quote Whether add surrounding quotes or not. - * @return string PHP-ready code. - */ - public static function escape($input, $quote = true) - { - $output = addcslashes($input, "\\'"); - - // adds quoting strings - if ($quote) { - $output = "'" . $output . "'"; - } - - return $output; - } - - /** - * @param string $outputMode - * @return ValueGenerator - */ - public function setOutputMode($outputMode) - { - $this->outputMode = (string) $outputMode; - return $this; - } - - /** - * @return string - */ - public function getOutputMode() - { - return $this->outputMode; - } - - public function __toString() - { - return $this->generate(); - } -} diff --git a/library/Zend/Code/Generic/Prototype/PrototypeClassFactory.php b/library/Zend/Code/Generic/Prototype/PrototypeClassFactory.php deleted file mode 100755 index 7c3a9bf1b..000000000 --- a/library/Zend/Code/Generic/Prototype/PrototypeClassFactory.php +++ /dev/null @@ -1,121 +0,0 @@ -addPrototype($prototype); - } - - if ($genericPrototype) { - $this->setGenericPrototype($genericPrototype); - } - } - - /** - * @param PrototypeInterface $prototype - * @throws Exception\InvalidArgumentException - */ - public function addPrototype(PrototypeInterface $prototype) - { - $prototypeName = $this->normalizeName($prototype->getName()); - - if (isset($this->prototypes[$prototypeName])) { - throw new Exception\InvalidArgumentException('A prototype with this name already exists in this manager'); - } - - $this->prototypes[$prototypeName] = $prototype; - } - - /** - * @param PrototypeGenericInterface $prototype - * @throws Exception\InvalidArgumentException - */ - public function setGenericPrototype(PrototypeGenericInterface $prototype) - { - if (isset($this->genericPrototype)) { - throw new Exception\InvalidArgumentException('A default prototype is already set'); - } - - $this->genericPrototype = $prototype; - } - - /** - * @param string $name - * @return string - */ - protected function normalizeName($name) - { - return str_replace(array('-', '_'), '', $name); - } - - /** - * @param string $name - * @return bool - */ - public function hasPrototype($name) - { - $name = $this->normalizeName($name); - return isset($this->prototypes[$name]); - } - - /** - * @param string $prototypeName - * @return PrototypeInterface - * @throws Exception\RuntimeException - */ - public function getClonedPrototype($prototypeName) - { - $prototypeName = $this->normalizeName($prototypeName); - - if (!$this->hasPrototype($prototypeName) && !isset($this->genericPrototype)) { - throw new Exception\RuntimeException('This tag name is not supported by this tag manager'); - } - - if (!$this->hasPrototype($prototypeName)) { - $newPrototype = clone $this->genericPrototype; - $newPrototype->setName($prototypeName); - } else { - $newPrototype = clone $this->prototypes[$prototypeName]; - } - - return $newPrototype; - } -} diff --git a/library/Zend/Code/Generic/Prototype/PrototypeGenericInterface.php b/library/Zend/Code/Generic/Prototype/PrototypeGenericInterface.php deleted file mode 100755 index 3a5e44a88..000000000 --- a/library/Zend/Code/Generic/Prototype/PrototypeGenericInterface.php +++ /dev/null @@ -1,18 +0,0 @@ -setNamespace($namespace); - } - if ($uses) { - $this->setUses($uses); - } - } - - /** - * @param string $namespace - * @return NameInformation - */ - public function setNamespace($namespace) - { - $this->namespace = (string) $namespace; - return $this; - } - - /** - * @return string - */ - public function getNamespace() - { - return $this->namespace; - } - - /** - * @return bool - */ - public function hasNamespace() - { - return ($this->namespace != null); - } - - /** - * @param array $uses - * @return NameInformation - */ - public function setUses(array $uses) - { - $this->uses = array(); - $this->addUses($uses); - - return $this; - } - - /** - * @param array $uses - * @return NameInformation - */ - public function addUses(array $uses) - { - foreach ($uses as $use => $as) { - if (is_int($use)) { - $this->addUse($as); - } elseif (is_string($use)) { - $this->addUse($use, $as); - } - } - - return $this; - } - - /** - * @param array|string $use - * @param string $as - */ - public function addUse($use, $as = null) - { - if (is_array($use) && array_key_exists('use', $use) && array_key_exists('as', $use)) { - $uses = $use; - $use = $uses['use']; - $as = $uses['as']; - } - - $use = trim($use, '\\'); - if ($as === null) { - $as = trim($use, '\\'); - $nsSeparatorPosition = strrpos($as, '\\'); - if ($nsSeparatorPosition !== false && $nsSeparatorPosition !== 0 && $nsSeparatorPosition != strlen($as)) { - $as = substr($as, $nsSeparatorPosition + 1); - } - } - - $this->uses[$use] = $as; - } - - /** - * @return array - */ - public function getUses() - { - return $this->uses; - } - - /** - * @param string $name - * @return string - */ - public function resolveName($name) - { - if ($this->namespace && !$this->uses && strlen($name) > 0 && $name{0} != '\\') { - return $this->namespace . '\\' . $name; - } - - if (!$this->uses || strlen($name) <= 0 || $name{0} == '\\') { - return ltrim($name, '\\'); - } - - if ($this->namespace || $this->uses) { - $firstPart = $name; - if (($firstPartEnd = strpos($firstPart, '\\')) !== false) { - $firstPart = substr($firstPart, 0, $firstPartEnd); - } else { - $firstPartEnd = strlen($firstPart); - } - if (($fqns = array_search($firstPart, $this->uses)) !== false) { - return substr_replace($name, $fqns, 0, $firstPartEnd); - } - if ($this->namespace) { - return $this->namespace . '\\' . $name; - } - } - - return $name; - } -} diff --git a/library/Zend/Code/README.md b/library/Zend/Code/README.md deleted file mode 100755 index 640084b57..000000000 --- a/library/Zend/Code/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Code Component from ZF2 -======================= - -This is the Code component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Code/Reflection/ClassReflection.php b/library/Zend/Code/Reflection/ClassReflection.php deleted file mode 100755 index 86d1f14cb..000000000 --- a/library/Zend/Code/Reflection/ClassReflection.php +++ /dev/null @@ -1,257 +0,0 @@ -getFileName()); - - return $instance; - } - - /** - * Return the classes DocBlock reflection object - * - * @return DocBlockReflection - * @throws Exception\ExceptionInterface for missing DocBock or invalid reflection class - */ - public function getDocBlock() - { - if (isset($this->docBlock)) { - return $this->docBlock; - } - - if ('' == $this->getDocComment()) { - return false; - } - - $this->docBlock = new DocBlockReflection($this); - - return $this->docBlock; - } - - /** - * @param AnnotationManager $annotationManager - * @return AnnotationCollection - */ - public function getAnnotations(AnnotationManager $annotationManager) - { - $docComment = $this->getDocComment(); - - if ($docComment == '') { - return false; - } - - if ($this->annotations) { - return $this->annotations; - } - - $fileScanner = $this->createFileScanner($this->getFileName()); - $nameInformation = $fileScanner->getClassNameInformation($this->getName()); - - if (!$nameInformation) { - return false; - } - - $this->annotations = new AnnotationScanner($annotationManager, $docComment, $nameInformation); - - return $this->annotations; - } - - /** - * Return the start line of the class - * - * @param bool $includeDocComment - * @return int - */ - public function getStartLine($includeDocComment = false) - { - if ($includeDocComment && $this->getDocComment() != '') { - return $this->getDocBlock()->getStartLine(); - } - - return parent::getStartLine(); - } - - /** - * Return the contents of the class - * - * @param bool $includeDocBlock - * @return string - */ - public function getContents($includeDocBlock = true) - { - $fileName = $this->getFileName(); - - if (false === $fileName || ! file_exists($fileName)) { - return ''; - } - - $filelines = file($fileName); - $startnum = $this->getStartLine($includeDocBlock); - $endnum = $this->getEndLine() - $this->getStartLine(); - - // Ensure we get between the open and close braces - $lines = array_slice($filelines, $startnum, $endnum); - array_unshift($lines, $filelines[$startnum-1]); - - return strstr(implode('', $lines), '{'); - } - - /** - * Get all reflection objects of implemented interfaces - * - * @return ClassReflection[] - */ - public function getInterfaces() - { - $phpReflections = parent::getInterfaces(); - $zendReflections = array(); - while ($phpReflections && ($phpReflection = array_shift($phpReflections))) { - $instance = new ClassReflection($phpReflection->getName()); - $zendReflections[] = $instance; - unset($phpReflection); - } - unset($phpReflections); - - return $zendReflections; - } - - /** - * Return method reflection by name - * - * @param string $name - * @return MethodReflection - */ - public function getMethod($name) - { - $method = new MethodReflection($this->getName(), parent::getMethod($name)->getName()); - - return $method; - } - - /** - * Get reflection objects of all methods - * - * @param int $filter - * @return MethodReflection[] - */ - public function getMethods($filter = -1) - { - $methods = array(); - foreach (parent::getMethods($filter) as $method) { - $instance = new MethodReflection($this->getName(), $method->getName()); - $methods[] = $instance; - } - - return $methods; - } - - /** - * Get parent reflection class of reflected class - * - * @return ClassReflection|bool - */ - public function getParentClass() - { - $phpReflection = parent::getParentClass(); - if ($phpReflection) { - $zendReflection = new ClassReflection($phpReflection->getName()); - unset($phpReflection); - - return $zendReflection; - } - - return false; - } - - /** - * Return reflection property of this class by name - * - * @param string $name - * @return PropertyReflection - */ - public function getProperty($name) - { - $phpReflection = parent::getProperty($name); - $zendReflection = new PropertyReflection($this->getName(), $phpReflection->getName()); - unset($phpReflection); - - return $zendReflection; - } - - /** - * Return reflection properties of this class - * - * @param int $filter - * @return PropertyReflection[] - */ - public function getProperties($filter = -1) - { - $phpReflections = parent::getProperties($filter); - $zendReflections = array(); - while ($phpReflections && ($phpReflection = array_shift($phpReflections))) { - $instance = new PropertyReflection($this->getName(), $phpReflection->getName()); - $zendReflections[] = $instance; - unset($phpReflection); - } - unset($phpReflections); - - return $zendReflections; - } - - public function toString() - { - return parent::__toString(); - } - - public function __toString() - { - return parent::__toString(); - } - - /** - * Creates a new FileScanner instance. - * - * By having this as a seperate method it allows the method to be overridden - * if a different FileScanner is needed. - * - * @param string $filename - * - * @return FileScanner - */ - protected function createFileScanner($filename) - { - return new FileScanner($filename); - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/AuthorTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/AuthorTag.php deleted file mode 100755 index 9afdee087..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/AuthorTag.php +++ /dev/null @@ -1,74 +0,0 @@ -]*)\>)?(.*)$/u', $tagDocblockLine, $match)) { - return; - } - - if ($match[1] !== '') { - $this->authorName = rtrim($match[1]); - } - - if (isset($match[3]) && $match[3] !== '') { - $this->authorEmail = $match[3]; - } - } - - /** - * @return null|string - */ - public function getAuthorName() - { - return $this->authorName; - } - - /** - * @return null|string - */ - public function getAuthorEmail() - { - return $this->authorEmail; - } - - public function __toString() - { - return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/GenericTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/GenericTag.php deleted file mode 100755 index 9f3481085..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/GenericTag.php +++ /dev/null @@ -1,109 +0,0 @@ -contentSplitCharacter = $contentSplitCharacter; - } - - /** - * @param string $tagDocBlockLine - * @return void - */ - public function initialize($tagDocBlockLine) - { - $this->parse($tagDocBlockLine); - } - - /** - * Get annotation tag name - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * @return string - */ - public function getContent() - { - return $this->content; - } - - /** - * @param int $position - * @return string - */ - public function returnValue($position) - { - return $this->values[$position]; - } - - /** - * Serialize to string - * - * Required by Reflector - * - * @todo What should this do? - * @return string - */ - public function __toString() - { - return 'DocBlock Tag [ * @' . $this->name . ' ]' . PHP_EOL; - } - - /** - * @param string $docBlockLine - */ - protected function parse($docBlockLine) - { - $this->content = trim($docBlockLine); - $this->values = explode($this->contentSplitCharacter, $docBlockLine); - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/LicenseTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/LicenseTag.php deleted file mode 100755 index d1148ef62..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/LicenseTag.php +++ /dev/null @@ -1,74 +0,0 @@ -url = trim($match[1]); - } - - if (isset($match[2]) && $match[2] !== '') { - $this->licenseName = $match[2]; - } - } - - /** - * @return null|string - */ - public function getUrl() - { - return $this->url; - } - - /** - * @return null|string - */ - public function getLicenseName() - { - return $this->licenseName; - } - - public function __toString() - { - return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/MethodTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/MethodTag.php deleted file mode 100755 index 50738bfea..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/MethodTag.php +++ /dev/null @@ -1,122 +0,0 @@ -isStatic = true; - } - - if ($match[2] !== '') { - $this->types = explode('|', rtrim($match[2])); - } - - $this->methodName = $match[3]; - - if ($match[4] !== '') { - $this->description = $match[4]; - } - } - - /** - * Get return value type - * - * @return null|string - * @deprecated 2.0.4 use getTypes instead - */ - public function getReturnType() - { - if (empty($this->types)) { - return null; - } - - return $this->types[0]; - } - - public function getTypes() - { - return $this->types; - } - - /** - * @return string - */ - public function getMethodName() - { - return $this->methodName; - } - - /** - * @return null|string - */ - public function getDescription() - { - return $this->description; - } - - /** - * @return bool - */ - public function isStatic() - { - return $this->isStatic; - } - - public function __toString() - { - return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php deleted file mode 100755 index b11a16e4e..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/ParamTag.php +++ /dev/null @@ -1,98 +0,0 @@ -types = explode('|', $matches[1]); - - if (isset($matches[2])) { - $this->variableName = $matches[2]; - } - - if (isset($matches[3])) { - $this->description = trim(preg_replace('#\s+#', ' ', $matches[3])); - } - } - - /** - * Get parameter variable type - * - * @return string - * @deprecated 2.0.4 use getTypes instead - */ - public function getType() - { - if (empty($this->types)) { - return ''; - } - - return $this->types[0]; - } - - public function getTypes() - { - return $this->types; - } - - /** - * Get parameter name - * - * @return string - */ - public function getVariableName() - { - return $this->variableName; - } - - /** - * @return string - */ - public function getDescription() - { - return $this->description; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/PhpDocTypedTagInterface.php b/library/Zend/Code/Reflection/DocBlock/Tag/PhpDocTypedTagInterface.php deleted file mode 100755 index 01bea4b9d..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/PhpDocTypedTagInterface.php +++ /dev/null @@ -1,20 +0,0 @@ -types = explode('|', rtrim($match[1])); - } - - if ($match[2] !== '') { - $this->propertyName = $match[2]; - } - - if ($match[3] !== '') { - $this->description = $match[3]; - } - } - - /** - * @return null|string - * @deprecated 2.0.4 use getTypes instead - */ - public function getType() - { - if (empty($this->types)) { - return null; - } - - return $this->types[0]; - } - - public function getTypes() - { - return $this->types; - } - - /** - * @return null|string - */ - public function getPropertyName() - { - return $this->propertyName; - } - - /** - * @return null|string - */ - public function getDescription() - { - return $this->description; - } - - public function __toString() - { - return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/ReturnTag.php b/library/Zend/Code/Reflection/DocBlock/Tag/ReturnTag.php deleted file mode 100755 index f43d7e2e3..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/ReturnTag.php +++ /dev/null @@ -1,75 +0,0 @@ -types = explode('|', $matches[1]); - - if (isset($matches[2])) { - $this->description = trim(preg_replace('#\s+#', ' ', $matches[2])); - } - } - - /** - * @return string - * @deprecated 2.0.4 use getTypes instead - */ - public function getType() - { - if (empty($this->types)) { - return ''; - } - - return $this->types[0]; - } - - public function getTypes() - { - return $this->types; - } - - /** - * @return string - */ - public function getDescription() - { - return $this->description; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/Tag/TagInterface.php b/library/Zend/Code/Reflection/DocBlock/Tag/TagInterface.php deleted file mode 100755 index f34e154f6..000000000 --- a/library/Zend/Code/Reflection/DocBlock/Tag/TagInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -types = explode('|', $matches[1]); - - if (isset($matches[2])) { - $this->description = $matches[2]; - } - } - - /** - * Get return variable type - * - * @return string - * @deprecated 2.0.4 use getTypes instead - */ - public function getType() - { - return implode('|', $this->getTypes()); - } - - /** - * @return array - */ - public function getTypes() - { - return $this->types; - } - - /** - * @return string - */ - public function getDescription() - { - return $this->description; - } -} diff --git a/library/Zend/Code/Reflection/DocBlock/TagManager.php b/library/Zend/Code/Reflection/DocBlock/TagManager.php deleted file mode 100755 index 4d8f0da85..000000000 --- a/library/Zend/Code/Reflection/DocBlock/TagManager.php +++ /dev/null @@ -1,48 +0,0 @@ -addPrototype(new Tag\ParamTag()); - $this->addPrototype(new Tag\ReturnTag()); - $this->addPrototype(new Tag\MethodTag()); - $this->addPrototype(new Tag\PropertyTag()); - $this->addPrototype(new Tag\AuthorTag()); - $this->addPrototype(new Tag\LicenseTag()); - $this->addPrototype(new Tag\ThrowsTag()); - $this->setGenericPrototype(new Tag\GenericTag()); - } - - /** - * @param string $tagName - * @param string $content - * @return TagInterface - */ - public function createTag($tagName, $content = null) - { - /* @var TagInterface $newTag */ - $newTag = $this->getClonedPrototype($tagName); - - if ($content) { - $newTag->initialize($content); - } - - return $newTag; - } -} diff --git a/library/Zend/Code/Reflection/DocBlockReflection.php b/library/Zend/Code/Reflection/DocBlockReflection.php deleted file mode 100755 index a49021364..000000000 --- a/library/Zend/Code/Reflection/DocBlockReflection.php +++ /dev/null @@ -1,293 +0,0 @@ -initializeDefaultTags(); - } - $this->tagManager = $tagManager; - - if ($commentOrReflector instanceof Reflector) { - $this->reflector = $commentOrReflector; - if (!method_exists($commentOrReflector, 'getDocComment')) { - throw new Exception\InvalidArgumentException('Reflector must contain method "getDocComment"'); - } - /* @var MethodReflection $commentOrReflector */ - $this->docComment = $commentOrReflector->getDocComment(); - - // determine line numbers - $lineCount = substr_count($this->docComment, "\n"); - $this->startLine = $this->reflector->getStartLine() - $lineCount - 1; - $this->endLine = $this->reflector->getStartLine() - 1; - } elseif (is_string($commentOrReflector)) { - $this->docComment = $commentOrReflector; - } else { - throw new Exception\InvalidArgumentException(sprintf( - '%s must have a (string) DocComment or a Reflector in the constructor', - get_class($this) - )); - } - - if ($this->docComment == '') { - throw new Exception\InvalidArgumentException('DocComment cannot be empty'); - } - - $this->reflect(); - } - - /** - * Retrieve contents of DocBlock - * - * @return string - */ - public function getContents() - { - $this->reflect(); - - return $this->cleanDocComment; - } - - /** - * Get start line (position) of DocBlock - * - * @return int - */ - public function getStartLine() - { - $this->reflect(); - - return $this->startLine; - } - - /** - * Get last line (position) of DocBlock - * - * @return int - */ - public function getEndLine() - { - $this->reflect(); - - return $this->endLine; - } - - /** - * Get DocBlock short description - * - * @return string - */ - public function getShortDescription() - { - $this->reflect(); - - return $this->shortDescription; - } - - /** - * Get DocBlock long description - * - * @return string - */ - public function getLongDescription() - { - $this->reflect(); - - return $this->longDescription; - } - - /** - * Does the DocBlock contain the given annotation tag? - * - * @param string $name - * @return bool - */ - public function hasTag($name) - { - $this->reflect(); - foreach ($this->tags as $tag) { - if ($tag->getName() == $name) { - return true; - } - } - - return false; - } - - /** - * Retrieve the given DocBlock tag - * - * @param string $name - * @return DocBlockTagInterface|false - */ - public function getTag($name) - { - $this->reflect(); - foreach ($this->tags as $tag) { - if ($tag->getName() == $name) { - return $tag; - } - } - - return false; - } - - /** - * Get all DocBlock annotation tags - * - * @param string $filter - * @return DocBlockTagInterface[] - */ - public function getTags($filter = null) - { - $this->reflect(); - if ($filter === null || !is_string($filter)) { - return $this->tags; - } - - $returnTags = array(); - foreach ($this->tags as $tag) { - if ($tag->getName() == $filter) { - $returnTags[] = $tag; - } - } - - return $returnTags; - } - - /** - * Parse the DocBlock - * - * @return void - */ - protected function reflect() - { - if ($this->isReflected) { - return; - } - - $docComment = $this->docComment; // localize variable - - // create a clean docComment - $this->cleanDocComment = preg_replace("#[ \t]*(?:/\*\*|\*/|\*)[ ]{0,1}(.*)?#", '$1', $docComment); - $this->cleanDocComment = ltrim($this->cleanDocComment, "\r\n"); // @todo should be changed to remove first and last empty line - - $scanner = new DocBlockScanner($docComment); - $this->shortDescription = ltrim($scanner->getShortDescription()); - $this->longDescription = ltrim($scanner->getLongDescription()); - - foreach ($scanner->getTags() as $tag) { - $this->tags[] = $this->tagManager->createTag(ltrim($tag['name'], '@'), ltrim($tag['value'])); - } - - $this->isReflected = true; - } - - public function toString() - { - $str = "DocBlock [ /* DocBlock */ ] {" . PHP_EOL . PHP_EOL; - $str .= " - Tags [" . count($this->tags) . "] {" . PHP_EOL; - - foreach ($this->tags as $tag) { - $str .= " " . $tag; - } - - $str .= " }" . PHP_EOL; - $str .= "}" . PHP_EOL; - - return $str; - } - - /** - * Serialize to string - * - * Required by the Reflector interface - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } -} diff --git a/library/Zend/Code/Reflection/Exception/BadMethodCallException.php b/library/Zend/Code/Reflection/Exception/BadMethodCallException.php deleted file mode 100755 index 6eeb226fb..000000000 --- a/library/Zend/Code/Reflection/Exception/BadMethodCallException.php +++ /dev/null @@ -1,17 +0,0 @@ -filePath = $fileRealPath; - $this->reflect(); - } - - /** - * Required by the Reflector interface. - * - * @todo What should this do? - * @return null - */ - public static function export() - { - return null; - } - - /** - * Return the file name of the reflected file - * - * @return string - */ - public function getFileName() - { - // @todo get file name from path - return $this->filePath; - } - - /** - * Get the start line - Always 1, staying consistent with the Reflection API - * - * @return int - */ - public function getStartLine() - { - return $this->startLine; - } - - /** - * Get the end line / number of lines - * - * @return int - */ - public function getEndLine() - { - return $this->endLine; - } - - /** - * @return string - */ - public function getDocComment() - { - return $this->docComment; - } - - /** - * @return DocBlockReflection - */ - public function getDocBlock() - { - if (!($docComment = $this->getDocComment())) { - return false; - } - - $instance = new DocBlockReflection($docComment); - - return $instance; - } - - /** - * @return array - */ - public function getNamespaces() - { - return $this->namespaces; - } - - /** - * @return string - */ - public function getNamespace() - { - if (count($this->namespaces) == 0) { - return null; - } - - return $this->namespaces[0]; - } - - /** - * @return array - */ - public function getUses() - { - return $this->uses; - } - - /** - * Return the reflection classes of the classes found inside this file - * - * @return ClassReflection[] - */ - public function getClasses() - { - $classes = array(); - foreach ($this->classes as $class) { - $classes[] = new ClassReflection($class); - } - - return $classes; - } - - /** - * Return the reflection functions of the functions found inside this file - * - * @return FunctionReflection[] - */ - public function getFunctions() - { - $functions = array(); - foreach ($this->functions as $function) { - $functions[] = new FunctionReflection($function); - } - - return $functions; - } - - /** - * Retrieve the reflection class of a given class found in this file - * - * @param null|string $name - * @return ClassReflection - * @throws Exception\InvalidArgumentException for invalid class name or invalid reflection class - */ - public function getClass($name = null) - { - if (null === $name) { - reset($this->classes); - $selected = current($this->classes); - - return new ClassReflection($selected); - } - - if (in_array($name, $this->classes)) { - return new ClassReflection($name); - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Class by name %s not found.', - $name - )); - } - - /** - * Return the full contents of file - * - * @return string - */ - public function getContents() - { - return file_get_contents($this->filePath); - } - - public function toString() - { - return ''; // @todo - } - - /** - * Serialize to string - * - * Required by the Reflector interface - * - * @todo What should this serialization look like? - * @return string - */ - public function __toString() - { - return ''; - } - - /** - * This method does the work of "reflecting" the file - * - * Uses Zend\Code\Scanner\FileScanner to gather file information - * - * @return void - */ - protected function reflect() - { - $scanner = new CachingFileScanner($this->filePath); - $this->docComment = $scanner->getDocComment(); - $this->requiredFiles = $scanner->getIncludes(); - $this->classes = $scanner->getClassNames(); - $this->namespaces = $scanner->getNamespaces(); - $this->uses = $scanner->getUses(); - } - - /** - * Validate / check a file level DocBlock - * - * @param array $tokens Array of tokenizer tokens - * @return void - */ - protected function checkFileDocBlock($tokens) - { - foreach ($tokens as $token) { - $type = $token[0]; - $value = $token[1]; - $lineNum = $token[2]; - if (($type == T_OPEN_TAG) || ($type == T_WHITESPACE)) { - continue; - } elseif ($type == T_DOC_COMMENT) { - $this->docComment = $value; - $this->startLine = $lineNum + substr_count($value, "\n") + 1; - - return; - } else { - // Only whitespace is allowed before file DocBlocks - return; - } - } - } -} diff --git a/library/Zend/Code/Reflection/FunctionReflection.php b/library/Zend/Code/Reflection/FunctionReflection.php deleted file mode 100755 index c752f1eca..000000000 --- a/library/Zend/Code/Reflection/FunctionReflection.php +++ /dev/null @@ -1,266 +0,0 @@ -getDocComment())) { - throw new Exception\InvalidArgumentException(sprintf( - '%s does not have a DocBlock', - $this->getName() - )); - } - - $instance = new DocBlockReflection($comment); - - return $instance; - } - - /** - * Get start line (position) of function - * - * @param bool $includeDocComment - * @return int - */ - public function getStartLine($includeDocComment = false) - { - if ($includeDocComment) { - if ($this->getDocComment() != '') { - return $this->getDocBlock()->getStartLine(); - } - } - - return parent::getStartLine(); - } - - /** - * Get contents of function - * - * @param bool $includeDocBlock - * @return string - */ - public function getContents($includeDocBlock = true) - { - $fileName = $this->getFileName(); - if (false === $fileName) { - return ''; - } - - $startLine = $this->getStartLine(); - $endLine = $this->getEndLine(); - - // eval'd protect - if (preg_match('#\((\d+)\) : eval\(\)\'d code$#', $fileName, $matches)) { - $fileName = preg_replace('#\(\d+\) : eval\(\)\'d code$#', '', $fileName); - $startLine = $endLine = $matches[1]; - } - - $lines = array_slice( - file($fileName, FILE_IGNORE_NEW_LINES), - $startLine - 1, - ($endLine - ($startLine - 1)), - true - ); - - $functionLine = implode("\n", $lines); - - $content = ''; - if ($this->isClosure()) { - preg_match('#function\s*\([^\)]*\)\s*(use\s*\([^\)]+\))?\s*\{(.*\;)?\s*\}#s', $functionLine, $matches); - if (isset($matches[0])) { - $content = $matches[0]; - } - } else { - $name = substr($this->getName(), strrpos($this->getName(), '\\')+1); - preg_match('#function\s+' . preg_quote($name) . '\s*\([^\)]*\)\s*{([^{}]+({[^}]+})*[^}]+)?}#', $functionLine, $matches); - if (isset($matches[0])) { - $content = $matches[0]; - } - } - - $docComment = $this->getDocComment(); - - return $includeDocBlock && $docComment ? $docComment . "\n" . $content : $content; - } - - /** - * Get method prototype - * - * @return array - */ - public function getPrototype($format = FunctionReflection::PROTOTYPE_AS_ARRAY) - { - $returnType = 'mixed'; - $docBlock = $this->getDocBlock(); - if ($docBlock) { - $return = $docBlock->getTag('return'); - $returnTypes = $return->getTypes(); - $returnType = count($returnTypes) > 1 ? implode('|', $returnTypes) : $returnTypes[0]; - } - - $prototype = array( - 'namespace' => $this->getNamespaceName(), - 'name' => substr($this->getName(), strlen($this->getNamespaceName()) + 1), - 'return' => $returnType, - 'arguments' => array(), - ); - - $parameters = $this->getParameters(); - foreach ($parameters as $parameter) { - $prototype['arguments'][$parameter->getName()] = array( - 'type' => $parameter->getType(), - 'required' => !$parameter->isOptional(), - 'by_ref' => $parameter->isPassedByReference(), - 'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null, - ); - } - - if ($format == FunctionReflection::PROTOTYPE_AS_STRING) { - $line = $prototype['return'] . ' ' . $prototype['name'] . '('; - $args = array(); - foreach ($prototype['arguments'] as $name => $argument) { - $argsLine = ($argument['type'] ? $argument['type'] . ' ' : '') . ($argument['by_ref'] ? '&' : '') . '$' . $name; - if (!$argument['required']) { - $argsLine .= ' = ' . var_export($argument['default'], true); - } - $args[] = $argsLine; - } - $line .= implode(', ', $args); - $line .= ')'; - - return $line; - } - - return $prototype; - } - - /** - * Get function parameters - * - * @return ParameterReflection[] - */ - public function getParameters() - { - $phpReflections = parent::getParameters(); - $zendReflections = array(); - while ($phpReflections && ($phpReflection = array_shift($phpReflections))) { - $instance = new ParameterReflection($this->getName(), $phpReflection->getName()); - $zendReflections[] = $instance; - unset($phpReflection); - } - unset($phpReflections); - - return $zendReflections; - } - - /** - * Get return type tag - * - * @throws Exception\InvalidArgumentException - * @return DocBlockReflection - */ - public function getReturn() - { - $docBlock = $this->getDocBlock(); - if (!$docBlock->hasTag('return')) { - throw new Exception\InvalidArgumentException( - 'Function does not specify an @return annotation tag; cannot determine return type' - ); - } - - $tag = $docBlock->getTag('return'); - - return new DocBlockReflection('@return ' . $tag->getDescription()); - } - - /** - * Get method body - * - * @return string|bool - */ - public function getBody() - { - $fileName = $this->getFileName(); - if (false === $fileName) { - throw new Exception\InvalidArgumentException( - 'Cannot determine internals functions body' - ); - } - - $startLine = $this->getStartLine(); - $endLine = $this->getEndLine(); - - // eval'd protect - if (preg_match('#\((\d+)\) : eval\(\)\'d code$#', $fileName, $matches)) { - $fileName = preg_replace('#\(\d+\) : eval\(\)\'d code$#', '', $fileName); - $startLine = $endLine = $matches[1]; - } - - $lines = array_slice( - file($fileName, FILE_IGNORE_NEW_LINES), - $startLine - 1, - ($endLine - ($startLine - 1)), - true - ); - - $functionLine = implode("\n", $lines); - - $body = false; - if ($this->isClosure()) { - preg_match('#function\s*\([^\)]*\)\s*(use\s*\([^\)]+\))?\s*\{(.*\;)\s*\}#s', $functionLine, $matches); - if (isset($matches[2])) { - $body = $matches[2]; - } - } else { - $name = substr($this->getName(), strrpos($this->getName(), '\\')+1); - preg_match('#function\s+' . $name . '\s*\([^\)]*\)\s*{([^{}]+({[^}]+})*[^}]+)}#', $functionLine, $matches); - if (isset($matches[1])) { - $body = $matches[1]; - } - } - - return $body; - } - - public function toString() - { - return $this->__toString(); - } - - /** - * Required due to bug in php - * - * @return string - */ - public function __toString() - { - return parent::__toString(); - } -} diff --git a/library/Zend/Code/Reflection/MethodReflection.php b/library/Zend/Code/Reflection/MethodReflection.php deleted file mode 100755 index 10a9b8ab4..000000000 --- a/library/Zend/Code/Reflection/MethodReflection.php +++ /dev/null @@ -1,487 +0,0 @@ -getDocComment()) { - return false; - } - - $instance = new DocBlockReflection($this); - - return $instance; - } - - /** - * @param AnnotationManager $annotationManager - * @return AnnotationScanner - */ - public function getAnnotations(AnnotationManager $annotationManager) - { - if (($docComment = $this->getDocComment()) == '') { - return false; - } - - if ($this->annotations) { - return $this->annotations; - } - - $cachingFileScanner = $this->createFileScanner($this->getFileName()); - $nameInformation = $cachingFileScanner->getClassNameInformation($this->getDeclaringClass()->getName()); - - if (!$nameInformation) { - return false; - } - - $this->annotations = new AnnotationScanner($annotationManager, $docComment, $nameInformation); - - return $this->annotations; - } - - /** - * Get start line (position) of method - * - * @param bool $includeDocComment - * @return int - */ - public function getStartLine($includeDocComment = false) - { - if ($includeDocComment) { - if ($this->getDocComment() != '') { - return $this->getDocBlock()->getStartLine(); - } - } - - return parent::getStartLine(); - } - - /** - * Get reflection of declaring class - * - * @return ClassReflection - */ - public function getDeclaringClass() - { - $phpReflection = parent::getDeclaringClass(); - $zendReflection = new ClassReflection($phpReflection->getName()); - unset($phpReflection); - - return $zendReflection; - } - - /** - * Get method prototype - * - * @return array - */ - public function getPrototype($format = MethodReflection::PROTOTYPE_AS_ARRAY) - { - $returnType = 'mixed'; - $docBlock = $this->getDocBlock(); - if ($docBlock) { - $return = $docBlock->getTag('return'); - $returnTypes = $return->getTypes(); - $returnType = count($returnTypes) > 1 ? implode('|', $returnTypes) : $returnTypes[0]; - } - - $declaringClass = $this->getDeclaringClass(); - $prototype = array( - 'namespace' => $declaringClass->getNamespaceName(), - 'class' => substr($declaringClass->getName(), strlen($declaringClass->getNamespaceName()) + 1), - 'name' => $this->getName(), - 'visibility' => ($this->isPublic() ? 'public' : ($this->isPrivate() ? 'private' : 'protected')), - 'return' => $returnType, - 'arguments' => array(), - ); - - $parameters = $this->getParameters(); - foreach ($parameters as $parameter) { - $prototype['arguments'][$parameter->getName()] = array( - 'type' => $parameter->getType(), - 'required' => !$parameter->isOptional(), - 'by_ref' => $parameter->isPassedByReference(), - 'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null, - ); - } - - if ($format == MethodReflection::PROTOTYPE_AS_STRING) { - $line = $prototype['visibility'] . ' ' . $prototype['return'] . ' ' . $prototype['name'] . '('; - $args = array(); - foreach ($prototype['arguments'] as $name => $argument) { - $argsLine = ($argument['type'] ? $argument['type'] . ' ' : '') . ($argument['by_ref'] ? '&' : '') . '$' . $name; - if (!$argument['required']) { - $argsLine .= ' = ' . var_export($argument['default'], true); - } - $args[] = $argsLine; - } - $line .= implode(', ', $args); - $line .= ')'; - - return $line; - } - - return $prototype; - } - - /** - * Get all method parameter reflection objects - * - * @return ParameterReflection[] - */ - public function getParameters() - { - $phpReflections = parent::getParameters(); - $zendReflections = array(); - while ($phpReflections && ($phpReflection = array_shift($phpReflections))) { - $instance = new ParameterReflection( - array($this->getDeclaringClass()->getName(), $this->getName()), - $phpReflection->getName() - ); - $zendReflections[] = $instance; - unset($phpReflection); - } - unset($phpReflections); - - return $zendReflections; - } - - /** - * Get method contents - * - * @param bool $includeDocBlock - * @return string|bool - */ - public function getContents($includeDocBlock = true) - { - $docComment = $this->getDocComment(); - $content = ($includeDocBlock && !empty($docComment)) ? $docComment . "\n" : ''; - $content .= $this->extractMethodContents(); - - return $content; - } - - /** - * Get method body - * - * @return string|bool - */ - public function getBody() - { - return $this->extractMethodContents(true); - } - - /** - * Tokenize method string and return concatenated body - * - * @param bool $bodyOnly - * @return string - */ - protected function extractMethodContents($bodyOnly=false) - { - $fileName = $this->getDeclaringClass()->getFileName(); - - if ((class_exists($this->class) && false === $fileName) || ! file_exists($fileName)) { - return ''; - } - - $lines = array_slice( - file($fileName, FILE_IGNORE_NEW_LINES), - $this->getStartLine() - 1, - ($this->getEndLine() - ($this->getStartLine() - 1)), - true - ); - - $functionLine = implode("\n", $lines); - $tokens = token_get_all(" $token) { - $tokenType = (is_array($token)) ? token_name($token[0]) : $token; - $tokenValue = (is_array($token)) ? $token[1] : $token; - - switch ($tokenType) { - case "T_FINAL": - case "T_ABSTRACT": - case "T_PUBLIC": - case "T_PROTECTED": - case "T_PRIVATE": - case "T_STATIC": - case "T_FUNCTION": - // check to see if we have a valid function - // then check if we are inside function and have a closure - if ($this->isValidFunction($tokens, $key, $this->getName())) { - if ($bodyOnly === false) { - //if first instance of tokenType grab prefixed whitespace - //and append to body - if ($capture === false) { - $body .= $this->extractPrefixedWhitespace($tokens, $key); - } - $body .= $tokenValue; - } - - $capture = true; - } else { - //closure test - if ($firstBrace && $tokenType == "T_FUNCTION") { - $body .= $tokenValue; - continue; - } - $capture = false; - continue; - } - break; - - case "{": - if ($capture === false) { - continue; - } - - if ($firstBrace === false) { - $firstBrace = true; - if ($bodyOnly === true) { - continue; - } - } - - $body .= $tokenValue; - break; - - case "}": - if ($capture === false) { - continue; - } - - //check to see if this is the last brace - if ($this->isEndingBrace($tokens, $key)) { - //capture the end brace if not bodyOnly - if ($bodyOnly === false) { - $body .= $tokenValue; - } - - break 2; - } - - $body .= $tokenValue; - break; - - default: - if ($capture === false) { - continue; - } - - // if returning body only wait for first brace before capturing - if ($bodyOnly === true && $firstBrace !== true) { - continue; - } - - $body .= $tokenValue; - break; - } - } - - //remove ending whitespace and return - return rtrim($body); - } - - /** - * Take current position and find any whitespace - * - * @param $haystack - * @param $position - * @return string - */ - protected function extractPrefixedWhitespace($haystack, $position) - { - $content = ''; - $count = count($haystack); - if ($position+1 == $count) { - return $content; - } - - for ($i = $position-1;$i >= 0;$i--) { - $tokenType = (is_array($haystack[$i])) ? token_name($haystack[$i][0]) : $haystack[$i]; - $tokenValue = (is_array($haystack[$i])) ? $haystack[$i][1] : $haystack[$i]; - - //search only for whitespace - if ($tokenType == "T_WHITESPACE") { - $content .= $tokenValue; - } else { - break; - } - } - - return $content; - } - - /** - * Test for ending brace - * - * @param $haystack - * @param $position - * @return bool - */ - protected function isEndingBrace($haystack, $position) - { - $count = count($haystack); - - //advance one position - $position = $position+1; - - if ($position == $count) { - return true; - } - - for ($i = $position;$i < $count; $i++) { - $tokenType = (is_array($haystack[$i])) ? token_name($haystack[$i][0]) : $haystack[$i]; - switch ($tokenType) { - case "T_FINAL": - case "T_ABSTRACT": - case "T_PUBLIC": - case "T_PROTECTED": - case "T_PRIVATE": - case "T_STATIC": - return true; - - case "T_FUNCTION": - // If a function is encountered and that function is not a closure - // then return true. otherwise the function is a closure, return false - if ($this->isValidFunction($haystack, $i)) { - return true; - } - return false; - - case "}": - case ";"; - case "T_BREAK": - case "T_CATCH": - case "T_DO": - case "T_ECHO": - case "T_ELSE": - case "T_ELSEIF": - case "T_EVAL": - case "T_EXIT": - case "T_FINALLY": - case "T_FOR": - case "T_FOREACH": - case "T_GOTO": - case "T_IF": - case "T_INCLUDE": - case "T_INCLUDE_ONCE": - case "T_PRINT": - case "T_STRING": - case "T_STRING_VARNAME": - case "T_THROW": - case "T_USE": - case "T_VARIABLE": - case "T_WHILE": - case "T_YIELD": - - return false; - } - } - } - - /** - * Test to see if current position is valid function or - * closure. Returns true if it's a function and NOT a closure - * - * @param $haystack - * @param $position - * @return bool - */ - protected function isValidFunction($haystack, $position, $functionName = null) - { - $isValid = false; - $count = count($haystack); - for ($i = $position+1;$i < $count; $i++) { - $tokenType = (is_array($haystack[$i])) ? token_name($haystack[$i][0]) : $haystack[$i]; - $tokenValue = (is_array($haystack[$i])) ? $haystack[$i][1] : $haystack[$i]; - - //check for occurance of ( or - if ($tokenType == "T_STRING") { - //check to see if function name is passed, if so validate against that - if ($functionName !== null && $tokenValue != $functionName) { - $isValid = false; - break; - } - - $isValid = true; - break; - } elseif ($tokenValue == "(") { - break; - } - } - - return $isValid; - } - - public function toString() - { - return parent::__toString(); - } - - public function __toString() - { - return parent::__toString(); - } - - /** - * Creates a new FileScanner instance. - * - * By having this as a seperate method it allows the method to be overridden - * if a different FileScanner is needed. - * - * @param string $filename - * - * @return CachingFileScanner - */ - protected function createFileScanner($filename) - { - return new CachingFileScanner($filename); - } -} diff --git a/library/Zend/Code/Reflection/ParameterReflection.php b/library/Zend/Code/Reflection/ParameterReflection.php deleted file mode 100755 index e6239abce..000000000 --- a/library/Zend/Code/Reflection/ParameterReflection.php +++ /dev/null @@ -1,110 +0,0 @@ -getName()); - unset($phpReflection); - - return $zendReflection; - } - - /** - * Get class reflection object - * - * @return ClassReflection - */ - public function getClass() - { - $phpReflection = parent::getClass(); - if ($phpReflection == null) { - return null; - } - - $zendReflection = new ClassReflection($phpReflection->getName()); - unset($phpReflection); - - return $zendReflection; - } - - /** - * Get declaring function reflection object - * - * @return FunctionReflection|MethodReflection - */ - public function getDeclaringFunction() - { - $phpReflection = parent::getDeclaringFunction(); - if ($phpReflection instanceof \ReflectionMethod) { - $zendReflection = new MethodReflection($this->getDeclaringClass()->getName(), $phpReflection->getName()); - } else { - $zendReflection = new FunctionReflection($phpReflection->getName()); - } - unset($phpReflection); - - return $zendReflection; - } - - /** - * Get parameter type - * - * @return string - */ - public function getType() - { - if ($this->isArray()) { - return 'array'; - } elseif (method_exists($this, 'isCallable') && $this->isCallable()) { - return 'callable'; - } - - if (($class = $this->getClass()) instanceof \ReflectionClass) { - return $class->getName(); - } - - $docBlock = $this->getDeclaringFunction()->getDocBlock(); - if (!$docBlock instanceof DocBlockReflection) { - return null; - } - - $params = $docBlock->getTags('param'); - if (isset($params[$this->getPosition()])) { - return $params[$this->getPosition()]->getType(); - } - - return null; - } - - public function toString() - { - return parent::__toString(); - } - - public function __toString() - { - return parent::__toString(); - } -} diff --git a/library/Zend/Code/Reflection/PropertyReflection.php b/library/Zend/Code/Reflection/PropertyReflection.php deleted file mode 100755 index c9b5a8d25..000000000 --- a/library/Zend/Code/Reflection/PropertyReflection.php +++ /dev/null @@ -1,111 +0,0 @@ -getName()); - unset($phpReflection); - - return $zendReflection; - } - - /** - * Get DocBlock comment - * - * @return string|false False if no DocBlock defined - */ - public function getDocComment() - { - return parent::getDocComment(); - } - - /** - * @return false|DocBlockReflection - */ - public function getDocBlock() - { - if (!($docComment = $this->getDocComment())) { - return false; - } - - $docBlockReflection = new DocBlockReflection($docComment); - - return $docBlockReflection; - } - - /** - * @param AnnotationManager $annotationManager - * @return AnnotationScanner - */ - public function getAnnotations(AnnotationManager $annotationManager) - { - if (null !== $this->annotations) { - return $this->annotations; - } - - if (($docComment = $this->getDocComment()) == '') { - return false; - } - - $class = $this->getDeclaringClass(); - $cachingFileScanner = $this->createFileScanner($class->getFileName()); - $nameInformation = $cachingFileScanner->getClassNameInformation($class->getName()); - - if (!$nameInformation) { - return false; - } - - $this->annotations = new AnnotationScanner($annotationManager, $docComment, $nameInformation); - - return $this->annotations; - } - - public function toString() - { - return $this->__toString(); - } - - /** - * Creates a new FileScanner instance. - * - * By having this as a seperate method it allows the method to be overridden - * if a different FileScanner is needed. - * - * @param string $filename - * - * @return CachingFileScanner - */ - protected function createFileScanner($filename) - { - return new CachingFileScanner($filename); - } -} diff --git a/library/Zend/Code/Reflection/ReflectionInterface.php b/library/Zend/Code/Reflection/ReflectionInterface.php deleted file mode 100755 index ed5ffd46c..000000000 --- a/library/Zend/Code/Reflection/ReflectionInterface.php +++ /dev/null @@ -1,20 +0,0 @@ -directories as $scanner) { - $classes += $scanner->getClasses(); - } - if ($returnScannerClass) { - foreach ($classes as $index => $class) { - $classes[$index] = $this->getClass($class, $returnScannerClass, $returnDerivedScannerClass); - } - } - - return $classes; - } - - /** - * @param string $class - * @return bool - */ - public function hasClass($class) - { - foreach ($this->directories as $scanner) { - if ($scanner->hasClass($class)) { - break; - } else { - unset($scanner); - } - } - - return (isset($scanner)); - } - - /** - * @param string $class - * @param bool $returnScannerClass - * @param bool $returnDerivedScannerClass - * @return ClassScanner|DerivedClassScanner - * @throws Exception\RuntimeException - */ - public function getClass($class, $returnScannerClass = true, $returnDerivedScannerClass = false) - { - foreach ($this->directories as $scanner) { - if ($scanner->hasClass($class)) { - break; - } else { - unset($scanner); - } - } - - if (!isset($scanner)) { - throw new Exception\RuntimeException('Class by that name was not found.'); - } - - $classScanner = $scanner->getClass($class); - - return new DerivedClassScanner($classScanner, $this); - } - - /** - * @param bool $returnScannerClass - */ - public function getFunctions($returnScannerClass = false) - { - $this->scan(); - - if (!$returnScannerClass) { - $functions = array(); - foreach ($this->infos as $info) { - if ($info['type'] == 'function') { - $functions[] = $info['name']; - } - } - - return $functions; - } - $scannerClass = new FunctionScanner(); - // @todo - } -} diff --git a/library/Zend/Code/Scanner/AnnotationScanner.php b/library/Zend/Code/Scanner/AnnotationScanner.php deleted file mode 100755 index 76e8144c0..000000000 --- a/library/Zend/Code/Scanner/AnnotationScanner.php +++ /dev/null @@ -1,338 +0,0 @@ -annotationManager = $annotationManager; - $this->docComment = $docComment; - $this->nameInformation = $nameInformation; - $this->scan($this->tokenize()); - } - - /** - * @param NameInformation $nameInformation - */ - public function setNameInformation(NameInformation $nameInformation) - { - $this->nameInformation = $nameInformation; - } - - /** - * @param array $tokens - */ - protected function scan(array $tokens) - { - $annotations = array(); - $annotationIndex = -1; - $contentEnd = false; - - reset($tokens); - - SCANNER_TOP: - $token = current($tokens); - - switch ($token[0]) { - - case 'ANNOTATION_CLASS': - - $contentEnd = false; - $annotationIndex++; - $class = substr($token[1], 1); - $class = $this->nameInformation->resolveName($class); - $annotations[$annotationIndex] = array($class, null); - goto SCANNER_CONTINUE; - // goto no break needed - - case 'ANNOTATION_CONTENT_START': - - $annotations[$annotationIndex][1] = ''; - //fall-through - - case 'ANNOTATION_CONTENT_END': - case 'ANNOTATION_CONTENT': - case 'ANNOTATION_WHITESPACE': - case 'ANNOTATION_NEWLINE': - - if (!$contentEnd && isset($annotations[$annotationIndex]) && is_string($annotations[$annotationIndex][1])) { - $annotations[$annotationIndex][1] .= $token[1]; - } - - if ($token[0] === 'ANNOTATION_CONTENT_END') { - $contentEnd = true; - } - - goto SCANNER_CONTINUE; - } - - SCANNER_CONTINUE: - if (next($tokens) === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_END: - - foreach ($annotations as $annotation) { - $annotation[] = '@' . $annotation[0] . $annotation[1]; - $annotationObject = $this->annotationManager->createAnnotation($annotation); - if ($annotationObject) { - $this->append($annotationObject); - } - } - } - - /** - * @return array - */ - protected function tokenize() - { - static $CONTEXT_DOCBLOCK = 0x01; - static $CONTEXT_ASTERISK = 0x02; - static $CONTEXT_CLASS = 0x04; - static $CONTEXT_CONTENT = 0x08; - - $context = 0x00; - $stream = $this->docComment; - $streamIndex = null; - $tokens = array(); - $tokenIndex = null; - $currentChar = null; - $currentWord = null; - $currentLine = null; - - $annotationParentCount = 0; - - $MACRO_STREAM_ADVANCE_CHAR = function ($positionsForward = 1) use (&$stream, &$streamIndex, &$currentChar, &$currentWord, &$currentLine) { - $positionsForward = ($positionsForward > 0) ? $positionsForward : 1; - $streamIndex = ($streamIndex === null) ? 0 : $streamIndex + $positionsForward; - if (!isset($stream[$streamIndex])) { - $currentChar = false; - - return false; - } - $currentChar = $stream[$streamIndex]; - $matches = array(); - $currentLine = (preg_match('#(.*)\n#', $stream, $matches, null, $streamIndex) === 1) ? $matches[1] : substr($stream, $streamIndex); - if ($currentChar === ' ') { - $currentWord = (preg_match('#( +)#', $currentLine, $matches) === 1) ? $matches[1] : $currentLine; - } else { - $currentWord = (($matches = strpos($currentLine, ' ')) !== false) ? substr($currentLine, 0, $matches) : $currentLine; - } - - return $currentChar; - }; - $MACRO_STREAM_ADVANCE_WORD = function () use (&$currentWord, &$MACRO_STREAM_ADVANCE_CHAR) { - return $MACRO_STREAM_ADVANCE_CHAR(strlen($currentWord)); - }; - $MACRO_STREAM_ADVANCE_LINE = function () use (&$currentLine, &$MACRO_STREAM_ADVANCE_CHAR) { - return $MACRO_STREAM_ADVANCE_CHAR(strlen($currentLine)); - }; - $MACRO_TOKEN_ADVANCE = function () use (&$tokenIndex, &$tokens) { - $tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1; - $tokens[$tokenIndex] = array('ANNOTATION_UNKNOWN', ''); - }; - $MACRO_TOKEN_SET_TYPE = function ($type) use (&$tokenIndex, &$tokens) { - $tokens[$tokenIndex][0] = $type; - }; - $MACRO_TOKEN_APPEND_CHAR = function () use (&$currentChar, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= $currentChar; - }; - $MACRO_TOKEN_APPEND_WORD = function () use (&$currentWord, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= $currentWord; - }; - $MACRO_TOKEN_APPEND_LINE = function () use (&$currentLine, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= $currentLine; - }; - $MACRO_HAS_CONTEXT = function ($which) use (&$context) { - return (($context & $which) === $which); - }; - - $MACRO_STREAM_ADVANCE_CHAR(); - $MACRO_TOKEN_ADVANCE(); - - TOKENIZER_TOP: - - if ($context === 0x00 && $currentChar === '/' && $currentWord === '/**') { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_COMMENTSTART'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - $context |= $CONTEXT_DOCBLOCK; - $context |= $CONTEXT_ASTERISK; - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($MACRO_HAS_CONTEXT($CONTEXT_CLASS)) { - if (in_array($currentChar, array(' ', '(', "\n"))) { - $context &= ~$CONTEXT_CLASS; - $MACRO_TOKEN_ADVANCE(); - } else { - $MACRO_TOKEN_APPEND_CHAR(); - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - } - - if ($currentChar === "\n") { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_NEWLINE'); - $MACRO_TOKEN_APPEND_CHAR(); - $MACRO_TOKEN_ADVANCE(); - $context &= ~$CONTEXT_ASTERISK; - $context &= ~$CONTEXT_CLASS; - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === ' ') { - $MACRO_TOKEN_SET_TYPE(($MACRO_HAS_CONTEXT($CONTEXT_ASTERISK)) ? 'ANNOTATION_WHITESPACE' : 'ANNOTATION_WHITESPACE_INDENT'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($MACRO_HAS_CONTEXT($CONTEXT_CONTENT) && $MACRO_HAS_CONTEXT($CONTEXT_ASTERISK)) { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_CONTENT'); - $annotationParentCount += substr_count($currentWord, '('); - $annotationParentCount -= substr_count($currentWord, ')'); - - if ($annotationParentCount === 0) { - $context &= ~$CONTEXT_CONTENT; - $MACRO_TOKEN_SET_TYPE('ANNOTATION_CONTENT_END'); - } - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === '(' && $tokens[$tokenIndex - 1][0] === 'ANNOTATION_CLASS') { - $context |= $CONTEXT_CONTENT; - $annotationParentCount = 1; - $MACRO_TOKEN_SET_TYPE('ANNOTATION_CONTENT_START'); - $MACRO_TOKEN_APPEND_CHAR(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($MACRO_HAS_CONTEXT($CONTEXT_DOCBLOCK) && $currentWord === '*/') { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_COMMENTEND'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - $context &= ~$CONTEXT_DOCBLOCK; - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === '*') { - if ($MACRO_HAS_CONTEXT($CONTEXT_DOCBLOCK) && ($MACRO_HAS_CONTEXT($CONTEXT_ASTERISK))) { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_IGNORE'); - } else { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_ASTERISK'); - $context |= $CONTEXT_ASTERISK; - } - $MACRO_TOKEN_APPEND_CHAR(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === '@') { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_CLASS'); - $context |= $CONTEXT_CLASS; - $MACRO_TOKEN_APPEND_CHAR(); - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - TOKENIZER_CONTINUE: - - if ($context && $CONTEXT_CONTENT) { - $MACRO_TOKEN_APPEND_CHAR(); - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - } else { - $MACRO_TOKEN_SET_TYPE('ANNOTATION_IGNORE'); - $MACRO_TOKEN_APPEND_LINE(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_LINE() === false) { - goto TOKENIZER_END; - } - } - goto TOKENIZER_TOP; - - TOKENIZER_END: - - array_pop($tokens); - - return $tokens; - } -} diff --git a/library/Zend/Code/Scanner/CachingFileScanner.php b/library/Zend/Code/Scanner/CachingFileScanner.php deleted file mode 100755 index cb7286704..000000000 --- a/library/Zend/Code/Scanner/CachingFileScanner.php +++ /dev/null @@ -1,160 +0,0 @@ -fileScanner = static::$cache[$cacheId]; - } else { - $this->fileScanner = new FileScanner($file, $annotationManager); - static::$cache[$cacheId] = $this->fileScanner; - } - } - - /** - * @return void - */ - public static function clearCache() - { - static::$cache = array(); - } - - /** - * @return AnnotationManager - */ - public function getAnnotationManager() - { - return $this->fileScanner->getAnnotationManager(); - } - - /** - * @return array|null|string - */ - public function getFile() - { - return $this->fileScanner->getFile(); - } - - /** - * @return null|string - */ - public function getDocComment() - { - return $this->fileScanner->getDocComment(); - } - - /** - * @return array - */ - public function getNamespaces() - { - return $this->fileScanner->getNamespaces(); - } - - /** - * @param null|string $namespace - * @return array|null - */ - public function getUses($namespace = null) - { - return $this->fileScanner->getUses($namespace); - } - - /** - * @return array - */ - public function getIncludes() - { - return $this->fileScanner->getIncludes(); - } - - /** - * @return array - */ - public function getClassNames() - { - return $this->fileScanner->getClassNames(); - } - - /** - * @return array - */ - public function getClasses() - { - return $this->fileScanner->getClasses(); - } - - /** - * @param int|string $className - * @return ClassScanner - */ - public function getClass($className) - { - return $this->fileScanner->getClass($className); - } - - /** - * @param string $className - * @return bool|null|NameInformation - */ - public function getClassNameInformation($className) - { - return $this->fileScanner->getClassNameInformation($className); - } - - /** - * @return array - */ - public function getFunctionNames() - { - return $this->fileScanner->getFunctionNames(); - } - - /** - * @return array - */ - public function getFunctions() - { - return $this->fileScanner->getFunctions(); - } -} diff --git a/library/Zend/Code/Scanner/ClassScanner.php b/library/Zend/Code/Scanner/ClassScanner.php deleted file mode 100755 index 2efc5539c..000000000 --- a/library/Zend/Code/Scanner/ClassScanner.php +++ /dev/null @@ -1,972 +0,0 @@ -tokens = $classTokens; - $this->nameInformation = $nameInformation; - } - - /** - * Get annotations - * - * @param Annotation\AnnotationManager $annotationManager - * @return Annotation\AnnotationCollection - */ - public function getAnnotations(Annotation\AnnotationManager $annotationManager) - { - if (($docComment = $this->getDocComment()) == '') { - return false; - } - - return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation); - } - - /** - * Return documentation comment - * - * @return null|string - */ - public function getDocComment() - { - $this->scan(); - - return $this->docComment; - } - - /** - * Return documentation block - * - * @return false|DocBlockScanner - */ - public function getDocBlock() - { - if (!$docComment = $this->getDocComment()) { - return false; - } - - return new DocBlockScanner($docComment); - } - - /** - * Return a name of class - * - * @return null|string - */ - public function getName() - { - $this->scan(); - return $this->name; - } - - /** - * Return short name of class - * - * @return null|string - */ - public function getShortName() - { - $this->scan(); - return $this->shortName; - } - - /** - * Return number of first line - * - * @return int|null - */ - public function getLineStart() - { - $this->scan(); - return $this->lineStart; - } - - /** - * Return number of last line - * - * @return int|null - */ - public function getLineEnd() - { - $this->scan(); - return $this->lineEnd; - } - - /** - * Verify if class is final - * - * @return bool - */ - public function isFinal() - { - $this->scan(); - return $this->isFinal; - } - - /** - * Verify if class is instantiable - * - * @return bool - */ - public function isInstantiable() - { - $this->scan(); - return (!$this->isAbstract && !$this->isInterface); - } - - /** - * Verify if class is an abstract class - * - * @return bool - */ - public function isAbstract() - { - $this->scan(); - return $this->isAbstract; - } - - /** - * Verify if class is an interface - * - * @return bool - */ - public function isInterface() - { - $this->scan(); - return $this->isInterface; - } - - /** - * Verify if class has parent - * - * @return bool - */ - public function hasParentClass() - { - $this->scan(); - return ($this->parentClass != null); - } - - /** - * Return a name of parent class - * - * @return null|string - */ - public function getParentClass() - { - $this->scan(); - return $this->parentClass; - } - - /** - * Return a list of interface names - * - * @return array - */ - public function getInterfaces() - { - $this->scan(); - return $this->interfaces; - } - - /** - * Return a list of constant names - * - * @return array - */ - public function getConstantNames() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'constant') { - continue; - } - - $return[] = $info['name']; - } - - return $return; - } - - /** - * Return a list of constants - * - * @param bool $namesOnly Set false to return instances of ConstantScanner - * @return array|ConstantScanner[] - */ - public function getConstants($namesOnly = true) - { - if (true === $namesOnly) { - trigger_error('Use method getConstantNames() instead', E_USER_DEPRECATED); - return $this->getConstantNames(); - } - - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'constant') { - continue; - } - - $return[] = $this->getConstant($info['name']); - } - - return $return; - } - - /** - * Return a single constant by given name or index of info - * - * @param string|int $constantNameOrInfoIndex - * @throws Exception\InvalidArgumentException - * @return bool|ConstantScanner - */ - public function getConstant($constantNameOrInfoIndex) - { - $this->scan(); - - if (is_int($constantNameOrInfoIndex)) { - $info = $this->infos[$constantNameOrInfoIndex]; - if ($info['type'] != 'constant') { - throw new Exception\InvalidArgumentException('Index of info offset is not about a constant'); - } - } elseif (is_string($constantNameOrInfoIndex)) { - $constantFound = false; - foreach ($this->infos as $info) { - if ($info['type'] === 'constant' && $info['name'] === $constantNameOrInfoIndex) { - $constantFound = true; - break; - } - } - if (!$constantFound) { - return false; - } - } else { - throw new Exception\InvalidArgumentException('Invalid constant name of info index type. Must be of type int or string'); - } - if (!isset($info)) { - return false; - } - $p = new ConstantScanner( - array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart'] + 1), - $this->nameInformation - ); - $p->setClass($this->name); - $p->setScannerClass($this); - return $p; - } - - /** - * Verify if class has constant - * - * @param string $name - * @return bool - */ - public function hasConstant($name) - { - $this->scan(); - - foreach ($this->infos as $info) { - if ($info['type'] === 'constant' && $info['name'] === $name) { - return true; - } - } - - return false; - } - - /** - * Return a list of property names - * - * @return array - */ - public function getPropertyNames() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'property') { - continue; - } - - $return[] = $info['name']; - } - - return $return; - } - - /** - * Return a list of properties - * - * @return PropertyScanner - */ - public function getProperties() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'property') { - continue; - } - - $return[] = $this->getProperty($info['name']); - } - - return $return; - } - - /** - * Return a single property by given name or index of info - * - * @param string|int $propertyNameOrInfoIndex - * @throws Exception\InvalidArgumentException - * @return bool|PropertyScanner - */ - public function getProperty($propertyNameOrInfoIndex) - { - $this->scan(); - - if (is_int($propertyNameOrInfoIndex)) { - $info = $this->infos[$propertyNameOrInfoIndex]; - if ($info['type'] != 'property') { - throw new Exception\InvalidArgumentException('Index of info offset is not about a property'); - } - } elseif (is_string($propertyNameOrInfoIndex)) { - $propertyFound = false; - foreach ($this->infos as $info) { - if ($info['type'] === 'property' && $info['name'] === $propertyNameOrInfoIndex) { - $propertyFound = true; - break; - } - } - if (!$propertyFound) { - return false; - } - } else { - throw new Exception\InvalidArgumentException('Invalid property name of info index type. Must be of type int or string'); - } - if (!isset($info)) { - return false; - } - $p = new PropertyScanner( - array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart'] + 1), - $this->nameInformation - ); - $p->setClass($this->name); - $p->setScannerClass($this); - return $p; - } - - /** - * Verify if class has property - * - * @param string $name - * @return bool - */ - public function hasProperty($name) - { - $this->scan(); - - foreach ($this->infos as $info) { - if ($info['type'] === 'property' && $info['name'] === $name) { - return true; - } - } - - return false; - } - - /** - * Return a list of method names - * - * @return array - */ - public function getMethodNames() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'method') { - continue; - } - - $return[] = $info['name']; - } - - return $return; - } - - /** - * Return a list of methods - * - * @return MethodScanner[] - */ - public function getMethods() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'method') { - continue; - } - - $return[] = $this->getMethod($info['name']); - } - - return $return; - } - - /** - * Return a single method by given name or index of info - * - * @param string|int $methodNameOrInfoIndex - * @throws Exception\InvalidArgumentException - * @return MethodScanner - */ - public function getMethod($methodNameOrInfoIndex) - { - $this->scan(); - - if (is_int($methodNameOrInfoIndex)) { - $info = $this->infos[$methodNameOrInfoIndex]; - if ($info['type'] != 'method') { - throw new Exception\InvalidArgumentException('Index of info offset is not about a method'); - } - } elseif (is_string($methodNameOrInfoIndex)) { - $methodFound = false; - foreach ($this->infos as $info) { - if ($info['type'] === 'method' && $info['name'] === $methodNameOrInfoIndex) { - $methodFound = true; - break; - } - } - if (!$methodFound) { - return false; - } - } - if (!isset($info)) { - // @todo find a way to test this - die('Massive Failure, test this'); - } - - $m = new MethodScanner( - array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart'] + 1), - $this->nameInformation - ); - $m->setClass($this->name); - $m->setScannerClass($this); - - return $m; - } - - /** - * Verify if class has method by given name - * - * @param string $name - * @return bool - */ - public function hasMethod($name) - { - $this->scan(); - - foreach ($this->infos as $info) { - if ($info['type'] === 'method' && $info['name'] === $name) { - return true; - } - } - - return false; - } - - public static function export() - { - // @todo - } - - public function __toString() - { - // @todo - } - - /** - * Scan tokens - * - * @return void - * @throws Exception\RuntimeException - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - if (!$this->tokens) { - throw new Exception\RuntimeException('No tokens were provided'); - } - - /** - * Variables & Setup - */ - - $tokens = &$this->tokens; // localize - $infos = &$this->infos; // localize - $tokenIndex = null; - $token = null; - $tokenType = null; - $tokenContent = null; - $tokenLine = null; - $namespace = null; - $infoIndex = 0; - $braceCount = 0; - - /* - * MACRO creation - */ - $MACRO_TOKEN_ADVANCE = function () use (&$tokens, &$tokenIndex, &$token, &$tokenType, &$tokenContent, &$tokenLine) { - static $lastTokenArray = null; - $tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1; - if (!isset($tokens[$tokenIndex])) { - $token = false; - $tokenContent = false; - $tokenType = false; - $tokenLine = false; - - return false; - } - $token = $tokens[$tokenIndex]; - - if (is_string($token)) { - $tokenType = null; - $tokenContent = $token; - $tokenLine = $tokenLine + substr_count( - $lastTokenArray[1], - "\n" - ); // adjust token line by last known newline count - } else { - $lastTokenArray = $token; - list($tokenType, $tokenContent, $tokenLine) = $token; - } - - return $tokenIndex; - }; - $MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) { - $infos[$infoIndex]['tokenEnd'] = $tokenIndex; - $infos[$infoIndex]['lineEnd'] = $tokenLine; - $infoIndex++; - - return $infoIndex; - }; - - /** - * START FINITE STATE MACHINE FOR SCANNING TOKENS - */ - - // Initialize token - $MACRO_TOKEN_ADVANCE(); - - SCANNER_TOP: - - switch ($tokenType) { - - case T_DOC_COMMENT: - - $this->docComment = $tokenContent; - goto SCANNER_CONTINUE; - //goto no break needed - - case T_FINAL: - case T_ABSTRACT: - case T_CLASS: - case T_INTERFACE: - - // CLASS INFORMATION - - $classContext = null; - $classInterfaceIndex = 0; - - SCANNER_CLASS_INFO_TOP: - - if (is_string($tokens[$tokenIndex + 1]) && $tokens[$tokenIndex + 1] === '{') { - goto SCANNER_CLASS_INFO_END; - } - - $this->lineStart = $tokenLine; - - switch ($tokenType) { - - case T_FINAL: - $this->isFinal = true; - goto SCANNER_CLASS_INFO_CONTINUE; - //goto no break needed - - case T_ABSTRACT: - $this->isAbstract = true; - goto SCANNER_CLASS_INFO_CONTINUE; - //goto no break needed - - case T_INTERFACE: - $this->isInterface = true; - //fall-through - case T_CLASS: - $this->shortName = $tokens[$tokenIndex + 2][1]; - if ($this->nameInformation && $this->nameInformation->hasNamespace()) { - $this->name = $this->nameInformation->getNamespace() . '\\' . $this->shortName; - } else { - $this->name = $this->shortName; - } - goto SCANNER_CLASS_INFO_CONTINUE; - //goto no break needed - - case T_NS_SEPARATOR: - case T_STRING: - switch ($classContext) { - case T_EXTENDS: - $this->shortParentClass .= $tokenContent; - break; - case T_IMPLEMENTS: - $this->shortInterfaces[$classInterfaceIndex] .= $tokenContent; - break; - } - goto SCANNER_CLASS_INFO_CONTINUE; - //goto no break needed - - case T_EXTENDS: - case T_IMPLEMENTS: - $classContext = $tokenType; - if (($this->isInterface && $classContext === T_EXTENDS) || $classContext === T_IMPLEMENTS) { - $this->shortInterfaces[$classInterfaceIndex] = ''; - } elseif (!$this->isInterface && $classContext === T_EXTENDS) { - $this->shortParentClass = ''; - } - goto SCANNER_CLASS_INFO_CONTINUE; - //goto no break needed - - case null: - if ($classContext == T_IMPLEMENTS && $tokenContent == ',') { - $classInterfaceIndex++; - $this->shortInterfaces[$classInterfaceIndex] = ''; - } - - } - - SCANNER_CLASS_INFO_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_CLASS_INFO_TOP; - - SCANNER_CLASS_INFO_END: - - goto SCANNER_CONTINUE; - - } - - if ($tokenType === null && $tokenContent === '{' && $braceCount === 0) { - $braceCount++; - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - - SCANNER_CLASS_BODY_TOP: - - if ($braceCount === 0) { - goto SCANNER_CLASS_BODY_END; - } - - switch ($tokenType) { - - case T_CONST: - - $infos[$infoIndex] = array( - 'type' => 'constant', - 'tokenStart' => $tokenIndex, - 'tokenEnd' => null, - 'lineStart' => $tokenLine, - 'lineEnd' => null, - 'name' => null, - 'value' => null, - ); - - SCANNER_CLASS_BODY_CONST_TOP: - - if ($tokenContent === ';') { - goto SCANNER_CLASS_BODY_CONST_END; - } - - if ($tokenType === T_STRING && null === $infos[$infoIndex]['name']) { - $infos[$infoIndex]['name'] = $tokenContent; - } - - SCANNER_CLASS_BODY_CONST_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_CLASS_BODY_CONST_TOP; - - SCANNER_CLASS_BODY_CONST_END: - - $MACRO_INFO_ADVANCE(); - goto SCANNER_CLASS_BODY_CONTINUE; - //goto no break needed - - case T_DOC_COMMENT: - case T_PUBLIC: - case T_PROTECTED: - case T_PRIVATE: - case T_ABSTRACT: - case T_FINAL: - case T_VAR: - case T_FUNCTION: - - $infos[$infoIndex] = array( - 'type' => null, - 'tokenStart' => $tokenIndex, - 'tokenEnd' => null, - 'lineStart' => $tokenLine, - 'lineEnd' => null, - 'name' => null, - ); - - $memberContext = null; - $methodBodyStarted = false; - - SCANNER_CLASS_BODY_MEMBER_TOP: - - if ($memberContext === 'method') { - switch ($tokenContent) { - case '{': - $methodBodyStarted = true; - $braceCount++; - goto SCANNER_CLASS_BODY_MEMBER_CONTINUE; - //goto no break needed - case '}': - $braceCount--; - goto SCANNER_CLASS_BODY_MEMBER_CONTINUE; - - case ';': - $infos[$infoIndex]['tokenEnd'] = $tokenIndex; - goto SCANNER_CLASS_BODY_MEMBER_CONTINUE; - } - } - - if ($memberContext !== null) { - if ( - ($memberContext === 'property' && $tokenContent === ';') - || ($memberContext === 'method' && $methodBodyStarted && $braceCount === 1) - || ($memberContext === 'method' && $this->isInterface && $tokenContent === ';') - ) { - goto SCANNER_CLASS_BODY_MEMBER_END; - } - } - - switch ($tokenType) { - - case T_CONST: - $memberContext = 'constant'; - $infos[$infoIndex]['type'] = 'constant'; - goto SCANNER_CLASS_BODY_CONST_CONTINUE; - //goto no break needed - - case T_VARIABLE: - if ($memberContext === null) { - $memberContext = 'property'; - $infos[$infoIndex]['type'] = 'property'; - $infos[$infoIndex]['name'] = ltrim($tokenContent, '$'); - } - goto SCANNER_CLASS_BODY_MEMBER_CONTINUE; - //goto no break needed - - case T_FUNCTION: - $memberContext = 'method'; - $infos[$infoIndex]['type'] = 'method'; - goto SCANNER_CLASS_BODY_MEMBER_CONTINUE; - //goto no break needed - - case T_STRING: - if ($memberContext === 'method' && null === $infos[$infoIndex]['name']) { - $infos[$infoIndex]['name'] = $tokenContent; - } - goto SCANNER_CLASS_BODY_MEMBER_CONTINUE; - //goto no break needed - } - - SCANNER_CLASS_BODY_MEMBER_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_CLASS_BODY_MEMBER_TOP; - - SCANNER_CLASS_BODY_MEMBER_END: - - $memberContext = null; - $MACRO_INFO_ADVANCE(); - goto SCANNER_CLASS_BODY_CONTINUE; - //goto no break needed - - case null: // no type, is a string - - switch ($tokenContent) { - case '{': - $braceCount++; - goto SCANNER_CLASS_BODY_CONTINUE; - //fall-through - case '}': - $braceCount--; - goto SCANNER_CLASS_BODY_CONTINUE; - } - } - - SCANNER_CLASS_BODY_CONTINUE: - - if ($braceCount === 0 || $MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_CONTINUE; - } - goto SCANNER_CLASS_BODY_TOP; - - SCANNER_CLASS_BODY_END: - - goto SCANNER_CONTINUE; - } - - SCANNER_CONTINUE: - - if ($tokenContent === '}') { - $this->lineEnd = $tokenLine; - } - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_END: - - // process short names - if ($this->nameInformation) { - if ($this->shortParentClass) { - $this->parentClass = $this->nameInformation->resolveName($this->shortParentClass); - } - if ($this->shortInterfaces) { - foreach ($this->shortInterfaces as $siIndex => $si) { - $this->interfaces[$siIndex] = $this->nameInformation->resolveName($si); - } - } - } else { - $this->parentClass = $this->shortParentClass; - $this->interfaces = $this->shortInterfaces; - } - - $this->isScanned = true; - - return; - } -} diff --git a/library/Zend/Code/Scanner/ConstantScanner.php b/library/Zend/Code/Scanner/ConstantScanner.php deleted file mode 100755 index c37c7a22c..000000000 --- a/library/Zend/Code/Scanner/ConstantScanner.php +++ /dev/null @@ -1,236 +0,0 @@ -tokens = $constantTokens; - $this->nameInformation = $nameInformation; - } - - /** - * @param string $class - */ - public function setClass($class) - { - $this->class = $class; - } - - /** - * @param ClassScanner $scannerClass - */ - public function setScannerClass(ClassScanner $scannerClass) - { - $this->scannerClass = $scannerClass; - } - - /** - * @return ClassScanner - */ - public function getClassScanner() - { - return $this->scannerClass; - } - - /** - * @return string - */ - public function getName() - { - $this->scan(); - return $this->name; - } - - /** - * @return string - */ - public function getValue() - { - $this->scan(); - return $this->value; - } - - /** - * @return string - */ - public function getDocComment() - { - $this->scan(); - return $this->docComment; - } - - /** - * @param Annotation\AnnotationManager $annotationManager - * @return AnnotationScanner - */ - public function getAnnotations(Annotation\AnnotationManager $annotationManager) - { - if (($docComment = $this->getDocComment()) == '') { - return false; - } - - return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation); - } - - /** - * @return string - */ - public function __toString() - { - $this->scan(); - return var_export($this, true); - } - - /** - * Scan tokens - * - * @throws Exception\RuntimeException - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - if (!$this->tokens) { - throw new Exception\RuntimeException('No tokens were provided'); - } - - /** - * Variables & Setup - */ - $tokens = &$this->tokens; - - reset($tokens); - - SCANNER_TOP: - - $token = current($tokens); - - if (!is_string($token)) { - list($tokenType, $tokenContent, $tokenLine) = $token; - - switch ($tokenType) { - case T_DOC_COMMENT: - if ($this->docComment === null && $this->name === null) { - $this->docComment = $tokenContent; - } - goto SCANNER_CONTINUE; - // fall-through - - case T_STRING: - $string = (is_string($token)) ? $token : $tokenContent; - - if (null === $this->name) { - $this->name = $string; - } else { - if ('self' == strtolower($string)) { - list($tokenNextType, $tokenNextContent, $tokenNextLine) = next($tokens); - - if ('::' == $tokenNextContent) { - list($tokenNextType, $tokenNextContent, $tokenNextLine) = next($tokens); - - if ($this->getClassScanner()->getConstant($tokenNextContent)) { - $this->value = $this->getClassScanner()->getConstant($tokenNextContent)->getValue(); - } - } - } - } - - goto SCANNER_CONTINUE; - // fall-through - - case T_CONSTANT_ENCAPSED_STRING: - case T_DNUMBER: - case T_LNUMBER: - $string = (is_string($token)) ? $token : $tokenContent; - - if (substr($string, 0, 1) === '"' || substr($string, 0, 1) === "'") { - $this->value = substr($string, 1, -1); // Remove quotes - } else { - $this->value = $string; - } - goto SCANNER_CONTINUE; - // fall-trough - - default: - goto SCANNER_CONTINUE; - } - } - - SCANNER_CONTINUE: - - if (next($this->tokens) === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_END: - - $this->isScanned = true; - } -} diff --git a/library/Zend/Code/Scanner/DerivedClassScanner.php b/library/Zend/Code/Scanner/DerivedClassScanner.php deleted file mode 100755 index 6c8463ede..000000000 --- a/library/Zend/Code/Scanner/DerivedClassScanner.php +++ /dev/null @@ -1,381 +0,0 @@ -classScanner = $classScanner; - $this->directoryScanner = $directoryScanner; - - $currentScannerClass = $classScanner; - - while ($currentScannerClass && $currentScannerClass->hasParentClass()) { - $currentParentClassName = $currentScannerClass->getParentClass(); - if ($directoryScanner->hasClass($currentParentClassName)) { - $currentParentClass = $directoryScanner->getClass($currentParentClassName); - $this->parentClassScanners[$currentParentClassName] = $currentParentClass; - $currentScannerClass = $currentParentClass; - } else { - $currentScannerClass = false; - } - } - - foreach ($interfaces = $this->classScanner->getInterfaces() as $iName) { - if ($directoryScanner->hasClass($iName)) { - $this->interfaceClassScanners[$iName] = $directoryScanner->getClass($iName); - } - } - } - - /** - * @return null|string - */ - public function getName() - { - return $this->classScanner->getName(); - } - - /** - * @return null|string - */ - public function getShortName() - { - return $this->classScanner->getShortName(); - } - - /** - * @return bool - */ - public function isInstantiable() - { - return $this->classScanner->isInstantiable(); - } - - /** - * @return bool - */ - public function isFinal() - { - return $this->classScanner->isFinal(); - } - - /** - * @return bool - */ - public function isAbstract() - { - return $this->classScanner->isAbstract(); - } - - /** - * @return bool - */ - public function isInterface() - { - return $this->classScanner->isInterface(); - } - - /** - * @return array - */ - public function getParentClasses() - { - return array_keys($this->parentClassScanners); - } - - /** - * @return bool - */ - public function hasParentClass() - { - return ($this->classScanner->getParentClass() != null); - } - - /** - * @return null|string - */ - public function getParentClass() - { - return $this->classScanner->getParentClass(); - } - - /** - * @param bool $returnClassScanners - * @return array - */ - public function getInterfaces($returnClassScanners = false) - { - if ($returnClassScanners) { - return $this->interfaceClassScanners; - } - - $interfaces = $this->classScanner->getInterfaces(); - foreach ($this->parentClassScanners as $pClassScanner) { - $interfaces = array_merge($interfaces, $pClassScanner->getInterfaces()); - } - - return $interfaces; - } - - /** - * Return a list of constant names - * - * @return array - */ - public function getConstantNames() - { - $constants = $this->classScanner->getConstantNames(); - foreach ($this->parentClassScanners as $pClassScanner) { - $constants = array_merge($constants, $pClassScanner->getConstantNames()); - } - - return $constants; - } - - /** - * Return a list of constants - * - * @param bool $namesOnly Set false to return instances of ConstantScanner - * @return array|ConstantScanner[] - */ - public function getConstants($namesOnly = true) - { - if (true === $namesOnly) { - trigger_error('Use method getConstantNames() instead', E_USER_DEPRECATED); - return $this->getConstantNames(); - } - - $constants = $this->classScanner->getConstants(); - foreach ($this->parentClassScanners as $pClassScanner) { - $constants = array_merge($constants, $pClassScanner->getConstants($namesOnly)); - } - - return $constants; - } - - /** - * Return a single constant by given name or index of info - * - * @param string|int $constantNameOrInfoIndex - * @throws Exception\InvalidArgumentException - * @return bool|ConstantScanner - */ - public function getConstant($constantNameOrInfoIndex) - { - if ($this->classScanner->hasConstant($constantNameOrInfoIndex)) { - return $this->classScanner->getConstant($constantNameOrInfoIndex); - } - - foreach ($this->parentClassScanners as $pClassScanner) { - if ($pClassScanner->hasConstant($constantNameOrInfoIndex)) { - return $pClassScanner->getConstant($constantNameOrInfoIndex); - } - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Constant %s not found in %s', - $constantNameOrInfoIndex, - $this->classScanner->getName() - )); - } - - /** - * Verify if class or parent class has constant - * - * @param string $name - * @return bool - */ - public function hasConstant($name) - { - if ($this->classScanner->hasConstant($name)) { - return true; - } - foreach ($this->parentClassScanners as $pClassScanner) { - if ($pClassScanner->hasConstant($name)) { - return true; - } - } - - return false; - } - - /** - * Return a list of property names - * - * @return array - */ - public function getPropertyNames() - { - $properties = $this->classScanner->getPropertyNames(); - foreach ($this->parentClassScanners as $pClassScanner) { - $properties = array_merge($properties, $pClassScanner->getPropertyNames()); - } - - return $properties; - } - - /** - * @param bool $returnScannerProperty - * @return array - */ - public function getProperties($returnScannerProperty = false) - { - $properties = $this->classScanner->getProperties($returnScannerProperty); - foreach ($this->parentClassScanners as $pClassScanner) { - $properties = array_merge($properties, $pClassScanner->getProperties($returnScannerProperty)); - } - - return $properties; - } - - /** - * Return a single property by given name or index of info - * - * @param string|int $propertyNameOrInfoIndex - * @throws Exception\InvalidArgumentException - * @return bool|PropertyScanner - */ - public function getProperty($propertyNameOrInfoIndex) - { - if ($this->classScanner->hasProperty($propertyNameOrInfoIndex)) { - return $this->classScanner->getProperty($propertyNameOrInfoIndex); - } - - foreach ($this->parentClassScanners as $pClassScanner) { - if ($pClassScanner->hasProperty($propertyNameOrInfoIndex)) { - return $pClassScanner->getProperty($propertyNameOrInfoIndex); - } - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Property %s not found in %s', - $propertyNameOrInfoIndex, - $this->classScanner->getName() - )); - } - - /** - * Verify if class or parent class has property - * - * @param string $name - * @return bool - */ - public function hasProperty($name) - { - if ($this->classScanner->hasProperty($name)) { - return true; - } - foreach ($this->parentClassScanners as $pClassScanner) { - if ($pClassScanner->hasProperty($name)) { - return true; - } - } - - return false; - } - - /** - * @return array - */ - public function getMethodNames() - { - $methods = $this->classScanner->getMethodNames(); - foreach ($this->parentClassScanners as $pClassScanner) { - $methods = array_merge($methods, $pClassScanner->getMethodNames()); - } - - return $methods; - } - - /** - * @return MethodScanner[] - */ - public function getMethods() - { - $methods = $this->classScanner->getMethods(); - foreach ($this->parentClassScanners as $pClassScanner) { - $methods = array_merge($methods, $pClassScanner->getMethods()); - } - - return $methods; - } - - /** - * @param int|string $methodNameOrInfoIndex - * @return MethodScanner - * @throws Exception\InvalidArgumentException - */ - public function getMethod($methodNameOrInfoIndex) - { - if ($this->classScanner->hasMethod($methodNameOrInfoIndex)) { - return $this->classScanner->getMethod($methodNameOrInfoIndex); - } - - foreach ($this->parentClassScanners as $pClassScanner) { - if ($pClassScanner->hasMethod($methodNameOrInfoIndex)) { - return $pClassScanner->getMethod($methodNameOrInfoIndex); - } - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Method %s not found in %s', - $methodNameOrInfoIndex, - $this->classScanner->getName() - )); - } - - /** - * Verify if class or parent class has method by given name - * - * @param string $name - * @return bool - */ - public function hasMethod($name) - { - if ($this->classScanner->hasMethod($name)) { - return true; - } - foreach ($this->parentClassScanners as $pClassScanner) { - if ($pClassScanner->hasMethod($name)) { - return true; - } - } - - return false; - } -} diff --git a/library/Zend/Code/Scanner/DirectoryScanner.php b/library/Zend/Code/Scanner/DirectoryScanner.php deleted file mode 100755 index b1a0223da..000000000 --- a/library/Zend/Code/Scanner/DirectoryScanner.php +++ /dev/null @@ -1,272 +0,0 @@ -addDirectory($directory); - } elseif (is_array($directory)) { - foreach ($directory as $d) { - $this->addDirectory($d); - } - } - } - } - - /** - * @param DirectoryScanner|string $directory - * @return void - * @throws Exception\InvalidArgumentException - */ - public function addDirectory($directory) - { - if ($directory instanceof DirectoryScanner) { - $this->directories[] = $directory; - } elseif (is_string($directory)) { - $realDir = realpath($directory); - if (!$realDir || !is_dir($realDir)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Directory "%s" does not exist', - $realDir - )); - } - $this->directories[] = $realDir; - } else { - throw new Exception\InvalidArgumentException( - 'The argument provided was neither a DirectoryScanner or directory path' - ); - } - } - - /** - * @param DirectoryScanner $directoryScanner - * @return void - */ - public function addDirectoryScanner(DirectoryScanner $directoryScanner) - { - $this->addDirectory($directoryScanner); - } - - /** - * @param FileScanner $fileScanner - * @return void - */ - public function addFileScanner(FileScanner $fileScanner) - { - $this->fileScanners[] = $fileScanner; - } - - /** - * @return void - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - // iterate directories creating file scanners - foreach ($this->directories as $directory) { - if ($directory instanceof DirectoryScanner) { - $directory->scan(); - if ($directory->fileScanners) { - $this->fileScanners = array_merge($this->fileScanners, $directory->fileScanners); - } - } else { - $rdi = new RecursiveDirectoryIterator($directory); - foreach (new RecursiveIteratorIterator($rdi) as $item) { - if ($item->isFile() && pathinfo($item->getRealPath(), PATHINFO_EXTENSION) == 'php') { - $this->fileScanners[] = new FileScanner($item->getRealPath()); - } - } - } - } - - $this->isScanned = true; - } - - /** - * @todo implement method - */ - public function getNamespaces() - { - // @todo - } - - /** - * @param bool $returnFileScanners - * @return array - */ - public function getFiles($returnFileScanners = false) - { - $this->scan(); - - $return = array(); - foreach ($this->fileScanners as $fileScanner) { - $return[] = ($returnFileScanners) ? $fileScanner : $fileScanner->getFile(); - } - - return $return; - } - - /** - * @return array - */ - public function getClassNames() - { - $this->scan(); - - if ($this->classToFileScanner === null) { - $this->createClassToFileScannerCache(); - } - - return array_keys($this->classToFileScanner); - } - - /** - * @param bool $returnDerivedScannerClass - * @return array - */ - public function getClasses($returnDerivedScannerClass = false) - { - $this->scan(); - - if ($this->classToFileScanner === null) { - $this->createClassToFileScannerCache(); - } - - $returnClasses = array(); - foreach ($this->classToFileScanner as $className => $fsIndex) { - $classScanner = $this->fileScanners[$fsIndex]->getClass($className); - if ($returnDerivedScannerClass) { - $classScanner = new DerivedClassScanner($classScanner, $this); - } - $returnClasses[] = $classScanner; - } - - return $returnClasses; - } - - /** - * @param string $class - * @return bool - */ - public function hasClass($class) - { - $this->scan(); - - if ($this->classToFileScanner === null) { - $this->createClassToFileScannerCache(); - } - - return (isset($this->classToFileScanner[$class])); - } - - /** - * @param string $class - * @param bool $returnDerivedScannerClass - * @return ClassScanner|DerivedClassScanner - * @throws Exception\InvalidArgumentException - */ - public function getClass($class, $returnDerivedScannerClass = false) - { - $this->scan(); - - if ($this->classToFileScanner === null) { - $this->createClassToFileScannerCache(); - } - - if (!isset($this->classToFileScanner[$class])) { - throw new Exception\InvalidArgumentException('Class not found.'); - } - - /** @var FileScanner $fs */ - $fs = $this->fileScanners[$this->classToFileScanner[$class]]; - $returnClass = $fs->getClass($class); - - if (($returnClass instanceof ClassScanner) && $returnDerivedScannerClass) { - return new DerivedClassScanner($returnClass, $this); - } - - return $returnClass; - } - - /** - * Create class to file scanner cache - * - * @return void - */ - protected function createClassToFileScannerCache() - { - if ($this->classToFileScanner !== null) { - return; - } - - $this->classToFileScanner = array(); - /** @var FileScanner $fileScanner */ - foreach ($this->fileScanners as $fsIndex => $fileScanner) { - $fsClasses = $fileScanner->getClassNames(); - foreach ($fsClasses as $fsClassName) { - $this->classToFileScanner[$fsClassName] = $fsIndex; - } - } - } - - /** - * Export - * - * @todo implement method - */ - public static function export() - { - // @todo - } - - /** - * __ToString - * - * @todo implement method - */ - public function __toString() - { - // @todo - } -} diff --git a/library/Zend/Code/Scanner/DocBlockScanner.php b/library/Zend/Code/Scanner/DocBlockScanner.php deleted file mode 100755 index 3bb28ece1..000000000 --- a/library/Zend/Code/Scanner/DocBlockScanner.php +++ /dev/null @@ -1,326 +0,0 @@ -docComment = $docComment; - $this->nameInformation = $nameInformation; - } - - /** - * @return string - */ - public function getShortDescription() - { - $this->scan(); - - return $this->shortDescription; - } - - /** - * @return string - */ - public function getLongDescription() - { - $this->scan(); - - return $this->longDescription; - } - - /** - * @return array - */ - public function getTags() - { - $this->scan(); - - return $this->tags; - } - - /** - * @return array - */ - public function getAnnotations() - { - $this->scan(); - - return $this->annotations; - } - - /** - * @return void - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - $mode = 1; - - $tokens = $this->tokenize(); - $tagIndex = null; - reset($tokens); - - SCANNER_TOP: - $token = current($tokens); - - switch ($token[0]) { - case 'DOCBLOCK_NEWLINE': - if ($this->shortDescription != '' && $tagIndex === null) { - $mode = 2; - } else { - $this->longDescription .= $token[1]; - } - goto SCANNER_CONTINUE; - //goto no break needed - - case 'DOCBLOCK_WHITESPACE': - case 'DOCBLOCK_TEXT': - if ($tagIndex !== null) { - $this->tags[$tagIndex]['value'] .= ($this->tags[$tagIndex]['value'] == '') ? $token[1] : ' ' . $token[1]; - goto SCANNER_CONTINUE; - } elseif ($mode <= 2) { - if ($mode == 1) { - $this->shortDescription .= $token[1]; - } else { - $this->longDescription .= $token[1]; - } - goto SCANNER_CONTINUE; - } - //gotos no break needed - case 'DOCBLOCK_TAG': - array_push($this->tags, array('name' => $token[1], - 'value' => '')); - end($this->tags); - $tagIndex = key($this->tags); - $mode = 3; - goto SCANNER_CONTINUE; - //goto no break needed - - case 'DOCBLOCK_COMMENTEND': - goto SCANNER_END; - - } - - SCANNER_CONTINUE: - if (next($tokens) === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_END: - - $this->shortDescription = trim($this->shortDescription); - $this->longDescription = trim($this->longDescription); - $this->isScanned = true; - } - - /** - * @return array - */ - protected function tokenize() - { - static $CONTEXT_INSIDE_DOCBLOCK = 0x01; - static $CONTEXT_INSIDE_ASTERISK = 0x02; - - $context = 0x00; - $stream = $this->docComment; - $streamIndex = null; - $tokens = array(); - $tokenIndex = null; - $currentChar = null; - $currentWord = null; - $currentLine = null; - - $MACRO_STREAM_ADVANCE_CHAR = function ($positionsForward = 1) use (&$stream, &$streamIndex, &$currentChar, &$currentWord, &$currentLine) { - $positionsForward = ($positionsForward > 0) ? $positionsForward : 1; - $streamIndex = ($streamIndex === null) ? 0 : $streamIndex + $positionsForward; - if (!isset($stream[$streamIndex])) { - $currentChar = false; - - return false; - } - $currentChar = $stream[$streamIndex]; - $matches = array(); - $currentLine = (preg_match('#(.*?)\r?\n#', $stream, $matches, null, $streamIndex) === 1) ? $matches[1] : substr($stream, $streamIndex); - if ($currentChar === ' ') { - $currentWord = (preg_match('#( +)#', $currentLine, $matches) === 1) ? $matches[1] : $currentLine; - } else { - $currentWord = (($matches = strpos($currentLine, ' ')) !== false) ? substr($currentLine, 0, $matches) : $currentLine; - } - - return $currentChar; - }; - $MACRO_STREAM_ADVANCE_WORD = function () use (&$currentWord, &$MACRO_STREAM_ADVANCE_CHAR) { - return $MACRO_STREAM_ADVANCE_CHAR(strlen($currentWord)); - }; - $MACRO_STREAM_ADVANCE_LINE = function () use (&$currentLine, &$MACRO_STREAM_ADVANCE_CHAR) { - return $MACRO_STREAM_ADVANCE_CHAR(strlen($currentLine)); - }; - $MACRO_TOKEN_ADVANCE = function () use (&$tokenIndex, &$tokens) { - $tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1; - $tokens[$tokenIndex] = array('DOCBLOCK_UNKNOWN', ''); - }; - $MACRO_TOKEN_SET_TYPE = function ($type) use (&$tokenIndex, &$tokens) { - $tokens[$tokenIndex][0] = $type; - }; - $MACRO_TOKEN_APPEND_CHAR = function () use (&$currentChar, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= $currentChar; - }; - $MACRO_TOKEN_APPEND_WORD = function () use (&$currentWord, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= $currentWord; - }; - $MACRO_TOKEN_APPEND_WORD_PARTIAL = function ($length) use (&$currentWord, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= substr($currentWord, 0, $length); - }; - $MACRO_TOKEN_APPEND_LINE = function () use (&$currentLine, &$tokens, &$tokenIndex) { - $tokens[$tokenIndex][1] .= $currentLine; - }; - - $MACRO_STREAM_ADVANCE_CHAR(); - $MACRO_TOKEN_ADVANCE(); - - TOKENIZER_TOP: - - if ($context === 0x00 && $currentChar === '/' && $currentWord === '/**') { - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_COMMENTSTART'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - $context |= $CONTEXT_INSIDE_DOCBLOCK; - $context |= $CONTEXT_INSIDE_ASTERISK; - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($context & $CONTEXT_INSIDE_DOCBLOCK && $currentWord === '*/') { - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_COMMENTEND'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - $context &= ~$CONTEXT_INSIDE_DOCBLOCK; - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === ' ' || $currentChar === "\t") { - $MACRO_TOKEN_SET_TYPE(($context & $CONTEXT_INSIDE_ASTERISK) ? 'DOCBLOCK_WHITESPACE' : 'DOCBLOCK_WHITESPACE_INDENT'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === '*') { - if (($context & $CONTEXT_INSIDE_DOCBLOCK) && ($context & $CONTEXT_INSIDE_ASTERISK)) { - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_TEXT'); - } else { - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_ASTERISK'); - $context |= $CONTEXT_INSIDE_ASTERISK; - } - $MACRO_TOKEN_APPEND_CHAR(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === '@') { - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_TAG'); - $MACRO_TOKEN_APPEND_WORD(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_WORD() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - if ($currentChar === "\n") { - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_NEWLINE'); - $MACRO_TOKEN_APPEND_CHAR(); - $MACRO_TOKEN_ADVANCE(); - $context &= ~$CONTEXT_INSIDE_ASTERISK; - if ($MACRO_STREAM_ADVANCE_CHAR() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - } - - $MACRO_TOKEN_SET_TYPE('DOCBLOCK_TEXT'); - $MACRO_TOKEN_APPEND_LINE(); - $MACRO_TOKEN_ADVANCE(); - if ($MACRO_STREAM_ADVANCE_LINE() === false) { - goto TOKENIZER_END; - } - goto TOKENIZER_TOP; - - TOKENIZER_END: - - array_pop($tokens); - - return $tokens; - } -} diff --git a/library/Zend/Code/Scanner/FileScanner.php b/library/Zend/Code/Scanner/FileScanner.php deleted file mode 100755 index 64700f611..000000000 --- a/library/Zend/Code/Scanner/FileScanner.php +++ /dev/null @@ -1,46 +0,0 @@ -file = $file; - if (!file_exists($file)) { - throw new Exception\InvalidArgumentException(sprintf( - 'File "%s" not found', - $file - )); - } - parent::__construct(token_get_all(file_get_contents($file)), $annotationManager); - } - - /** - * @return string - */ - public function getFile() - { - return $this->file; - } -} diff --git a/library/Zend/Code/Scanner/FunctionScanner.php b/library/Zend/Code/Scanner/FunctionScanner.php deleted file mode 100755 index dbb082b23..000000000 --- a/library/Zend/Code/Scanner/FunctionScanner.php +++ /dev/null @@ -1,16 +0,0 @@ -tokens = $methodTokens; - $this->nameInformation = $nameInformation; - } - - /** - * @param string $class - * @return MethodScanner - */ - public function setClass($class) - { - $this->class = (string) $class; - return $this; - } - - /** - * @param ClassScanner $scannerClass - * @return MethodScanner - */ - public function setScannerClass(ClassScanner $scannerClass) - { - $this->scannerClass = $scannerClass; - return $this; - } - - /** - * @return MethodScanner - */ - public function getClassScanner() - { - return $this->scannerClass; - } - - /** - * @return string - */ - public function getName() - { - $this->scan(); - - return $this->name; - } - - /** - * @return int - */ - public function getLineStart() - { - $this->scan(); - - return $this->lineStart; - } - - /** - * @return int - */ - public function getLineEnd() - { - $this->scan(); - - return $this->lineEnd; - } - - /** - * @return string - */ - public function getDocComment() - { - $this->scan(); - - return $this->docComment; - } - - /** - * @param AnnotationManager $annotationManager - * @return AnnotationScanner - */ - public function getAnnotations(AnnotationManager $annotationManager) - { - if (($docComment = $this->getDocComment()) == '') { - return false; - } - - return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation); - } - - /** - * @return bool - */ - public function isFinal() - { - $this->scan(); - - return $this->isFinal; - } - - /** - * @return bool - */ - public function isAbstract() - { - $this->scan(); - - return $this->isAbstract; - } - - /** - * @return bool - */ - public function isPublic() - { - $this->scan(); - - return $this->isPublic; - } - - /** - * @return bool - */ - public function isProtected() - { - $this->scan(); - - return $this->isProtected; - } - - /** - * @return bool - */ - public function isPrivate() - { - $this->scan(); - - return $this->isPrivate; - } - - /** - * @return bool - */ - public function isStatic() - { - $this->scan(); - - return $this->isStatic; - } - - /** - * @return int - */ - public function getNumberOfParameters() - { - return count($this->getParameters()); - } - - /** - * @param bool $returnScanner - * @return array - */ - public function getParameters($returnScanner = false) - { - $this->scan(); - - $return = array(); - - foreach ($this->infos as $info) { - if ($info['type'] != 'parameter') { - continue; - } - - if (!$returnScanner) { - $return[] = $info['name']; - } else { - $return[] = $this->getParameter($info['name']); - } - } - - return $return; - } - - /** - * @param int|string $parameterNameOrInfoIndex - * @return ParameterScanner - * @throws Exception\InvalidArgumentException - */ - public function getParameter($parameterNameOrInfoIndex) - { - $this->scan(); - - if (is_int($parameterNameOrInfoIndex)) { - $info = $this->infos[$parameterNameOrInfoIndex]; - if ($info['type'] != 'parameter') { - throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter'); - } - } elseif (is_string($parameterNameOrInfoIndex)) { - foreach ($this->infos as $info) { - if ($info['type'] === 'parameter' && $info['name'] === $parameterNameOrInfoIndex) { - break; - } - unset($info); - } - if (!isset($info)) { - throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter'); - } - } - - $p = new ParameterScanner( - array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart']), - $this->nameInformation - ); - $p->setDeclaringFunction($this->name); - $p->setDeclaringScannerFunction($this); - $p->setDeclaringClass($this->class); - $p->setDeclaringScannerClass($this->scannerClass); - $p->setPosition($info['position']); - - return $p; - } - - /** - * @return string - */ - public function getBody() - { - $this->scan(); - - return $this->body; - } - - public static function export() - { - // @todo - } - - public function __toString() - { - $this->scan(); - - return var_export($this, true); - } - - protected function scan() - { - if ($this->isScanned) { - return; - } - - if (!$this->tokens) { - throw new Exception\RuntimeException('No tokens were provided'); - } - - /** - * Variables & Setup - */ - - $tokens = &$this->tokens; // localize - $infos = &$this->infos; // localize - $tokenIndex = null; - $token = null; - $tokenType = null; - $tokenContent = null; - $tokenLine = null; - $infoIndex = 0; - $parentCount = 0; - - /* - * MACRO creation - */ - $MACRO_TOKEN_ADVANCE = function () use (&$tokens, &$tokenIndex, &$token, &$tokenType, &$tokenContent, &$tokenLine) { - static $lastTokenArray = null; - $tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1; - if (!isset($tokens[$tokenIndex])) { - $token = false; - $tokenContent = false; - $tokenType = false; - $tokenLine = false; - - return false; - } - $token = $tokens[$tokenIndex]; - if (is_string($token)) { - $tokenType = null; - $tokenContent = $token; - $tokenLine = $tokenLine + substr_count( - $lastTokenArray[1], - "\n" - ); // adjust token line by last known newline count - } else { - list($tokenType, $tokenContent, $tokenLine) = $token; - } - - return $tokenIndex; - }; - $MACRO_INFO_START = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) { - $infos[$infoIndex] = array( - 'type' => 'parameter', - 'tokenStart' => $tokenIndex, - 'tokenEnd' => null, - 'lineStart' => $tokenLine, - 'lineEnd' => $tokenLine, - 'name' => null, - 'position' => $infoIndex + 1, // position is +1 of infoIndex - ); - }; - $MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) { - $infos[$infoIndex]['tokenEnd'] = $tokenIndex; - $infos[$infoIndex]['lineEnd'] = $tokenLine; - $infoIndex++; - - return $infoIndex; - }; - - /** - * START FINITE STATE MACHINE FOR SCANNING TOKENS - */ - - // Initialize token - $MACRO_TOKEN_ADVANCE(); - - SCANNER_TOP: - - $this->lineStart = ($this->lineStart) ? : $tokenLine; - - switch ($tokenType) { - case T_DOC_COMMENT: - $this->lineStart = null; - if ($this->docComment === null && $this->name === null) { - $this->docComment = $tokenContent; - } - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_FINAL: - $this->isFinal = true; - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_ABSTRACT: - $this->isAbstract = true; - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_PUBLIC: - // use defaults - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_PROTECTED: - $this->isProtected = true; - $this->isPublic = false; - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_PRIVATE: - $this->isPrivate = true; - $this->isPublic = false; - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_STATIC: - $this->isStatic = true; - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case T_VARIABLE: - case T_STRING: - - if ($tokenType === T_STRING && $parentCount === 0) { - $this->name = $tokenContent; - } - - if ($parentCount === 1) { - if (!isset($infos[$infoIndex])) { - $MACRO_INFO_START(); - } - if ($tokenType === T_VARIABLE) { - $infos[$infoIndex]['name'] = ltrim($tokenContent, '$'); - } - } - - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - - case null: - - switch ($tokenContent) { - case '&': - if (!isset($infos[$infoIndex])) { - $MACRO_INFO_START(); - } - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - case '(': - $parentCount++; - goto SCANNER_CONTINUE_SIGNATURE; - //goto (no break needed); - case ')': - $parentCount--; - if ($parentCount > 0) { - goto SCANNER_CONTINUE_SIGNATURE; - } - if ($parentCount === 0) { - if ($infos) { - $MACRO_INFO_ADVANCE(); - } - $context = 'body'; - } - goto SCANNER_CONTINUE_BODY; - //goto (no break needed); - case ',': - if ($parentCount === 1) { - $MACRO_INFO_ADVANCE(); - } - goto SCANNER_CONTINUE_SIGNATURE; - } - } - - SCANNER_CONTINUE_SIGNATURE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_CONTINUE_BODY: - - $braceCount = 0; - while ($MACRO_TOKEN_ADVANCE() !== false) { - if ($tokenContent == '}') { - $braceCount--; - } - if ($braceCount > 0) { - $this->body .= $tokenContent; - } - if ($tokenContent == '{') { - $braceCount++; - } - $this->lineEnd = $tokenLine; - } - - SCANNER_END: - - $this->isScanned = true; - - return; - } -} diff --git a/library/Zend/Code/Scanner/ParameterScanner.php b/library/Zend/Code/Scanner/ParameterScanner.php deleted file mode 100755 index ef15a16c8..000000000 --- a/library/Zend/Code/Scanner/ParameterScanner.php +++ /dev/null @@ -1,352 +0,0 @@ -tokens = $parameterTokens; - $this->nameInformation = $nameInformation; - } - - /** - * Set declaring class - * - * @param string $class - * @return void - */ - public function setDeclaringClass($class) - { - $this->declaringClass = (string) $class; - } - - /** - * Set declaring scanner class - * - * @param ClassScanner $scannerClass - * @return void - */ - public function setDeclaringScannerClass(ClassScanner $scannerClass) - { - $this->declaringScannerClass = $scannerClass; - } - - /** - * Set declaring function - * - * @param string $function - * @return void - */ - public function setDeclaringFunction($function) - { - $this->declaringFunction = $function; - } - - /** - * Set declaring scanner function - * - * @param MethodScanner $scannerFunction - * @return void - */ - public function setDeclaringScannerFunction(MethodScanner $scannerFunction) - { - $this->declaringScannerFunction = $scannerFunction; - } - - /** - * Set position - * - * @param int $position - * @return void - */ - public function setPosition($position) - { - $this->position = $position; - } - - /** - * Scan - * - * @return void - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - $tokens = &$this->tokens; - - reset($tokens); - - SCANNER_TOP: - - $token = current($tokens); - - if (is_string($token)) { - // check pass by ref - if ($token === '&') { - $this->isPassedByReference = true; - goto SCANNER_CONTINUE; - } - if ($token === '=') { - $this->isOptional = true; - $this->isDefaultValueAvailable = true; - goto SCANNER_CONTINUE; - } - } else { - if ($this->name === null && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR)) { - $this->class .= $token[1]; - goto SCANNER_CONTINUE; - } - if ($token[0] === T_VARIABLE) { - $this->name = ltrim($token[1], '$'); - goto SCANNER_CONTINUE; - } - } - - if ($this->name !== null) { - $this->defaultValue .= trim((is_string($token)) ? $token : $token[1]); - } - - SCANNER_CONTINUE: - - if (next($this->tokens) === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_END: - - if ($this->class && $this->nameInformation) { - $this->class = $this->nameInformation->resolveName($this->class); - } - - $this->isScanned = true; - } - - /** - * Get declaring scanner class - * - * @return ClassScanner - */ - public function getDeclaringScannerClass() - { - return $this->declaringScannerClass; - } - - /** - * Get declaring class - * - * @return string - */ - public function getDeclaringClass() - { - return $this->declaringClass; - } - - /** - * Get declaring scanner function - * - * @return MethodScanner - */ - public function getDeclaringScannerFunction() - { - return $this->declaringScannerFunction; - } - - /** - * Get declaring function - * - * @return string - */ - public function getDeclaringFunction() - { - return $this->declaringFunction; - } - - /** - * Get default value - * - * @return string - */ - public function getDefaultValue() - { - $this->scan(); - - return $this->defaultValue; - } - - /** - * Get class - * - * @return string - */ - public function getClass() - { - $this->scan(); - - return $this->class; - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - $this->scan(); - - return $this->name; - } - - /** - * Get position - * - * @return int - */ - public function getPosition() - { - $this->scan(); - - return $this->position; - } - - /** - * Check if is array - * - * @return bool - */ - public function isArray() - { - $this->scan(); - - return $this->isArray; - } - - /** - * Check if default value is available - * - * @return bool - */ - public function isDefaultValueAvailable() - { - $this->scan(); - - return $this->isDefaultValueAvailable; - } - - /** - * Check if is optional - * - * @return bool - */ - public function isOptional() - { - $this->scan(); - - return $this->isOptional; - } - - /** - * Check if is passed by reference - * - * @return bool - */ - public function isPassedByReference() - { - $this->scan(); - - return $this->isPassedByReference; - } -} diff --git a/library/Zend/Code/Scanner/PropertyScanner.php b/library/Zend/Code/Scanner/PropertyScanner.php deleted file mode 100755 index ce38b1585..000000000 --- a/library/Zend/Code/Scanner/PropertyScanner.php +++ /dev/null @@ -1,316 +0,0 @@ -tokens = $propertyTokens; - $this->nameInformation = $nameInformation; - } - - /** - * @param string $class - */ - public function setClass($class) - { - $this->class = $class; - } - - /** - * @param ClassScanner $scannerClass - */ - public function setScannerClass(ClassScanner $scannerClass) - { - $this->scannerClass = $scannerClass; - } - - /** - * @return ClassScanner - */ - public function getClassScanner() - { - return $this->scannerClass; - } - - /** - * @return string - */ - public function getName() - { - $this->scan(); - return $this->name; - } - - /** - * @return string - */ - public function getValueType() - { - return $this->valueType; - } - - /** - * @return bool - */ - public function isPublic() - { - $this->scan(); - return $this->isPublic; - } - - /** - * @return bool - */ - public function isPrivate() - { - $this->scan(); - return $this->isPrivate; - } - - /** - * @return bool - */ - public function isProtected() - { - $this->scan(); - return $this->isProtected; - } - - /** - * @return bool - */ - public function isStatic() - { - $this->scan(); - return $this->isStatic; - } - - /** - * @return string - */ - public function getValue() - { - $this->scan(); - return $this->value; - } - - /** - * @return string - */ - public function getDocComment() - { - $this->scan(); - return $this->docComment; - } - - /** - * @param Annotation\AnnotationManager $annotationManager - * @return AnnotationScanner - */ - public function getAnnotations(Annotation\AnnotationManager $annotationManager) - { - if (($docComment = $this->getDocComment()) == '') { - return false; - } - - return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation); - } - - /** - * @return string - */ - public function __toString() - { - $this->scan(); - return var_export($this, true); - } - - /** - * Scan tokens - * - * @throws \Zend\Code\Exception\RuntimeException - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - if (!$this->tokens) { - throw new Exception\RuntimeException('No tokens were provided'); - } - - /** - * Variables & Setup - */ - $value = ''; - $concatenateValue = false; - - $tokens = &$this->tokens; - reset($tokens); - - foreach ($tokens as $token) { - $tempValue = $token; - if (!is_string($token)) { - list($tokenType, $tokenContent, $tokenLine) = $token; - - switch ($tokenType) { - case T_DOC_COMMENT: - if ($this->docComment === null && $this->name === null) { - $this->docComment = $tokenContent; - } - break; - - case T_VARIABLE: - $this->name = ltrim($tokenContent, '$'); - break; - - case T_PUBLIC: - // use defaults - break; - - case T_PROTECTED: - $this->isProtected = true; - $this->isPublic = false; - break; - - case T_PRIVATE: - $this->isPrivate = true; - $this->isPublic = false; - break; - - case T_STATIC: - $this->isStatic = true; - break; - default: - $tempValue = trim($tokenContent); - break; - } - } - - //end value concatenation - if (!is_array($token) && trim($token) == ";") { - $concatenateValue = false; - } - - if (true === $concatenateValue) { - $value .= $tempValue; - } - - //start value concatenation - if (!is_array($token) && trim($token) == "=") { - $concatenateValue = true; - } - } - - $this->valueType = self::T_UNKNOWN; - if ($value == "false" || $value == "true") { - $this->valueType = self::T_BOOLEAN; - } elseif (is_numeric($value)) { - $this->valueType = self::T_INTEGER; - } elseif (0 === strpos($value, 'array') || 0 === strpos($value, "[")) { - $this->valueType = self::T_ARRAY; - } elseif (substr($value, 0, 1) === '"' || substr($value, 0, 1) === "'") { - $value = substr($value, 1, -1); // Remove quotes - $this->valueType = self::T_STRING; - } - - $this->value = empty($value) ? null : $value; - $this->isScanned = true; - } -} diff --git a/library/Zend/Code/Scanner/ScannerInterface.php b/library/Zend/Code/Scanner/ScannerInterface.php deleted file mode 100755 index 8acb04ecd..000000000 --- a/library/Zend/Code/Scanner/ScannerInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -tokens = $tokens; - $this->annotationManager = $annotationManager; - } - - /** - * @return AnnotationManager - */ - public function getAnnotationManager() - { - return $this->annotationManager; - } - - /** - * Get doc comment - * - * @todo Assignment of $this->docComment should probably be done in scan() - * and then $this->getDocComment() just retrieves it. - * - * @return string - */ - public function getDocComment() - { - foreach ($this->tokens as $token) { - $type = $token[0]; - $value = $token[1]; - if (($type == T_OPEN_TAG) || ($type == T_WHITESPACE)) { - continue; - } elseif ($type == T_DOC_COMMENT) { - $this->docComment = $value; - - return $this->docComment; - } else { - // Only whitespace is allowed before file docblocks - return; - } - } - } - - /** - * @return array - */ - public function getNamespaces() - { - $this->scan(); - - $namespaces = array(); - foreach ($this->infos as $info) { - if ($info['type'] == 'namespace') { - $namespaces[] = $info['namespace']; - } - } - - return $namespaces; - } - - /** - * @param null|string $namespace - * @return array|null - */ - public function getUses($namespace = null) - { - $this->scan(); - - return $this->getUsesNoScan($namespace); - } - - /** - * @return array - */ - public function getIncludes() - { - $this->scan(); - // @todo Implement getIncludes() in TokenArrayScanner - } - - /** - * @return array - */ - public function getClassNames() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'class') { - continue; - } - - $return[] = $info['name']; - } - - return $return; - } - - /** - * @return ClassScanner[] - */ - public function getClasses() - { - $this->scan(); - - $return = array(); - foreach ($this->infos as $info) { - if ($info['type'] != 'class') { - continue; - } - - $return[] = $this->getClass($info['name']); - } - - return $return; - } - - /** - * Return the class object from this scanner - * - * @param string|int $name - * @throws Exception\InvalidArgumentException - * @return ClassScanner - */ - public function getClass($name) - { - $this->scan(); - - if (is_int($name)) { - $info = $this->infos[$name]; - if ($info['type'] != 'class') { - throw new Exception\InvalidArgumentException('Index of info offset is not about a class'); - } - } elseif (is_string($name)) { - $classFound = false; - foreach ($this->infos as $info) { - if ($info['type'] === 'class' && $info['name'] === $name) { - $classFound = true; - break; - } - } - - if (!$classFound) { - return false; - } - } - - return new ClassScanner( - array_slice( - $this->tokens, - $info['tokenStart'], - ($info['tokenEnd'] - $info['tokenStart'] + 1) - ), // zero indexed array - new NameInformation($info['namespace'], $info['uses']) - ); - } - - /** - * @param string $className - * @return bool|null|NameInformation - */ - public function getClassNameInformation($className) - { - $this->scan(); - - $classFound = false; - foreach ($this->infos as $info) { - if ($info['type'] === 'class' && $info['name'] === $className) { - $classFound = true; - break; - } - } - - if (!$classFound) { - return false; - } - - if (!isset($info)) { - return null; - } - - return new NameInformation($info['namespace'], $info['uses']); - } - - /** - * @return array - */ - public function getFunctionNames() - { - $this->scan(); - $functionNames = array(); - foreach ($this->infos as $info) { - if ($info['type'] == 'function') { - $functionNames[] = $info['name']; - } - } - - return $functionNames; - } - - /** - * @return array - */ - public function getFunctions() - { - $this->scan(); - - $functions = array(); - foreach ($this->infos as $info) { - if ($info['type'] == 'function') { - // @todo $functions[] = new FunctionScanner($info['name']); - } - } - - return $functions; - } - - /** - * Export - * - * @param $tokens - */ - public static function export($tokens) - { - // @todo - } - - public function __toString() - { - // @todo - } - - /** - * Scan - * - * @todo: $this->docComment should be assigned for valid docblock during - * the scan instead of $this->getDocComment() (starting with - * T_DOC_COMMENT case) - * - * @throws Exception\RuntimeException - */ - protected function scan() - { - if ($this->isScanned) { - return; - } - - if (!$this->tokens) { - throw new Exception\RuntimeException('No tokens were provided'); - } - - /** - * Define PHP 5.4 'trait' token constant. - */ - if (!defined('T_TRAIT')) { - define('T_TRAIT', 42001); - } - - /** - * Variables & Setup - */ - - $tokens = &$this->tokens; // localize - $infos = &$this->infos; // localize - $tokenIndex = null; - $token = null; - $tokenType = null; - $tokenContent = null; - $tokenLine = null; - $namespace = null; - $docCommentIndex = false; - $infoIndex = 0; - - /* - * MACRO creation - */ - $MACRO_TOKEN_ADVANCE = function () use (&$tokens, &$tokenIndex, &$token, &$tokenType, &$tokenContent, &$tokenLine) { - $tokenIndex = ($tokenIndex === null) ? 0 : $tokenIndex + 1; - if (!isset($tokens[$tokenIndex])) { - $token = false; - $tokenContent = false; - $tokenType = false; - $tokenLine = false; - - return false; - } - if (is_string($tokens[$tokenIndex]) && $tokens[$tokenIndex] === '"') { - do { - $tokenIndex++; - } while (!(is_string($tokens[$tokenIndex]) && $tokens[$tokenIndex] === '"')); - } - $token = $tokens[$tokenIndex]; - if (is_array($token)) { - list($tokenType, $tokenContent, $tokenLine) = $token; - } else { - $tokenType = null; - $tokenContent = $token; - } - - return $tokenIndex; - }; - $MACRO_TOKEN_LOGICAL_START_INDEX = function () use (&$tokenIndex, &$docCommentIndex) { - return ($docCommentIndex === false) ? $tokenIndex : $docCommentIndex; - }; - $MACRO_DOC_COMMENT_START = function () use (&$tokenIndex, &$docCommentIndex) { - $docCommentIndex = $tokenIndex; - - return $docCommentIndex; - }; - $MACRO_DOC_COMMENT_VALIDATE = function () use (&$tokenType, &$docCommentIndex) { - static $validTrailingTokens = null; - if ($validTrailingTokens === null) { - $validTrailingTokens = array(T_WHITESPACE, T_FINAL, T_ABSTRACT, T_INTERFACE, T_CLASS, T_FUNCTION); - } - if ($docCommentIndex !== false && !in_array($tokenType, $validTrailingTokens)) { - $docCommentIndex = false; - } - - return $docCommentIndex; - }; - $MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) { - $infos[$infoIndex]['tokenEnd'] = $tokenIndex; - $infos[$infoIndex]['lineEnd'] = $tokenLine; - $infoIndex++; - - return $infoIndex; - }; - - /** - * START FINITE STATE MACHINE FOR SCANNING TOKENS - */ - - // Initialize token - $MACRO_TOKEN_ADVANCE(); - - SCANNER_TOP: - - if ($token === false) { - goto SCANNER_END; - } - - // Validate current doc comment index - $MACRO_DOC_COMMENT_VALIDATE(); - - switch ($tokenType) { - - case T_DOC_COMMENT: - - $MACRO_DOC_COMMENT_START(); - goto SCANNER_CONTINUE; - //goto no break needed - - case T_NAMESPACE: - - $infos[$infoIndex] = array( - 'type' => 'namespace', - 'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(), - 'tokenEnd' => null, - 'lineStart' => $token[2], - 'lineEnd' => null, - 'namespace' => null, - ); - - // start processing with next token - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - - SCANNER_NAMESPACE_TOP: - - if ($tokenType === null && $tokenContent === ';' || $tokenContent === '{') { - goto SCANNER_NAMESPACE_END; - } - - if ($tokenType === T_WHITESPACE) { - goto SCANNER_NAMESPACE_CONTINUE; - } - - if ($tokenType === T_NS_SEPARATOR || $tokenType === T_STRING) { - $infos[$infoIndex]['namespace'] .= $tokenContent; - } - - SCANNER_NAMESPACE_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_NAMESPACE_TOP; - - SCANNER_NAMESPACE_END: - - $namespace = $infos[$infoIndex]['namespace']; - - $MACRO_INFO_ADVANCE(); - goto SCANNER_CONTINUE; - //goto no break needed - - case T_USE: - - $infos[$infoIndex] = array( - 'type' => 'use', - 'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(), - 'tokenEnd' => null, - 'lineStart' => $tokens[$tokenIndex][2], - 'lineEnd' => null, - 'namespace' => $namespace, - 'statements' => array(0 => array('use' => null, - 'as' => null)), - ); - - $useStatementIndex = 0; - $useAsContext = false; - - // start processing with next token - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - - SCANNER_USE_TOP: - - if ($tokenType === null) { - if ($tokenContent === ';') { - goto SCANNER_USE_END; - } elseif ($tokenContent === ',') { - $useAsContext = false; - $useStatementIndex++; - $infos[$infoIndex]['statements'][$useStatementIndex] = array('use' => null, - 'as' => null); - } - } - - // ANALYZE - if ($tokenType !== null) { - if ($tokenType == T_AS) { - $useAsContext = true; - goto SCANNER_USE_CONTINUE; - } - - if ($tokenType == T_NS_SEPARATOR || $tokenType == T_STRING) { - if ($useAsContext == false) { - $infos[$infoIndex]['statements'][$useStatementIndex]['use'] .= $tokenContent; - } else { - $infos[$infoIndex]['statements'][$useStatementIndex]['as'] = $tokenContent; - } - } - } - - SCANNER_USE_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_USE_TOP; - - SCANNER_USE_END: - - $MACRO_INFO_ADVANCE(); - goto SCANNER_CONTINUE; - //goto no break needed - - case T_INCLUDE: - case T_INCLUDE_ONCE: - case T_REQUIRE: - case T_REQUIRE_ONCE: - - // Static for performance - static $includeTypes = array( - T_INCLUDE => 'include', - T_INCLUDE_ONCE => 'include_once', - T_REQUIRE => 'require', - T_REQUIRE_ONCE => 'require_once' - ); - - $infos[$infoIndex] = array( - 'type' => 'include', - 'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(), - 'tokenEnd' => null, - 'lineStart' => $tokens[$tokenIndex][2], - 'lineEnd' => null, - 'includeType' => $includeTypes[$tokens[$tokenIndex][0]], - 'path' => '', - ); - - // start processing with next token - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - - SCANNER_INCLUDE_TOP: - - if ($tokenType === null && $tokenContent === ';') { - goto SCANNER_INCLUDE_END; - } - - $infos[$infoIndex]['path'] .= $tokenContent; - - SCANNER_INCLUDE_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_INCLUDE_TOP; - - SCANNER_INCLUDE_END: - - $MACRO_INFO_ADVANCE(); - goto SCANNER_CONTINUE; - //goto no break needed - - case T_FUNCTION: - case T_FINAL: - case T_ABSTRACT: - case T_CLASS: - case T_INTERFACE: - case T_TRAIT: - - $infos[$infoIndex] = array( - 'type' => ($tokenType === T_FUNCTION) ? 'function' : 'class', - 'tokenStart' => $MACRO_TOKEN_LOGICAL_START_INDEX(), - 'tokenEnd' => null, - 'lineStart' => $tokens[$tokenIndex][2], - 'lineEnd' => null, - 'namespace' => $namespace, - 'uses' => $this->getUsesNoScan($namespace), - 'name' => null, - 'shortName' => null, - ); - - $classBraceCount = 0; - - // start processing with current token - - SCANNER_CLASS_TOP: - - // process the name - if ($infos[$infoIndex]['shortName'] == '' - && (($tokenType === T_CLASS || $tokenType === T_INTERFACE || $tokenType === T_TRAIT) && $infos[$infoIndex]['type'] === 'class' - || ($tokenType === T_FUNCTION && $infos[$infoIndex]['type'] === 'function')) - ) { - $infos[$infoIndex]['shortName'] = $tokens[$tokenIndex + 2][1]; - $infos[$infoIndex]['name'] = (($namespace != null) ? $namespace . '\\' : '') . $infos[$infoIndex]['shortName']; - } - - if ($tokenType === null) { - if ($tokenContent == '{') { - $classBraceCount++; - } - if ($tokenContent == '}') { - $classBraceCount--; - if ($classBraceCount === 0) { - goto SCANNER_CLASS_END; - } - } - } - - SCANNER_CLASS_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_CLASS_TOP; - - SCANNER_CLASS_END: - - $MACRO_INFO_ADVANCE(); - goto SCANNER_CONTINUE; - - } - - SCANNER_CONTINUE: - - if ($MACRO_TOKEN_ADVANCE() === false) { - goto SCANNER_END; - } - goto SCANNER_TOP; - - SCANNER_END: - - /** - * END FINITE STATE MACHINE FOR SCANNING TOKENS - */ - - $this->isScanned = true; - } - - /** - * Check for namespace - * - * @param string $namespace - * @return bool - */ - public function hasNamespace($namespace) - { - $this->scan(); - - foreach ($this->infos as $info) { - if ($info['type'] == 'namespace' && $info['namespace'] == $namespace) { - return true; - } - } - return false; - } - - /** - * @param string $namespace - * @return null|array - * @throws Exception\InvalidArgumentException - */ - protected function getUsesNoScan($namespace) - { - $namespaces = array(); - foreach ($this->infos as $info) { - if ($info['type'] == 'namespace') { - $namespaces[] = $info['namespace']; - } - } - - if ($namespace === null) { - $namespace = array_shift($namespaces); - } elseif (!is_string($namespace)) { - throw new Exception\InvalidArgumentException('Invalid namespace provided'); - } elseif (!in_array($namespace, $namespaces)) { - return null; - } - - $uses = array(); - foreach ($this->infos as $info) { - if ($info['type'] !== 'use') { - continue; - } - foreach ($info['statements'] as $statement) { - if ($info['namespace'] == $namespace) { - $uses[] = $statement; - } - } - } - - return $uses; - } -} diff --git a/library/Zend/Code/Scanner/Util.php b/library/Zend/Code/Scanner/Util.php deleted file mode 100755 index e54ae0b88..000000000 --- a/library/Zend/Code/Scanner/Util.php +++ /dev/null @@ -1,74 +0,0 @@ -namespace && !$data->uses && strlen($value) > 0 && $value{0} != '\\') { - $value = $data->namespace . '\\' . $value; - - return; - } - - if (!$data->uses || strlen($value) <= 0 || $value{0} == '\\') { - $value = ltrim($value, '\\'); - - return; - } - - if ($data->namespace || $data->uses) { - $firstPart = $value; - if (($firstPartEnd = strpos($firstPart, '\\')) !== false) { - $firstPart = substr($firstPart, 0, $firstPartEnd); - } else { - $firstPartEnd = strlen($firstPart); - } - - if (array_key_exists($firstPart, $data->uses)) { - $value = substr_replace($value, $data->uses[$firstPart], 0, $firstPartEnd); - - return; - } - - if ($data->namespace) { - $value = $data->namespace . '\\' . $value; - - return; - } - } - } -} diff --git a/library/Zend/Code/Scanner/ValueScanner.php b/library/Zend/Code/Scanner/ValueScanner.php deleted file mode 100755 index d0826cc24..000000000 --- a/library/Zend/Code/Scanner/ValueScanner.php +++ /dev/null @@ -1,15 +0,0 @@ -=5.3.23", - "zendframework/zend-eventmanager": "self.version" - }, - "require-dev": { - "doctrine/common": ">=2.1", - "zendframework/zend-stdlib": "self.version" - }, - "suggest": { - "doctrine/common": "Doctrine\\Common >=2.1 for annotation features", - "zendframework/zend-stdlib": "Zend\\Stdlib component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Config/AbstractConfigFactory.php b/library/Zend/Config/AbstractConfigFactory.php deleted file mode 100755 index 20f04be02..000000000 --- a/library/Zend/Config/AbstractConfigFactory.php +++ /dev/null @@ -1,172 +0,0 @@ -configs[$requestedName])) { - return true; - } - - if (!$serviceLocator->has('Config')) { - return false; - } - - $key = $this->match($requestedName); - if (null === $key) { - return false; - } - - $config = $serviceLocator->get('Config'); - return isset($config[$key]); - } - - /** - * Create service with name - * - * @param ServiceManager\ServiceLocatorInterface $serviceLocator - * @param string $name - * @param string $requestedName - * @return string|mixed|array - */ - public function createServiceWithName(ServiceManager\ServiceLocatorInterface $serviceLocator, $name, $requestedName) - { - if (isset($this->configs[$requestedName])) { - return $this->configs[$requestedName]; - } - - $key = $this->match($requestedName); - if (isset($this->configs[$key])) { - $this->configs[$requestedName] = $this->configs[$key]; - return $this->configs[$key]; - } - - $config = $serviceLocator->get('Config'); - $this->configs[$requestedName] = $this->configs[$key] = $config[$key]; - return $config; - } - - /** - * @param string $pattern - * @return self - * @throws Exception\InvalidArgumentException - */ - public function addPattern($pattern) - { - if (!is_string($pattern)) { - throw new Exception\InvalidArgumentException('pattern must be string'); - } - - $patterns = $this->getPatterns(); - array_unshift($patterns, $pattern); - $this->setPatterns($patterns); - return $this; - } - - /** - * @param array|Traversable $patterns - * @return self - * @throws Exception\InvalidArgumentException - */ - public function addPatterns($patterns) - { - if ($patterns instanceof Traversable) { - $patterns = iterator_to_array($patterns); - } - - if (!is_array($patterns)) { - throw new Exception\InvalidArgumentException("patterns must be array or Traversable"); - } - - foreach ($patterns as $pattern) { - $this->addPattern($pattern); - } - - return $this; - } - - /** - * @param array|Traversable $patterns - * @return self - * @throws \InvalidArgumentException - */ - public function setPatterns($patterns) - { - if ($patterns instanceof Traversable) { - $patterns = iterator_to_array($patterns); - } - - if (!is_array($patterns)) { - throw new \InvalidArgumentException("patterns must be array or Traversable"); - } - - $this->patterns = $patterns; - return $this; - } - - /** - * @return array - */ - public function getPatterns() - { - if (null === $this->patterns) { - $this->setPatterns($this->defaultPatterns); - } - return $this->patterns; - } - - /** - * @param string $requestedName - * @return null|string - */ - protected function match($requestedName) - { - foreach ($this->getPatterns() as $pattern) { - if (preg_match($pattern, $requestedName, $matches)) { - return $matches[1]; - } - } - return null; - } -} diff --git a/library/Zend/Config/CONTRIBUTING.md b/library/Zend/Config/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Config/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Config/Config.php b/library/Zend/Config/Config.php deleted file mode 100755 index 17b679782..000000000 --- a/library/Zend/Config/Config.php +++ /dev/null @@ -1,400 +0,0 @@ -allowModifications = (bool) $allowModifications; - - foreach ($array as $key => $value) { - if (is_array($value)) { - $this->data[$key] = new static($value, $this->allowModifications); - } else { - $this->data[$key] = $value; - } - - $this->count++; - } - } - - /** - * Retrieve a value and return $default if there is no element set. - * - * @param string $name - * @param mixed $default - * @return mixed - */ - public function get($name, $default = null) - { - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } - - return $default; - } - - /** - * Magic function so that $obj->value will work. - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - return $this->get($name); - } - - /** - * Set a value in the config. - * - * Only allow setting of a property if $allowModifications was set to true - * on construction. Otherwise, throw an exception. - * - * @param string $name - * @param mixed $value - * @return void - * @throws Exception\RuntimeException - */ - public function __set($name, $value) - { - if ($this->allowModifications) { - if (is_array($value)) { - $value = new static($value, true); - } - - if (null === $name) { - $this->data[] = $value; - } else { - $this->data[$name] = $value; - } - - $this->count++; - } else { - throw new Exception\RuntimeException('Config is read only'); - } - } - - /** - * Deep clone of this instance to ensure that nested Zend\Configs are also - * cloned. - * - * @return void - */ - public function __clone() - { - $array = array(); - - foreach ($this->data as $key => $value) { - if ($value instanceof self) { - $array[$key] = clone $value; - } else { - $array[$key] = $value; - } - } - - $this->data = $array; - } - - /** - * Return an associative array of the stored data. - * - * @return array - */ - public function toArray() - { - $array = array(); - $data = $this->data; - - /** @var self $value */ - foreach ($data as $key => $value) { - if ($value instanceof self) { - $array[$key] = $value->toArray(); - } else { - $array[$key] = $value; - } - } - - return $array; - } - - /** - * isset() overloading - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - return isset($this->data[$name]); - } - - /** - * unset() overloading - * - * @param string $name - * @return void - * @throws Exception\InvalidArgumentException - */ - public function __unset($name) - { - if (!$this->allowModifications) { - throw new Exception\InvalidArgumentException('Config is read only'); - } elseif (isset($this->data[$name])) { - unset($this->data[$name]); - $this->count--; - $this->skipNextIteration = true; - } - } - - /** - * count(): defined by Countable interface. - * - * @see Countable::count() - * @return int - */ - public function count() - { - return $this->count; - } - - /** - * current(): defined by Iterator interface. - * - * @see Iterator::current() - * @return mixed - */ - public function current() - { - $this->skipNextIteration = false; - return current($this->data); - } - - /** - * key(): defined by Iterator interface. - * - * @see Iterator::key() - * @return mixed - */ - public function key() - { - return key($this->data); - } - - /** - * next(): defined by Iterator interface. - * - * @see Iterator::next() - * @return void - */ - public function next() - { - if ($this->skipNextIteration) { - $this->skipNextIteration = false; - return; - } - - next($this->data); - } - - /** - * rewind(): defined by Iterator interface. - * - * @see Iterator::rewind() - * @return void - */ - public function rewind() - { - $this->skipNextIteration = false; - reset($this->data); - } - - /** - * valid(): defined by Iterator interface. - * - * @see Iterator::valid() - * @return bool - */ - public function valid() - { - return ($this->key() !== null); - } - - /** - * offsetExists(): defined by ArrayAccess interface. - * - * @see ArrayAccess::offsetExists() - * @param mixed $offset - * @return bool - */ - public function offsetExists($offset) - { - return $this->__isset($offset); - } - - /** - * offsetGet(): defined by ArrayAccess interface. - * - * @see ArrayAccess::offsetGet() - * @param mixed $offset - * @return mixed - */ - public function offsetGet($offset) - { - return $this->__get($offset); - } - - /** - * offsetSet(): defined by ArrayAccess interface. - * - * @see ArrayAccess::offsetSet() - * @param mixed $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset, $value) - { - $this->__set($offset, $value); - } - - /** - * offsetUnset(): defined by ArrayAccess interface. - * - * @see ArrayAccess::offsetUnset() - * @param mixed $offset - * @return void - */ - public function offsetUnset($offset) - { - $this->__unset($offset); - } - - /** - * Merge another Config with this one. - * - * For duplicate keys, the following will be performed: - * - Nested Configs will be recursively merged. - * - Items in $merge with INTEGER keys will be appended. - * - Items in $merge with STRING keys will overwrite current values. - * - * @param Config $merge - * @return Config - */ - public function merge(Config $merge) - { - /** @var Config $value */ - foreach ($merge as $key => $value) { - if (array_key_exists($key, $this->data)) { - if (is_int($key)) { - $this->data[] = $value; - } elseif ($value instanceof self && $this->data[$key] instanceof self) { - $this->data[$key]->merge($value); - } else { - if ($value instanceof self) { - $this->data[$key] = new static($value->toArray(), $this->allowModifications); - } else { - $this->data[$key] = $value; - } - } - } else { - if ($value instanceof self) { - $this->data[$key] = new static($value->toArray(), $this->allowModifications); - } else { - $this->data[$key] = $value; - } - - $this->count++; - } - } - - return $this; - } - - /** - * Prevent any more modifications being made to this instance. - * - * Useful after merge() has been used to merge multiple Config objects - * into one object which should then not be modified again. - * - * @return void - */ - public function setReadOnly() - { - $this->allowModifications = false; - - /** @var Config $value */ - foreach ($this->data as $value) { - if ($value instanceof self) { - $value->setReadOnly(); - } - } - } - - /** - * Returns whether this Config object is read only or not. - * - * @return bool - */ - public function isReadOnly() - { - return !$this->allowModifications; - } -} diff --git a/library/Zend/Config/Exception/ExceptionInterface.php b/library/Zend/Config/Exception/ExceptionInterface.php deleted file mode 100755 index d6e0240f1..000000000 --- a/library/Zend/Config/Exception/ExceptionInterface.php +++ /dev/null @@ -1,14 +0,0 @@ - 'ini', - 'json' => 'json', - 'xml' => 'xml', - 'yaml' => 'yaml', - ); - - /** - * Register config file extensions for writing - * key is extension, value is writer instance or plugin name - * - * @var array - */ - protected static $writerExtensions = array( - 'php' => 'php', - 'ini' => 'ini', - 'json' => 'json', - 'xml' => 'xml', - 'yaml' => 'yaml', - ); - - /** - * Read a config from a file. - * - * @param string $filename - * @param bool $returnConfigObject - * @param bool $useIncludePath - * @return array|Config - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public static function fromFile($filename, $returnConfigObject = false, $useIncludePath = false) - { - $filepath = $filename; - if (!file_exists($filename)) { - if (!$useIncludePath) { - throw new Exception\RuntimeException(sprintf( - 'Filename "%s" cannot be found relative to the working directory', - $filename - )); - } - - $fromIncludePath = stream_resolve_include_path($filename); - if (!$fromIncludePath) { - throw new Exception\RuntimeException(sprintf( - 'Filename "%s" cannot be found relative to the working directory or the include_path ("%s")', - $filename, - get_include_path() - )); - } - $filepath = $fromIncludePath; - } - - $pathinfo = pathinfo($filepath); - - if (!isset($pathinfo['extension'])) { - throw new Exception\RuntimeException(sprintf( - 'Filename "%s" is missing an extension and cannot be auto-detected', - $filename - )); - } - - $extension = strtolower($pathinfo['extension']); - - if ($extension === 'php') { - if (!is_file($filepath) || !is_readable($filepath)) { - throw new Exception\RuntimeException(sprintf( - "File '%s' doesn't exist or not readable", - $filename - )); - } - - $config = include $filepath; - } elseif (isset(static::$extensions[$extension])) { - $reader = static::$extensions[$extension]; - if (!$reader instanceof Reader\ReaderInterface) { - $reader = static::getReaderPluginManager()->get($reader); - static::$extensions[$extension] = $reader; - } - - /** @var Reader\ReaderInterface $reader */ - $config = $reader->fromFile($filepath); - } else { - throw new Exception\RuntimeException(sprintf( - 'Unsupported config file extension: .%s', - $pathinfo['extension'] - )); - } - - return ($returnConfigObject) ? new Config($config) : $config; - } - - /** - * Read configuration from multiple files and merge them. - * - * @param array $files - * @param bool $returnConfigObject - * @param bool $useIncludePath - * @return array|Config - */ - public static function fromFiles(array $files, $returnConfigObject = false, $useIncludePath = false) - { - $config = array(); - - foreach ($files as $file) { - $config = ArrayUtils::merge($config, static::fromFile($file, false, $useIncludePath)); - } - - return ($returnConfigObject) ? new Config($config) : $config; - } - - /** - * Writes a config to a file - * - * @param string $filename - * @param array|Config $config - * @return bool TRUE on success | FALSE on failure - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - */ - public static function toFile($filename, $config) - { - if ( - (is_object($config) && !($config instanceof Config)) || - (!is_object($config) && !is_array($config)) - ) { - throw new Exception\InvalidArgumentException( - __METHOD__." \$config should be an array or instance of Zend\\Config\\Config" - ); - } - - $extension = substr(strrchr($filename, '.'), 1); - $directory = dirname($filename); - - if (!is_dir($directory)) { - throw new Exception\RuntimeException( - "Directory '{$directory}' does not exists!" - ); - } - - if (!is_writable($directory)) { - throw new Exception\RuntimeException( - "Cannot write in directory '{$directory}'" - ); - } - - if (!isset(static::$writerExtensions[$extension])) { - throw new Exception\RuntimeException( - "Unsupported config file extension: '.{$extension}' for writing." - ); - } - - $writer = static::$writerExtensions[$extension]; - if (($writer instanceof Writer\AbstractWriter) === false) { - $writer = self::getWriterPluginManager()->get($writer); - static::$writerExtensions[$extension] = $writer; - } - - if (is_object($config)) { - $config = $config->toArray(); - } - - $content = $writer->processConfig($config); - - return (bool) (file_put_contents($filename, $content) !== false); - } - - /** - * Set reader plugin manager - * - * @param ReaderPluginManager $readers - * @return void - */ - public static function setReaderPluginManager(ReaderPluginManager $readers) - { - static::$readers = $readers; - } - - /** - * Get the reader plugin manager - * - * @return ReaderPluginManager - */ - public static function getReaderPluginManager() - { - if (static::$readers === null) { - static::$readers = new ReaderPluginManager(); - } - return static::$readers; - } - - /** - * Set writer plugin manager - * - * @param WriterPluginManager $writers - * @return void - */ - public static function setWriterPluginManager(WriterPluginManager $writers) - { - static::$writers = $writers; - } - - /** - * Get the writer plugin manager - * - * @return WriterPluginManager - */ - public static function getWriterPluginManager() - { - if (static::$writers === null) { - static::$writers = new WriterPluginManager(); - } - - return static::$writers; - } - - /** - * Set config reader for file extension - * - * @param string $extension - * @param string|Reader\ReaderInterface $reader - * @throws Exception\InvalidArgumentException - * @return void - */ - public static function registerReader($extension, $reader) - { - $extension = strtolower($extension); - - if (!is_string($reader) && !$reader instanceof Reader\ReaderInterface) { - throw new Exception\InvalidArgumentException(sprintf( - 'Reader should be plugin name, class name or ' . - 'instance of %s\Reader\ReaderInterface; received "%s"', - __NAMESPACE__, - (is_object($reader) ? get_class($reader) : gettype($reader)) - )); - } - - static::$extensions[$extension] = $reader; - } - - /** - * Set config writer for file extension - * - * @param string $extension - * @param string|Writer\AbstractWriter $writer - * @throws Exception\InvalidArgumentException - * @return void - */ - public static function registerWriter($extension, $writer) - { - $extension = strtolower($extension); - - if (!is_string($writer) && !$writer instanceof Writer\AbstractWriter) { - throw new Exception\InvalidArgumentException(sprintf( - 'Writer should be plugin name, class name or ' . - 'instance of %s\Writer\AbstractWriter; received "%s"', - __NAMESPACE__, - (is_object($writer) ? get_class($writer) : gettype($writer)) - )); - } - - static::$writerExtensions[$extension] = $writer; - } -} diff --git a/library/Zend/Config/Processor/Constant.php b/library/Zend/Config/Processor/Constant.php deleted file mode 100755 index 28f76b9a7..000000000 --- a/library/Zend/Config/Processor/Constant.php +++ /dev/null @@ -1,83 +0,0 @@ -setUserOnly($userOnly); - $this->setPrefix($prefix); - $this->setSuffix($suffix); - - $this->loadConstants(); - } - - /** - * @return bool - */ - public function getUserOnly() - { - return $this->userOnly; - } - - /** - * Should we use only user-defined constants? - * - * @param bool $userOnly - * @return Constant - */ - public function setUserOnly($userOnly) - { - $this->userOnly = (bool) $userOnly; - return $this; - } - - /** - * Load all currently defined constants into parser. - * - * @return void - */ - public function loadConstants() - { - if ($this->userOnly) { - $constants = get_defined_constants(true); - $constants = isset($constants['user']) ? $constants['user'] : array(); - $this->setTokens($constants); - } else { - $this->setTokens(get_defined_constants()); - } - } - - /** - * Get current token registry. - * @return array - */ - public function getTokens() - { - return $this->tokens; - } -} diff --git a/library/Zend/Config/Processor/Filter.php b/library/Zend/Config/Processor/Filter.php deleted file mode 100755 index 99909f289..000000000 --- a/library/Zend/Config/Processor/Filter.php +++ /dev/null @@ -1,88 +0,0 @@ -setFilter($filter); - } - - /** - * @param ZendFilter $filter - * @return Filter - */ - public function setFilter(ZendFilter $filter) - { - $this->filter = $filter; - return $this; - } - - /** - * @return ZendFilter - */ - public function getFilter() - { - return $this->filter; - } - - /** - * Process - * - * @param Config $config - * @return Config - * @throws Exception\InvalidArgumentException - */ - public function process(Config $config) - { - if ($config->isReadOnly()) { - throw new Exception\InvalidArgumentException('Cannot process config because it is read-only'); - } - - /** - * Walk through config and replace values - */ - foreach ($config as $key => $val) { - if ($val instanceof Config) { - $this->process($val); - } else { - $config->$key = $this->filter->filter($val); - } - } - - return $config; - } - - /** - * Process a single value - * - * @param mixed $value - * @return mixed - */ - public function processValue($value) - { - return $this->filter->filter($value); - } -} diff --git a/library/Zend/Config/Processor/ProcessorInterface.php b/library/Zend/Config/Processor/ProcessorInterface.php deleted file mode 100755 index 6aa28e91c..000000000 --- a/library/Zend/Config/Processor/ProcessorInterface.php +++ /dev/null @@ -1,31 +0,0 @@ -isReadOnly()) { - throw new Exception\InvalidArgumentException('Cannot process config because it is read-only'); - } - - foreach ($this as $parser) { - /** @var $parser ProcessorInterface */ - $parser->process($config); - } - } - - /** - * Process a single value - * - * @param mixed $value - * @return mixed - */ - public function processValue($value) - { - foreach ($this as $parser) { - /** @var $parser ProcessorInterface */ - $value = $parser->processValue($value); - } - - return $value; - } -} diff --git a/library/Zend/Config/Processor/Token.php b/library/Zend/Config/Processor/Token.php deleted file mode 100755 index 2af2e1b3f..000000000 --- a/library/Zend/Config/Processor/Token.php +++ /dev/null @@ -1,274 +0,0 @@ - value - * to replace it with - * @param string $prefix - * @param string $suffix - * @internal param array $options - * @return Token - */ - public function __construct($tokens = array(), $prefix = '', $suffix = '') - { - $this->setTokens($tokens); - $this->setPrefix($prefix); - $this->setSuffix($suffix); - } - - /** - * @param string $prefix - * @return Token - */ - public function setPrefix($prefix) - { - // reset map - $this->map = null; - $this->prefix = $prefix; - return $this; - } - - /** - * @return string - */ - public function getPrefix() - { - return $this->prefix; - } - - /** - * @param string $suffix - * @return Token - */ - public function setSuffix($suffix) - { - // reset map - $this->map = null; - $this->suffix = $suffix; - - return $this; - } - - /** - * @return string - */ - public function getSuffix() - { - return $this->suffix; - } - - /** - * Set token registry. - * - * @param array|Config|Traversable $tokens Associative array of TOKEN => value - * to replace it with - * @return Token - * @throws Exception\InvalidArgumentException - */ - public function setTokens($tokens) - { - if (is_array($tokens)) { - $this->tokens = $tokens; - } elseif ($tokens instanceof Config) { - $this->tokens = $tokens->toArray(); - } elseif ($tokens instanceof Traversable) { - $this->tokens = array(); - foreach ($tokens as $key => $val) { - $this->tokens[$key] = $val; - } - } else { - throw new Exception\InvalidArgumentException('Cannot use ' . gettype($tokens) . ' as token registry.'); - } - - // reset map - $this->map = null; - - return $this; - } - - /** - * Get current token registry. - * - * @return array - */ - public function getTokens() - { - return $this->tokens; - } - - /** - * Add new token. - * - * @param string $token - * @param mixed $value - * @return Token - * @throws Exception\InvalidArgumentException - */ - public function addToken($token, $value) - { - if (!is_scalar($token)) { - throw new Exception\InvalidArgumentException('Cannot use ' . gettype($token) . ' as token name.'); - } - $this->tokens[$token] = $value; - - // reset map - $this->map = null; - - return $this; - } - - /** - * Add new token. - * - * @param string $token - * @param mixed $value - * @return Token - */ - public function setToken($token, $value) - { - return $this->addToken($token, $value); - } - - /** - * Build replacement map - * - * @return array - */ - protected function buildMap() - { - if (null === $this->map) { - if (!$this->suffix && !$this->prefix) { - $this->map = $this->tokens; - } else { - $this->map = array(); - - foreach ($this->tokens as $token => $value) { - $this->map[$this->prefix . $token . $this->suffix] = $value; - } - } - - foreach (array_keys($this->map) as $key) { - if (empty($key)) { - unset($this->map[$key]); - } - } - } - - return $this->map; - } - - /** - * Process - * - * @param Config $config - * @return Config - * @throws Exception\InvalidArgumentException - */ - public function process(Config $config) - { - return $this->doProcess($config, $this->buildMap()); - } - - /** - * Process a single value - * - * @param $value - * @return mixed - */ - public function processValue($value) - { - return $this->doProcess($value, $this->buildMap()); - } - - /** - * Applies replacement map to the given value by modifying the value itself - * - * @param mixed $value - * @param array $replacements - * - * @return mixed - * - * @throws Exception\InvalidArgumentException if the provided value is a read-only {@see Config} - */ - private function doProcess($value, array $replacements) - { - if ($value instanceof Config) { - if ($value->isReadOnly()) { - throw new Exception\InvalidArgumentException('Cannot process config because it is read-only'); - } - - foreach ($value as $key => $val) { - $value->$key = $this->doProcess($val, $replacements); - } - - return $value; - } - - if ($value instanceof Traversable || is_array($value)) { - foreach ($value as & $val) { - $val = $this->doProcess($val, $replacements); - } - - return $value; - } - - if (!is_string($value) && (is_bool($value) || is_numeric($value))) { - $stringVal = (string) $value; - $changedVal = strtr($value, $this->map); - - // replace the value only if a string replacement occurred - if ($changedVal !== $stringVal) { - return $changedVal; - } - - return $value; - } - - return strtr((string) $value, $this->map); - } -} diff --git a/library/Zend/Config/Processor/Translator.php b/library/Zend/Config/Processor/Translator.php deleted file mode 100755 index 48c0985de..000000000 --- a/library/Zend/Config/Processor/Translator.php +++ /dev/null @@ -1,139 +0,0 @@ -setTranslator($translator); - $this->setTextDomain($textDomain); - $this->setLocale($locale); - } - - /** - * @param ZendTranslator $translator - * @return Translator - */ - public function setTranslator(ZendTranslator $translator) - { - $this->translator = $translator; - return $this; - } - - /** - * @return ZendTranslator - */ - public function getTranslator() - { - return $this->translator; - } - - /** - * @param string|null $locale - * @return Translator - */ - public function setLocale($locale) - { - $this->locale = $locale; - return $this; - } - - /** - * @return string|null - */ - public function getLocale() - { - return $this->locale; - } - - /** - * @param string $textDomain - * @return Translator - */ - public function setTextDomain($textDomain) - { - $this->textDomain = $textDomain; - return $this; - } - - /** - * @return string - */ - public function getTextDomain() - { - return $this->textDomain; - } - - /** - * Process - * - * @param Config $config - * @return Config - * @throws Exception\InvalidArgumentException - */ - public function process(Config $config) - { - if ($config->isReadOnly()) { - throw new Exception\InvalidArgumentException('Cannot process config because it is read-only'); - } - - /** - * Walk through config and replace values - */ - foreach ($config as $key => $val) { - if ($val instanceof Config) { - $this->process($val); - } else { - $config->{$key} = $this->translator->translate($val, $this->textDomain, $this->locale); - } - } - - return $config; - } - - /** - * Process a single value - * - * @param $value - * @return string - */ - public function processValue($value) - { - return $this->translator->translate($value, $this->textDomain, $this->locale); - } -} diff --git a/library/Zend/Config/README.md b/library/Zend/Config/README.md deleted file mode 100755 index 650ba568d..000000000 --- a/library/Zend/Config/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Config Component from ZF2 -========================= - -This is the Config component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Config/Reader/Ini.php b/library/Zend/Config/Reader/Ini.php deleted file mode 100755 index 343668549..000000000 --- a/library/Zend/Config/Reader/Ini.php +++ /dev/null @@ -1,225 +0,0 @@ -nestSeparator = $separator; - return $this; - } - - /** - * Get nest separator. - * - * @return string - */ - public function getNestSeparator() - { - return $this->nestSeparator; - } - - /** - * fromFile(): defined by Reader interface. - * - * @see ReaderInterface::fromFile() - * @param string $filename - * @return array - * @throws Exception\RuntimeException - */ - public function fromFile($filename) - { - if (!is_file($filename) || !is_readable($filename)) { - throw new Exception\RuntimeException(sprintf( - "File '%s' doesn't exist or not readable", - $filename - )); - } - - $this->directory = dirname($filename); - - set_error_handler( - function ($error, $message = '', $file = '', $line = 0) use ($filename) { - throw new Exception\RuntimeException( - sprintf('Error reading INI file "%s": %s', $filename, $message), - $error - ); - }, - E_WARNING - ); - $ini = parse_ini_file($filename, true); - restore_error_handler(); - - return $this->process($ini); - } - - /** - * fromString(): defined by Reader interface. - * - * @param string $string - * @return array|bool - * @throws Exception\RuntimeException - */ - public function fromString($string) - { - if (empty($string)) { - return array(); - } - $this->directory = null; - - set_error_handler( - function ($error, $message = '', $file = '', $line = 0) { - throw new Exception\RuntimeException( - sprintf('Error reading INI string: %s', $message), - $error - ); - }, - E_WARNING - ); - $ini = parse_ini_string($string, true); - restore_error_handler(); - - return $this->process($ini); - } - - /** - * Process data from the parsed ini file. - * - * @param array $data - * @return array - */ - protected function process(array $data) - { - $config = array(); - - foreach ($data as $section => $value) { - if (is_array($value)) { - if (strpos($section, $this->nestSeparator) !== false) { - $sections = explode($this->nestSeparator, $section); - $config = array_merge_recursive($config, $this->buildNestedSection($sections, $value)); - } else { - $config[$section] = $this->processSection($value); - } - } else { - $this->processKey($section, $value, $config); - } - } - - return $config; - } - - /** - * Process a nested section - * - * @param array $sections - * @param mixed $value - * @return array - */ - private function buildNestedSection($sections, $value) - { - if (count($sections) == 0) { - return $this->processSection($value); - } - - $nestedSection = array(); - - $first = array_shift($sections); - $nestedSection[$first] = $this->buildNestedSection($sections, $value); - - return $nestedSection; - } - - /** - * Process a section. - * - * @param array $section - * @return array - */ - protected function processSection(array $section) - { - $config = array(); - - foreach ($section as $key => $value) { - $this->processKey($key, $value, $config); - } - - return $config; - } - - /** - * Process a key. - * - * @param string $key - * @param string $value - * @param array $config - * @return array - * @throws Exception\RuntimeException - */ - protected function processKey($key, $value, array &$config) - { - if (strpos($key, $this->nestSeparator) !== false) { - $pieces = explode($this->nestSeparator, $key, 2); - - if (!strlen($pieces[0]) || !strlen($pieces[1])) { - throw new Exception\RuntimeException(sprintf('Invalid key "%s"', $key)); - } elseif (!isset($config[$pieces[0]])) { - if ($pieces[0] === '0' && !empty($config)) { - $config = array($pieces[0] => $config); - } else { - $config[$pieces[0]] = array(); - } - } elseif (!is_array($config[$pieces[0]])) { - throw new Exception\RuntimeException( - sprintf('Cannot create sub-key for "%s", as key already exists', $pieces[0]) - ); - } - - $this->processKey($pieces[1], $value, $config[$pieces[0]]); - } else { - if ($key === '@include') { - if ($this->directory === null) { - throw new Exception\RuntimeException('Cannot process @include statement for a string config'); - } - - $reader = clone $this; - $include = $reader->fromFile($this->directory . '/' . $value); - $config = array_replace_recursive($config, $include); - } else { - $config[$key] = $value; - } - } - } -} diff --git a/library/Zend/Config/Reader/JavaProperties.php b/library/Zend/Config/Reader/JavaProperties.php deleted file mode 100755 index 965bd3c80..000000000 --- a/library/Zend/Config/Reader/JavaProperties.php +++ /dev/null @@ -1,138 +0,0 @@ -directory = dirname($filename); - - $config = $this->parse(file_get_contents($filename)); - - return $this->process($config); - } - - /** - * fromString(): defined by Reader interface. - * - * @see ReaderInterface::fromString() - * @param string $string - * @return array - * @throws Exception\RuntimeException if an @include key is found - */ - public function fromString($string) - { - if (empty($string)) { - return array(); - } - - $this->directory = null; - - $config = $this->parse($string); - - return $this->process($config); - } - - /** - * Process the array for @include - * - * @param array $data - * @return array - * @throws Exception\RuntimeException if an @include key is found - */ - protected function process(array $data) - { - foreach ($data as $key => $value) { - if (trim($key) === '@include') { - if ($this->directory === null) { - throw new Exception\RuntimeException('Cannot process @include statement for a string'); - } - $reader = clone $this; - unset($data[$key]); - $data = array_replace_recursive($data, $reader->fromFile($this->directory . '/' . $value)); - } - } - return $data; - } - - /** - * Parse Java-style properties string - * - * @todo Support use of the equals sign "key=value" as key-value delimiter - * @todo Ignore whitespace that precedes text past the first line of multiline values - * - * @param string $string - * @return array - */ - protected function parse($string) - { - $result = array(); - $lines = explode("\n", $string); - $key = ""; - $isWaitingOtherLine = false; - foreach ($lines as $i => $line) { - // Ignore empty lines and commented lines - if (empty($line) - || (!$isWaitingOtherLine && strpos($line, "#") === 0) - || (!$isWaitingOtherLine && strpos($line, "!") === 0)) { - continue; - } - - // Add a new key-value pair or append value to a previous pair - if (!$isWaitingOtherLine) { - $key = substr($line, 0, strpos($line, ':')); - $value = substr($line, strpos($line, ':') + 1, strlen($line)); - } else { - $value .= $line; - } - - // Check if ends with single '\' (indicating another line is expected) - if (strrpos($value, "\\") === strlen($value) - strlen("\\")) { - $value = substr($value, 0, strlen($value) - 1); - $isWaitingOtherLine = true; - } else { - $isWaitingOtherLine = false; - } - - $result[$key] = stripslashes($value); - unset($lines[$i]); - } - - return $result; - } -} diff --git a/library/Zend/Config/Reader/Json.php b/library/Zend/Config/Reader/Json.php deleted file mode 100755 index 407e2aafa..000000000 --- a/library/Zend/Config/Reader/Json.php +++ /dev/null @@ -1,105 +0,0 @@ -directory = dirname($filename); - - try { - $config = JsonFormat::decode(file_get_contents($filename), JsonFormat::TYPE_ARRAY); - } catch (JsonException\RuntimeException $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - - return $this->process($config); - } - - /** - * fromString(): defined by Reader interface. - * - * @see ReaderInterface::fromString() - * @param string $string - * @return array|bool - * @throws Exception\RuntimeException - */ - public function fromString($string) - { - if (empty($string)) { - return array(); - } - - $this->directory = null; - - try { - $config = JsonFormat::decode($string, JsonFormat::TYPE_ARRAY); - } catch (JsonException\RuntimeException $e) { - throw new Exception\RuntimeException($e->getMessage()); - } - - return $this->process($config); - } - - /** - * Process the array for @include - * - * @param array $data - * @return array - * @throws Exception\RuntimeException - */ - protected function process(array $data) - { - foreach ($data as $key => $value) { - if (is_array($value)) { - $data[$key] = $this->process($value); - } - if (trim($key) === '@include') { - if ($this->directory === null) { - throw new Exception\RuntimeException('Cannot process @include statement for a JSON string'); - } - $reader = clone $this; - unset($data[$key]); - $data = array_replace_recursive($data, $reader->fromFile($this->directory . '/' . $value)); - } - } - return $data; - } -} diff --git a/library/Zend/Config/Reader/ReaderInterface.php b/library/Zend/Config/Reader/ReaderInterface.php deleted file mode 100755 index 0393fe052..000000000 --- a/library/Zend/Config/Reader/ReaderInterface.php +++ /dev/null @@ -1,29 +0,0 @@ -reader = new XMLReader(); - $this->reader->open($filename, null, LIBXML_XINCLUDE); - - $this->directory = dirname($filename); - - set_error_handler( - function ($error, $message = '', $file = '', $line = 0) use ($filename) { - throw new Exception\RuntimeException( - sprintf('Error reading XML file "%s": %s', $filename, $message), - $error - ); - }, - E_WARNING - ); - $return = $this->process(); - restore_error_handler(); - - return $return; - } - - /** - * fromString(): defined by Reader interface. - * - * @see ReaderInterface::fromString() - * @param string $string - * @return array|bool - * @throws Exception\RuntimeException - */ - public function fromString($string) - { - if (empty($string)) { - return array(); - } - $this->reader = new XMLReader(); - - $this->reader->xml($string, null, LIBXML_XINCLUDE); - - $this->directory = null; - - set_error_handler( - function ($error, $message = '', $file = '', $line = 0) { - throw new Exception\RuntimeException( - sprintf('Error reading XML string: %s', $message), - $error - ); - }, - E_WARNING - ); - $return = $this->process(); - restore_error_handler(); - - return $return; - } - - /** - * Process data from the created XMLReader. - * - * @return array - */ - protected function process() - { - return $this->processNextElement(); - } - - /** - * Process the next inner element. - * - * @return mixed - */ - protected function processNextElement() - { - $children = array(); - $text = ''; - - while ($this->reader->read()) { - if ($this->reader->nodeType === XMLReader::ELEMENT) { - if ($this->reader->depth === 0) { - return $this->processNextElement(); - } - - $attributes = $this->getAttributes(); - $name = $this->reader->name; - - if ($this->reader->isEmptyElement) { - $child = array(); - } else { - $child = $this->processNextElement(); - } - - if ($attributes) { - if (is_string($child)) { - $child = array('_' => $child); - } - - if (! is_array($child) ) { - $child = array(); - } - - $child = array_merge($child, $attributes); - } - - if (isset($children[$name])) { - if (!is_array($children[$name]) || !array_key_exists(0, $children[$name])) { - $children[$name] = array($children[$name]); - } - - $children[$name][] = $child; - } else { - $children[$name] = $child; - } - } elseif ($this->reader->nodeType === XMLReader::END_ELEMENT) { - break; - } elseif (in_array($this->reader->nodeType, $this->textNodes)) { - $text .= $this->reader->value; - } - } - - return $children ?: $text; - } - - /** - * Get all attributes on the current node. - * - * @return array - */ - protected function getAttributes() - { - $attributes = array(); - - if ($this->reader->hasAttributes) { - while ($this->reader->moveToNextAttribute()) { - $attributes[$this->reader->localName] = $this->reader->value; - } - - $this->reader->moveToElement(); - } - - return $attributes; - } -} diff --git a/library/Zend/Config/Reader/Yaml.php b/library/Zend/Config/Reader/Yaml.php deleted file mode 100755 index 709b8b8a6..000000000 --- a/library/Zend/Config/Reader/Yaml.php +++ /dev/null @@ -1,159 +0,0 @@ -setYamlDecoder($yamlDecoder); - } else { - if (function_exists('yaml_parse')) { - $this->setYamlDecoder('yaml_parse'); - } - } - } - - /** - * Set callback for decoding YAML - * - * @param string|callable $yamlDecoder the decoder to set - * @return Yaml - * @throws Exception\RuntimeException - */ - public function setYamlDecoder($yamlDecoder) - { - if (!is_callable($yamlDecoder)) { - throw new Exception\RuntimeException( - 'Invalid parameter to setYamlDecoder() - must be callable' - ); - } - $this->yamlDecoder = $yamlDecoder; - return $this; - } - - /** - * Get callback for decoding YAML - * - * @return callable - */ - public function getYamlDecoder() - { - return $this->yamlDecoder; - } - - /** - * fromFile(): defined by Reader interface. - * - * @see ReaderInterface::fromFile() - * @param string $filename - * @return array - * @throws Exception\RuntimeException - */ - public function fromFile($filename) - { - if (!is_file($filename) || !is_readable($filename)) { - throw new Exception\RuntimeException(sprintf( - "File '%s' doesn't exist or not readable", - $filename - )); - } - - if (null === $this->getYamlDecoder()) { - throw new Exception\RuntimeException("You didn't specify a Yaml callback decoder"); - } - - $this->directory = dirname($filename); - - $config = call_user_func($this->getYamlDecoder(), file_get_contents($filename)); - if (null === $config) { - throw new Exception\RuntimeException("Error parsing YAML data"); - } - - return $this->process($config); - } - - /** - * fromString(): defined by Reader interface. - * - * @see ReaderInterface::fromString() - * @param string $string - * @return array|bool - * @throws Exception\RuntimeException - */ - public function fromString($string) - { - if (null === $this->getYamlDecoder()) { - throw new Exception\RuntimeException("You didn't specify a Yaml callback decoder"); - } - if (empty($string)) { - return array(); - } - - $this->directory = null; - - $config = call_user_func($this->getYamlDecoder(), $string); - if (null === $config) { - throw new Exception\RuntimeException("Error parsing YAML data"); - } - - return $this->process($config); - } - - /** - * Process the array for @include - * - * @param array $data - * @return array - * @throws Exception\RuntimeException - */ - protected function process(array $data) - { - foreach ($data as $key => $value) { - if (is_array($value)) { - $data[$key] = $this->process($value); - } - if (trim($key) === '@include') { - if ($this->directory === null) { - throw new Exception\RuntimeException('Cannot process @include statement for a json string'); - } - $reader = clone $this; - unset($data[$key]); - $data = array_replace_recursive($data, $reader->fromFile($this->directory . '/' . $value)); - } - } - return $data; - } -} diff --git a/library/Zend/Config/ReaderPluginManager.php b/library/Zend/Config/ReaderPluginManager.php deleted file mode 100755 index 3e74a5640..000000000 --- a/library/Zend/Config/ReaderPluginManager.php +++ /dev/null @@ -1,49 +0,0 @@ - 'Zend\Config\Reader\Ini', - 'json' => 'Zend\Config\Reader\Json', - 'xml' => 'Zend\Config\Reader\Xml', - 'yaml' => 'Zend\Config\Reader\Yaml', - ); - - /** - * Validate the plugin - * Checks that the reader loaded is an instance of Reader\ReaderInterface. - * - * @param Reader\ReaderInterface $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Reader\ReaderInterface) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Reader\ReaderInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Config/Writer/AbstractWriter.php b/library/Zend/Config/Writer/AbstractWriter.php deleted file mode 100755 index a02111f7d..000000000 --- a/library/Zend/Config/Writer/AbstractWriter.php +++ /dev/null @@ -1,84 +0,0 @@ -toString($config), $flags); - } catch (\Exception $e) { - restore_error_handler(); - throw $e; - } - - restore_error_handler(); - } - - /** - * toString(): defined by Writer interface. - * - * @see WriterInterface::toString() - * @param mixed $config - * @return string - * @throws Exception\InvalidArgumentException - */ - public function toString($config) - { - if ($config instanceof Traversable) { - $config = ArrayUtils::iteratorToArray($config); - } elseif (!is_array($config)) { - throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable config'); - } - - return $this->processConfig($config); - } - - /** - * @param array $config - * @return string - */ - abstract protected function processConfig(array $config); -} diff --git a/library/Zend/Config/Writer/Ini.php b/library/Zend/Config/Writer/Ini.php deleted file mode 100755 index 9244f73e6..000000000 --- a/library/Zend/Config/Writer/Ini.php +++ /dev/null @@ -1,183 +0,0 @@ -nestSeparator = $separator; - return $this; - } - - /** - * Get nest separator. - * - * @return string - */ - public function getNestSeparator() - { - return $this->nestSeparator; - } - - /** - * Set if rendering should occur without sections or not. - * - * If set to true, the INI file is rendered without sections completely - * into the global namespace of the INI file. - * - * @param bool $withoutSections - * @return Ini - */ - public function setRenderWithoutSectionsFlags($withoutSections) - { - $this->renderWithoutSections = (bool) $withoutSections; - return $this; - } - - /** - * Return whether the writer should render without sections. - * - * @return bool - */ - public function shouldRenderWithoutSections() - { - return $this->renderWithoutSections; - } - - /** - * processConfig(): defined by AbstractWriter. - * - * @param array $config - * @return string - */ - public function processConfig(array $config) - { - $iniString = ''; - - if ($this->shouldRenderWithoutSections()) { - $iniString .= $this->addBranch($config); - } else { - $config = $this->sortRootElements($config); - - foreach ($config as $sectionName => $data) { - if (!is_array($data)) { - $iniString .= $sectionName - . ' = ' - . $this->prepareValue($data) - . "\n"; - } else { - $iniString .= '[' . $sectionName . ']' . "\n" - . $this->addBranch($data) - . "\n"; - } - } - } - - return $iniString; - } - - /** - * Add a branch to an INI string recursively. - * - * @param array $config - * @param array $parents - * @return string - */ - protected function addBranch(array $config, $parents = array()) - { - $iniString = ''; - - foreach ($config as $key => $value) { - $group = array_merge($parents, array($key)); - - if (is_array($value)) { - $iniString .= $this->addBranch($value, $group); - } else { - $iniString .= implode($this->nestSeparator, $group) - . ' = ' - . $this->prepareValue($value) - . "\n"; - } - } - - return $iniString; - } - - /** - * Prepare a value for INI. - * - * @param mixed $value - * @return string - * @throws Exception\RuntimeException - */ - protected function prepareValue($value) - { - if (is_int($value) || is_float($value)) { - return $value; - } elseif (is_bool($value)) { - return ($value ? 'true' : 'false'); - } elseif (false === strpos($value, '"')) { - return '"' . $value . '"'; - } else { - throw new Exception\RuntimeException('Value can not contain double quotes'); - } - } - - /** - * Root elements that are not assigned to any section needs to be on the - * top of config. - * - * @param array $config - * @return array - */ - protected function sortRootElements(array $config) - { - $sections = array(); - - // Remove sections from config array. - foreach ($config as $key => $value) { - if (is_array($value)) { - $sections[$key] = $value; - unset($config[$key]); - } - } - - // Read sections to the end. - foreach ($sections as $key => $value) { - $config[$key] = $value; - } - - return $config; - } -} diff --git a/library/Zend/Config/Writer/Json.php b/library/Zend/Config/Writer/Json.php deleted file mode 100755 index 04548495b..000000000 --- a/library/Zend/Config/Writer/Json.php +++ /dev/null @@ -1,26 +0,0 @@ - $this->useBracketArraySyntax ? '[' : 'array(', - 'close' => $this->useBracketArraySyntax ? ']' : ')' - ); - - return "processIndented($config, $arraySyntax) . - $arraySyntax['close'] . ";\n"; - } - - /** - * Sets whether or not to use the PHP 5.4+ "[]" array syntax. - * - * @param bool $value - * @return self - */ - public function setUseBracketArraySyntax($value) - { - $this->useBracketArraySyntax = $value; - return $this; - } - - /** - * toFile(): defined by Writer interface. - * - * @see WriterInterface::toFile() - * @param string $filename - * @param mixed $config - * @param bool $exclusiveLock - * @return void - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public function toFile($filename, $config, $exclusiveLock = true) - { - if (empty($filename)) { - throw new Exception\InvalidArgumentException('No file name specified'); - } - - $flags = 0; - if ($exclusiveLock) { - $flags |= LOCK_EX; - } - - set_error_handler( - function ($error, $message = '', $file = '', $line = 0) use ($filename) { - throw new Exception\RuntimeException( - sprintf('Error writing to "%s": %s', $filename, $message), - $error - ); - }, - E_WARNING - ); - - try { - // for Windows, paths are escaped. - $dirname = str_replace('\\', '\\\\', dirname($filename)); - - $string = $this->toString($config); - $string = str_replace("'" . $dirname, "__DIR__ . '", $string); - - file_put_contents($filename, $string, $flags); - } catch (\Exception $e) { - restore_error_handler(); - throw $e; - } - - restore_error_handler(); - } - - /** - * Recursively processes a PHP config array structure into a readable format. - * - * @param array $config - * @param array $arraySyntax - * @param int $indentLevel - * @return string - */ - protected function processIndented(array $config, array $arraySyntax, &$indentLevel = 1) - { - $arrayString = ""; - - foreach ($config as $key => $value) { - $arrayString .= str_repeat(self::INDENT_STRING, $indentLevel); - $arrayString .= (is_int($key) ? $key : "'" . addslashes($key) . "'") . ' => '; - - if (is_array($value)) { - if ($value === array()) { - $arrayString .= $arraySyntax['open'] . $arraySyntax['close'] . ",\n"; - } else { - $indentLevel++; - $arrayString .= $arraySyntax['open'] . "\n" - . $this->processIndented($value, $arraySyntax, $indentLevel) - . str_repeat(self::INDENT_STRING, --$indentLevel) . $arraySyntax['close'] . ",\n"; - } - } elseif (is_object($value) || is_string($value)) { - $arrayString .= var_export($value, true) . ",\n"; - } elseif (is_bool($value)) { - $arrayString .= ($value ? 'true' : 'false') . ",\n"; - } elseif ($value === null) { - $arrayString .= "null,\n"; - } else { - $arrayString .= $value . ",\n"; - } - } - - return $arrayString; - } -} diff --git a/library/Zend/Config/Writer/WriterInterface.php b/library/Zend/Config/Writer/WriterInterface.php deleted file mode 100755 index afbecd104..000000000 --- a/library/Zend/Config/Writer/WriterInterface.php +++ /dev/null @@ -1,31 +0,0 @@ -openMemory(); - $writer->setIndent(true); - $writer->setIndentString(str_repeat(' ', 4)); - - $writer->startDocument('1.0', 'UTF-8'); - $writer->startElement('zend-config'); - - foreach ($config as $sectionName => $data) { - if (!is_array($data)) { - $writer->writeElement($sectionName, (string) $data); - } else { - $this->addBranch($sectionName, $data, $writer); - } - } - - $writer->endElement(); - $writer->endDocument(); - - return $writer->outputMemory(); - } - - /** - * Add a branch to an XML object recursively. - * - * @param string $branchName - * @param array $config - * @param XMLWriter $writer - * @return void - * @throws Exception\RuntimeException - */ - protected function addBranch($branchName, array $config, XMLWriter $writer) - { - $branchType = null; - - foreach ($config as $key => $value) { - if ($branchType === null) { - if (is_numeric($key)) { - $branchType = 'numeric'; - } else { - $writer->startElement($branchName); - $branchType = 'string'; - } - } elseif ($branchType !== (is_numeric($key) ? 'numeric' : 'string')) { - throw new Exception\RuntimeException('Mixing of string and numeric keys is not allowed'); - } - - if ($branchType === 'numeric') { - if (is_array($value)) { - $this->addBranch($value, $value, $writer); - } else { - $writer->writeElement($branchName, (string) $value); - } - } else { - if (is_array($value)) { - $this->addBranch($key, $value, $writer); - } else { - $writer->writeElement($key, (string) $value); - } - } - } - - if ($branchType === 'string') { - $writer->endElement(); - } - } -} diff --git a/library/Zend/Config/Writer/Yaml.php b/library/Zend/Config/Writer/Yaml.php deleted file mode 100755 index f741ad677..000000000 --- a/library/Zend/Config/Writer/Yaml.php +++ /dev/null @@ -1,85 +0,0 @@ -setYamlEncoder($yamlEncoder); - } else { - if (function_exists('yaml_emit')) { - $this->setYamlEncoder('yaml_emit'); - } - } - } - - /** - * Get callback for decoding YAML - * - * @return callable - */ - public function getYamlEncoder() - { - return $this->yamlEncoder; - } - - /** - * Set callback for decoding YAML - * - * @param callable $yamlEncoder the decoder to set - * @return Yaml - * @throws Exception\InvalidArgumentException - */ - public function setYamlEncoder($yamlEncoder) - { - if (!is_callable($yamlEncoder)) { - throw new Exception\InvalidArgumentException('Invalid parameter to setYamlEncoder() - must be callable'); - } - $this->yamlEncoder = $yamlEncoder; - return $this; - } - - /** - * processConfig(): defined by AbstractWriter. - * - * @param array $config - * @return string - * @throws Exception\RuntimeException - */ - public function processConfig(array $config) - { - if (null === $this->getYamlEncoder()) { - throw new Exception\RuntimeException("You didn't specify a Yaml callback encoder"); - } - - $config = call_user_func($this->getYamlEncoder(), $config); - if (null === $config) { - throw new Exception\RuntimeException("Error generating YAML data"); - } - - return $config; - } -} diff --git a/library/Zend/Config/WriterPluginManager.php b/library/Zend/Config/WriterPluginManager.php deleted file mode 100755 index c70e4415c..000000000 --- a/library/Zend/Config/WriterPluginManager.php +++ /dev/null @@ -1,36 +0,0 @@ - 'Zend\Config\Writer\Ini', - 'json' => 'Zend\Config\Writer\Json', - 'php' => 'Zend\Config\Writer\PhpArray', - 'yaml' => 'Zend\Config\Writer\Yaml', - 'xml' => 'Zend\Config\Writer\Xml', - ); - - public function validatePlugin($plugin) - { - if ($plugin instanceof Writer\AbstractWriter) { - return; - } - - $type = is_object($plugin) ? get_class($plugin) : gettype($plugin); - - throw new Exception\InvalidArgumentException( - "Plugin of type {$type} is invalid. Plugin must extend ". __NAMESPACE__ . '\Writer\AbstractWriter' - ); - } -} diff --git a/library/Zend/Config/composer.json b/library/Zend/Config/composer.json deleted file mode 100755 index 6ea7fa11e..000000000 --- a/library/Zend/Config/composer.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "zendframework/zend-config", - "description": "provides a nested object property based user interface for accessing this configuration data within application code", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "config" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Config\\": "" - } - }, - "target-dir": "Zend/Config", - "require": { - "php": ">=5.3.23", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-filter": "self.version", - "zendframework/zend-i18n": "self.version", - "zendframework/zend-json": "self.version", - "zendframework/zend-servicemanager": "self.version" - }, - "suggest": { - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-i18n": "Zend\\I18n component", - "zendframework/zend-json": "Zend\\Json to use the Json reader or writer classes", - "zendframework/zend-servicemanager": "Zend\\ServiceManager for use with the Config Factory to retrieve reader and writer instances" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Console/Adapter/AbstractAdapter.php b/library/Zend/Console/Adapter/AbstractAdapter.php deleted file mode 100755 index 49718034f..000000000 --- a/library/Zend/Console/Adapter/AbstractAdapter.php +++ /dev/null @@ -1,561 +0,0 @@ -encodeText($text); - - if ($color !== null || $bgColor !== null) { - echo $this->colorize($text, $color, $bgColor); - } else { - echo $text; - } - } - - /** - * Alias for write() - * - * @param string $text - * @param null|int $color - * @param null|int $bgColor - */ - public function writeText($text, $color = null, $bgColor = null) - { - return $this->write($text, $color, $bgColor); - } - - /** - * Write a single line of text to console and advance cursor to the next line. - * - * @param string $text - * @param null|int $color - * @param null|int $bgColor - */ - public function writeLine($text = "", $color = null, $bgColor = null) - { - $this->write($text . PHP_EOL, $color, $bgColor); - } - - /** - * Write a piece of text at the coordinates of $x and $y - * - * - * @param string $text Text to write - * @param int $x Console X coordinate (column) - * @param int $y Console Y coordinate (row) - * @param null|int $color - * @param null|int $bgColor - */ - public function writeAt($text, $x, $y, $color = null, $bgColor = null) - { - $this->setPos($x, $y); - $this->write($text, $color, $bgColor); - } - - /** - * Write a box at the specified coordinates. - * If X or Y coordinate value is negative, it will be calculated as the distance from far right or bottom edge - * of the console (respectively). - * - * @param int $x1 Top-left corner X coordinate (column) - * @param int $y1 Top-left corner Y coordinate (row) - * @param int $x2 Bottom-right corner X coordinate (column) - * @param int $y2 Bottom-right corner Y coordinate (row) - * @param int $lineStyle (optional) Box border style. - * @param int $fillStyle (optional) Box fill style or a single character to fill it with. - * @param int $color (optional) Foreground color - * @param int $bgColor (optional) Background color - * @param null|int $fillColor (optional) Foreground color of box fill - * @param null|int $fillBgColor (optional) Background color of box fill - * @throws Exception\BadMethodCallException if coordinates are invalid - */ - public function writeBox( - $x1, - $y1, - $x2, - $y2, - $lineStyle = self::LINE_SINGLE, - $fillStyle = self::FILL_NONE, - $color = null, - $bgColor = null, - $fillColor = null, - $fillBgColor = null - ) { - // Sanitize coordinates - $x1 = (int) $x1; - $y1 = (int) $y1; - $x2 = (int) $x2; - $y2 = (int) $y2; - - // Translate negative coordinates - if ($x2 < 0) { - $x2 = $this->getWidth() - $x2; - } - - if ($y2 < 0) { - $y2 = $this->getHeight() - $y2; - } - - // Validate coordinates - if ($x1 < 0 - || $y1 < 0 - || $x2 < $x1 - || $y2 < $y1 - ) { - throw new Exception\BadMethodCallException('Supplied X,Y coordinates are invalid.'); - } - - // Determine charset and dimensions - $charset = $this->getCharset(); - $width = $x2 - $x1 + 1; - $height = $y2 - $y1 + 1; - - if ($width <= 2) { - $lineStyle = static::LINE_NONE; - } - - // Activate line drawing - $this->write($charset::ACTIVATE); - - // Draw horizontal lines - if ($lineStyle !== static::LINE_NONE) { - switch ($lineStyle) { - case static::LINE_SINGLE: - $lineChar = $charset::LINE_SINGLE_EW; - break; - - case static::LINE_DOUBLE: - $lineChar = $charset::LINE_DOUBLE_EW; - break; - - case static::LINE_BLOCK: - default: - $lineChar = $charset::LINE_BLOCK_EW; - break; - } - - $this->setPos($x1 + 1, $y1); - $this->write(str_repeat($lineChar, $width - 2), $color, $bgColor); - $this->setPos($x1 + 1, $y2); - $this->write(str_repeat($lineChar, $width - 2), $color, $bgColor); - } - - // Draw vertical lines and fill - if (is_numeric($fillStyle) - && $fillStyle !== static::FILL_NONE) { - switch ($fillStyle) { - case static::FILL_SHADE_LIGHT: - $fillChar = $charset::SHADE_LIGHT; - break; - case static::FILL_SHADE_MEDIUM: - $fillChar = $charset::SHADE_MEDIUM; - break; - case static::FILL_SHADE_DARK: - $fillChar = $charset::SHADE_DARK; - break; - case static::FILL_BLOCK: - default: - $fillChar = $charset::BLOCK; - break; - } - } elseif ($fillStyle) { - $fillChar = StringUtils::getWrapper()->substr($fillStyle, 0, 1); - } else { - $fillChar = ' '; - } - - if ($lineStyle === static::LINE_NONE) { - for ($y = $y1; $y <= $y2; $y++) { - $this->setPos($x1, $y); - $this->write(str_repeat($fillChar, $width), $fillColor, $fillBgColor); - } - } else { - switch ($lineStyle) { - case static::LINE_DOUBLE: - $lineChar = $charset::LINE_DOUBLE_NS; - break; - case static::LINE_BLOCK: - $lineChar = $charset::LINE_BLOCK_NS; - break; - case static::LINE_SINGLE: - default: - $lineChar = $charset::LINE_SINGLE_NS; - break; - } - - for ($y = $y1 + 1; $y < $y2; $y++) { - $this->setPos($x1, $y); - $this->write($lineChar, $color, $bgColor); - $this->write(str_repeat($fillChar, $width - 2), $fillColor, $fillBgColor); - $this->write($lineChar, $color, $bgColor); - } - } - - // Draw corners - if ($lineStyle !== static::LINE_NONE) { - if ($color !== null) { - $this->setColor($color); - } - if ($bgColor !== null) { - $this->setBgColor($bgColor); - } - if ($lineStyle === static::LINE_SINGLE) { - $this->writeAt($charset::LINE_SINGLE_NW, $x1, $y1); - $this->writeAt($charset::LINE_SINGLE_NE, $x2, $y1); - $this->writeAt($charset::LINE_SINGLE_SE, $x2, $y2); - $this->writeAt($charset::LINE_SINGLE_SW, $x1, $y2); - } elseif ($lineStyle === static::LINE_DOUBLE) { - $this->writeAt($charset::LINE_DOUBLE_NW, $x1, $y1); - $this->writeAt($charset::LINE_DOUBLE_NE, $x2, $y1); - $this->writeAt($charset::LINE_DOUBLE_SE, $x2, $y2); - $this->writeAt($charset::LINE_DOUBLE_SW, $x1, $y2); - } elseif ($lineStyle === static::LINE_BLOCK) { - $this->writeAt($charset::LINE_BLOCK_NW, $x1, $y1); - $this->writeAt($charset::LINE_BLOCK_NE, $x2, $y1); - $this->writeAt($charset::LINE_BLOCK_SE, $x2, $y2); - $this->writeAt($charset::LINE_BLOCK_SW, $x1, $y2); - } - } - - // Deactivate line drawing and reset colors - $this->write($charset::DEACTIVATE); - $this->resetColor(); - } - - /** - * Write a block of text at the given coordinates, matching the supplied width and height. - * In case a line of text does not fit desired width, it will be wrapped to the next line. - * In case the whole text does not fit in desired height, it will be truncated. - * - * @param string $text Text to write - * @param int $width Maximum block width. Negative value means distance from right edge. - * @param int|null $height Maximum block height. Negative value means distance from bottom edge. - * @param int $x Block X coordinate (column) - * @param int $y Block Y coordinate (row) - * @param null|int $color (optional) Text color - * @param null|int $bgColor (optional) Text background color - * @throws Exception\InvalidArgumentException - */ - public function writeTextBlock( - $text, - $width, - $height = null, - $x = 0, - $y = 0, - $color = null, - $bgColor = null - ) { - if ($x < 0 || $y < 0) { - throw new Exception\InvalidArgumentException('Supplied X,Y coordinates are invalid.'); - } - - if ($width < 1) { - throw new Exception\InvalidArgumentException('Invalid width supplied.'); - } - - if (null !== $height && $height < 1) { - throw new Exception\InvalidArgumentException('Invalid height supplied.'); - } - - // ensure the text is not wider than the width - if (strlen($text) <= $width) { - // just write the line at the spec'd position - $this->setPos($x, $y); - $this->write($text, $color, $bgColor); - return; - } - - $text = wordwrap($text, $width, PHP_EOL, true); - - // convert to array of lines - $lines = explode(PHP_EOL, $text); - - // truncate if height was specified - if (null !== $height && count($lines) > $height) { - $lines = array_slice($lines, 0, $height); - } - - // write each line - $curY = $y; - foreach ($lines as $line) { - $this->setPos($x, $curY); - $this->write($line, $color, $bgColor); - $curY++;//next line - } - } - - /** - * Determine and return current console width. - * - * @return int - */ - public function getWidth() - { - return 80; - } - - /** - * Determine and return current console height. - * - * @return int - */ - public function getHeight() - { - return 25; - } - - /** - * Determine and return current console width and height. - * - * @return int[] array($width, $height) - */ - public function getSize() - { - return array( - $this->getWidth(), - $this->getHeight(), - ); - } - - /** - * Check if console is UTF-8 compatible - * - * @return bool - */ - public function isUtf8() - { - return true; - } - - /** - * Set cursor position - * - * @param int $x - * @param int $y - */ - public function setPos($x, $y) - { - } - - /** - * Show console cursor - */ - public function showCursor() - { - } - - /** - * Hide console cursor - */ - public function hideCursor() - { - } - - /** - * Return current console window title. - * - * @return string - */ - public function getTitle() - { - return ''; - } - - /** - * Prepare a string that will be rendered in color. - * - * @param string $string - * @param int $color - * @param null|int $bgColor - * @return string - */ - public function colorize($string, $color = null, $bgColor = null) - { - return $string; - } - - /** - * Change current drawing color. - * - * @param int $color - */ - public function setColor($color) - { - } - - /** - * Change current drawing background color - * - * @param int $color - */ - public function setBgColor($color) - { - } - - /** - * Reset color to console default. - */ - public function resetColor() - { - } - - /** - * Set Console charset to use. - * - * @param Charset\CharsetInterface $charset - */ - public function setCharset(Charset\CharsetInterface $charset) - { - $this->charset = $charset; - } - - /** - * Get charset currently in use by this adapter. - * - * @return Charset\CharsetInterface $charset - */ - public function getCharset() - { - if ($this->charset === null) { - $this->charset = $this->getDefaultCharset(); - } - - return $this->charset; - } - - /** - * @return Charset\Utf8 - */ - public function getDefaultCharset() - { - return new Charset\Utf8; - } - - /** - * Clear console screen - */ - public function clear() - { - echo "\f"; - } - - /** - * Clear line at cursor position - */ - public function clearLine() - { - echo "\r" . str_repeat(" ", $this->getWidth()) . "\r"; - } - - /** - * Clear console screen - */ - public function clearScreen() - { - return $this->clear(); - } - - /** - * Read a single line from the console input - * - * @param int $maxLength Maximum response length - * @return string - */ - public function readLine($maxLength = 2048) - { - $f = fopen('php://stdin', 'r'); - $line = stream_get_line($f, $maxLength, PHP_EOL); - fclose($f); - return rtrim($line, "\n\r"); - } - - /** - * Read a single character from the console input - * - * @param string|null $mask A list of allowed chars - * @return string - */ - public function readChar($mask = null) - { - $f = fopen('php://stdin', 'r'); - do { - $char = fread($f, 1); - } while ("" === $char || ($mask !== null && false === strstr($mask, $char))); - fclose($f); - return $char; - } - - /** - * Encode a text to match console encoding - * - * @param string $text - * @return string the encoding text - */ - public function encodeText($text) - { - if ($this->isUtf8()) { - if (StringUtils::isValidUtf8($text)) { - return $text; - } - - return utf8_encode($text); - } - - if (StringUtils::isValidUtf8($text)) { - return utf8_decode($text); - } - - return $text; - } -} diff --git a/library/Zend/Console/Adapter/AdapterInterface.php b/library/Zend/Console/Adapter/AdapterInterface.php deleted file mode 100755 index 45407b80a..000000000 --- a/library/Zend/Console/Adapter/AdapterInterface.php +++ /dev/null @@ -1,264 +0,0 @@ - array( - Color::NORMAL => '22;39', - Color::RESET => '22;39', - - Color::BLACK => '0;30', - Color::RED => '0;31', - Color::GREEN => '0;32', - Color::YELLOW => '0;33', - Color::BLUE => '0;34', - Color::MAGENTA => '0;35', - Color::CYAN => '0;36', - Color::WHITE => '0;37', - - Color::GRAY => '1;30', - Color::LIGHT_RED => '1;31', - Color::LIGHT_GREEN => '1;32', - Color::LIGHT_YELLOW => '1;33', - Color::LIGHT_BLUE => '1;34', - Color::LIGHT_MAGENTA => '1;35', - Color::LIGHT_CYAN => '1;36', - Color::LIGHT_WHITE => '1;37', - ), - 'bg' => array( - Color::NORMAL => '0;49', - Color::RESET => '0;49', - - Color::BLACK => '40', - Color::RED => '41', - Color::GREEN => '42', - Color::YELLOW => '43', - Color::BLUE => '44', - Color::MAGENTA => '45', - Color::CYAN => '46', - Color::WHITE => '47', - - Color::GRAY => '40', - Color::LIGHT_RED => '41', - Color::LIGHT_GREEN => '42', - Color::LIGHT_YELLOW => '43', - Color::LIGHT_BLUE => '44', - Color::LIGHT_MAGENTA => '45', - Color::LIGHT_CYAN => '46', - Color::LIGHT_WHITE => '47', - ), - ); - - /** - * Last fetched TTY mode - * - * @var string|null - */ - protected $lastTTYMode = null; - - /** - * Write a single line of text to console and advance cursor to the next line. - * - * This override works around a bug in some terminals that cause the background color - * to fill the next line after EOL. To remedy this, we are sending the colored string with - * appropriate color reset sequences before sending EOL character. - * - * @link https://github.com/zendframework/zf2/issues/4167 - * @param string $text - * @param null|int $color - * @param null|int $bgColor - */ - public function writeLine($text = "", $color = null, $bgColor = null) - { - $this->write($text, $color, $bgColor); - $this->write(PHP_EOL); - } - - /** - * Determine and return current console width. - * - * @return int - */ - public function getWidth() - { - static $width; - if ($width > 0) { - return $width; - } - - /** - * Try to read env variable - */ - if (($result = getenv('COLUMNS')) !== false) { - return $width = (int) $result; - } - - /** - * Try to read console size from "tput" command - */ - $result = exec('tput cols', $output, $return); - if (!$return && is_numeric($result)) { - return $width = (int) $result; - } - - return $width = parent::getWidth(); - } - - /** - * Determine and return current console height. - * - * @return false|int - */ - public function getHeight() - { - static $height; - if ($height > 0) { - return $height; - } - - // Try to read env variable - if (($result = getenv('LINES')) !== false) { - return $height = (int) $result; - } - - // Try to read console size from "tput" command - $result = exec('tput lines', $output, $return); - if (!$return && is_numeric($result)) { - return $height = (int) $result; - } - - return $height = parent::getHeight(); - } - - /** - * Run a mode command and store results - * - * @return void - */ - protected function runModeCommand() - { - exec('mode', $output, $return); - if ($return || !count($output)) { - $this->modeResult = ''; - } else { - $this->modeResult = trim(implode('', $output)); - } - } - - /** - * Check if console is UTF-8 compatible - * - * @return bool - */ - public function isUtf8() - { - // Try to retrieve it from LANG env variable - if (($lang = getenv('LANG')) !== false) { - return stristr($lang, 'utf-8') || stristr($lang, 'utf8'); - } - - return false; - } - - /** - * Show console cursor - */ - public function showCursor() - { - echo "\x1b[?25h"; - } - - /** - * Hide console cursor - */ - public function hideCursor() - { - echo "\x1b[?25l"; - } - - /** - * Set cursor position - * @param int $x - * @param int $y - */ - public function setPos($x, $y) - { - echo "\x1b[" . $y . ';' . $x . 'f'; - } - - /** - * Prepare a string that will be rendered in color. - * - * @param string $string - * @param int $color - * @param null|int $bgColor - * @throws Exception\BadMethodCallException - * @return string - */ - public function colorize($string, $color = null, $bgColor = null) - { - $color = $this->getColorCode($color, 'fg'); - $bgColor = $this->getColorCode($bgColor, 'bg'); - return ($color !== null ? "\x1b[" . $color . 'm' : '') - . ($bgColor !== null ? "\x1b[" . $bgColor . 'm' : '') - . $string - . "\x1b[22;39m\x1b[0;49m"; - } - - /** - * Change current drawing color. - * - * @param int $color - * @throws Exception\BadMethodCallException - */ - public function setColor($color) - { - $color = $this->getColorCode($color, 'fg'); - echo "\x1b[" . $color . 'm'; - } - - /** - * Change current drawing background color - * - * @param int $bgColor - * @throws Exception\BadMethodCallException - */ - public function setBgColor($bgColor) - { - $bgColor = $this->getColorCode($bgColor, 'bg'); - echo "\x1b[" . ($bgColor) . 'm'; - } - - /** - * Reset color to console default. - */ - public function resetColor() - { - echo "\x1b[0;49m"; // reset bg color - echo "\x1b[22;39m"; // reset fg bold, bright and faint - echo "\x1b[25;39m"; // reset fg blink - echo "\x1b[24;39m"; // reset fg underline - } - - /** - * Set Console charset to use. - * - * @param Charset\CharsetInterface $charset - */ - public function setCharset(Charset\CharsetInterface $charset) - { - $this->charset = $charset; - } - - /** - * Get charset currently in use by this adapter. - * - * @return Charset\CharsetInterface $charset - */ - public function getCharset() - { - if ($this->charset === null) { - $this->charset = $this->getDefaultCharset(); - } - - return $this->charset; - } - - /** - * @return Charset\CharsetInterface - */ - public function getDefaultCharset() - { - if ($this->isUtf8()) { - return new Charset\Utf8; - } - return new Charset\DECSG(); - } - - /** - * Read a single character from the console input - * - * @param string|null $mask A list of allowed chars - * @return string - */ - public function readChar($mask = null) - { - $this->setTTYMode('-icanon -echo'); - - $stream = fopen('php://stdin', 'rb'); - do { - $char = fgetc($stream); - } while (strlen($char) !== 1 || ($mask !== null && false === strstr($mask, $char))); - fclose($stream); - - $this->restoreTTYMode(); - return $char; - } - - /** - * Reset color to console default. - */ - public function clear() - { - echo "\x1b[2J"; // reset bg color - $this->setPos(1, 1); // reset cursor position - } - - /** - * Restore TTY (Console) mode to previous value. - * - * @return void - */ - protected function restoreTTYMode() - { - if ($this->lastTTYMode === null) { - return; - } - - shell_exec('stty ' . escapeshellarg($this->lastTTYMode)); - } - - /** - * Change TTY (Console) mode - * - * @link http://en.wikipedia.org/wiki/Stty - * @param string $mode - */ - protected function setTTYMode($mode) - { - // Store last mode - $this->lastTTYMode = trim(`stty -g`); - - // Set new mode - shell_exec('stty '.escapeshellcmd($mode)); - } - - /** - * Get the final color code and throw exception on error - * - * @param null|int|Xterm256 $color - * @param string $type (optional) Foreground 'fg' or background 'bg'. - * @throws Exception\BadMethodCallException - * @return string - */ - protected function getColorCode($color, $type = 'fg') - { - if ($color instanceof Xterm256) { - $r = new ReflectionClass($color); - $code = $r->getStaticPropertyValue('color'); - if ($type == 'fg') { - $code = sprintf($code, $color::FOREGROUND); - } else { - $code = sprintf($code, $color::BACKGROUND); - } - return $code; - } - - if ($color !== null) { - if (!isset(static::$ansiColorMap[$type][$color])) { - throw new Exception\BadMethodCallException(sprintf( - 'Unknown color "%s". Please use one of the Zend\Console\ColorInterface constants ' - . 'or use Zend\Console\Color\Xterm256::calculate', - $color - )); - } - - return static::$ansiColorMap[$type][$color]; - } - - return null; - } -} diff --git a/library/Zend/Console/Adapter/Virtual.php b/library/Zend/Console/Adapter/Virtual.php deleted file mode 100755 index f1b1eb95e..000000000 --- a/library/Zend/Console/Adapter/Virtual.php +++ /dev/null @@ -1,176 +0,0 @@ - 0) { - return $width; - } - - // Try to read console size from "mode" command - if ($this->modeResult === null) { - $this->runProbeCommand(); - } - - if (preg_match('/Columns\:\s+(\d+)/', $this->modeResult, $matches)) { - $width = $matches[1]; - } else { - $width = parent::getWidth(); - } - - return $width; - } - - /** - * Determine and return current console height. - * - * @return false|int - */ - public function getHeight() - { - static $height; - if ($height > 0) { - return $height; - } - - // Try to read console size from "mode" command - if ($this->modeResult === null) { - $this->runProbeCommand(); - } - - if (preg_match('/Rows\:\s+(\d+)/', $this->modeResult, $matches)) { - $height = $matches[1]; - } else { - $height = parent::getHeight(); - } - - return $height; - } - - /** - * Run and store the results of mode command - * - * @return void - */ - protected function runProbeCommand() - { - exec('mode', $output, $return); - if ($return || !count($output)) { - $this->modeResult = ''; - } else { - $this->modeResult = trim(implode('', $output)); - } - } - - /** - * Check if console is UTF-8 compatible - * - * @return bool - */ - public function isUtf8() - { - // Try to read code page info from "mode" command - if ($this->modeResult === null) { - $this->runProbeCommand(); - } - - if (preg_match('/Code page\:\s+(\d+)/', $this->modeResult, $matches)) { - return (int) $matches[1] == 65001; - } - - return false; - } - - /** - * Return current console window title. - * - * @return string - */ - public function getTitle() - { - // Try to use powershell to retrieve console window title - exec('powershell -command "write $Host.UI.RawUI.WindowTitle"', $output, $result); - if ($result || !$output) { - return ''; - } - - return trim($output, "\r\n"); - } - - /** - * Set Console charset to use. - * - * @param Charset\CharsetInterface $charset - */ - public function setCharset(Charset\CharsetInterface $charset) - { - $this->charset = $charset; - } - - /** - * Get charset currently in use by this adapter. - * - * @return Charset\CharsetInterface $charset - */ - public function getCharset() - { - if ($this->charset === null) { - $this->charset = $this->getDefaultCharset(); - } - - return $this->charset; - } - - /** - * @return Charset\AsciiExtended - */ - public function getDefaultCharset() - { - return new Charset\AsciiExtended; - } - - /** - * Switch to UTF mode - * - * @return void - */ - protected function switchToUtf8() - { - shell_exec('mode con cp select=65001'); - } -} diff --git a/library/Zend/Console/Adapter/Windows.php b/library/Zend/Console/Adapter/Windows.php deleted file mode 100755 index c1bf8b734..000000000 --- a/library/Zend/Console/Adapter/Windows.php +++ /dev/null @@ -1,356 +0,0 @@ - 0) { - return $width; - } - - // Try to read console size from "mode" command - if ($this->probeResult === null) { - $this->runProbeCommand(); - } - - if (count($this->probeResult) && (int) $this->probeResult[0]) { - $width = (int) $this->probeResult[0]; - } else { - $width = parent::getWidth(); - } - - return $width; - } - - /** - * Determine and return current console height. - * - * @return int - */ - public function getHeight() - { - static $height; - if ($height > 0) { - return $height; - } - - // Try to read console size from "mode" command - if ($this->probeResult === null) { - $this->runProbeCommand(); - } - - if (count($this->probeResult) && (int) $this->probeResult[1]) { - $height = (int) $this->probeResult[1]; - } else { - $height = parent::getheight(); - } - - return $height; - } - - /** - * Probe for system capabilities and cache results - * - * Run a Windows Powershell command that determines parameters of console window. The command is fed through - * standard input (with echo) to prevent Powershell from creating a sub-thread and hanging PHP when run through - * a debugger/IDE. - * - * @return void - */ - protected function runProbeCommand() - { - exec( - 'echo $size = $Host.ui.rawui.windowsize; write $($size.width) $($size.height) | powershell -NonInteractive -NoProfile -NoLogo -OutputFormat Text -Command -', - $output, - $return - ); - if ($return || empty($output)) { - $this->probeResult = ''; - } else { - $this->probeResult = $output; - } - } - - /** - * Run and cache results of mode command - * - * @return void - */ - protected function runModeCommand() - { - exec('mode', $output, $return); - if ($return || !count($output)) { - $this->modeResult = ''; - } else { - $this->modeResult = trim(implode('', $output)); - } - } - - /** - * Check if console is UTF-8 compatible - * - * @return bool - */ - public function isUtf8() - { - // Try to read code page info from "mode" command - if ($this->modeResult === null) { - $this->runModeCommand(); - } - - if (preg_match('/Code page\:\s+(\d+)/', $this->modeResult, $matches)) { - return (int) $matches[1] == 65001; - } - - return false; - } - - /** - * Return current console window title. - * - * @return string - */ - public function getTitle() - { - // Try to use powershell to retrieve console window title - exec('powershell -command "write $Host.UI.RawUI.WindowTitle"', $output, $result); - if ($result || !$output) { - return ''; - } - - return trim($output, "\r\n"); - } - - /** - * Set Console charset to use. - * - * @param Charset\CharsetInterface $charset - */ - public function setCharset(Charset\CharsetInterface $charset) - { - $this->charset = $charset; - } - - /** - * Get charset currently in use by this adapter. - * - * @return Charset\CharsetInterface $charset - */ - public function getCharset() - { - if ($this->charset === null) { - $this->charset = $this->getDefaultCharset(); - } - - return $this->charset; - } - - /** - * @return Charset\AsciiExtended - */ - public function getDefaultCharset() - { - return new Charset\AsciiExtended; - } - - /** - * Switch to utf-8 encoding - * - * @return void - */ - protected function switchToUtf8() - { - shell_exec('mode con cp select=65001'); - } - - /** - * Clear console screen - */ - public function clear() - { - // Attempt to clear the screen using PowerShell command - exec("powershell -NonInteractive -NoProfile -NoLogo -OutputFormat Text -Command Clear-Host", $output, $return); - - if ($return) { - // Could not run powershell... fall back to filling the buffer with newlines - echo str_repeat("\r\n", $this->getHeight()); - } - } - - /** - * Clear line at cursor position - */ - public function clearLine() - { - echo "\r" . str_repeat(' ', $this->getWidth()) . "\r"; - } - - /** - * Read a single character from the console input - * - * @param string|null $mask A list of allowed chars - * @throws Exception\RuntimeException - * @return string - */ - public function readChar($mask = null) - { - // Decide if we can use `choice` tool - $useChoice = $mask !== null && preg_match('/^[a-zA-Z0-9]+$/D', $mask); - - if ($useChoice) { - // Use Windows 95+ "choice" command, which allows for reading a - // single character matching a mask, but is limited to lower ASCII - // range. - do { - exec('choice /n /cs /c:' . $mask, $output, $return); - if ($return == 255 || $return < 1 || $return > strlen($mask)) { - throw new Exception\RuntimeException('"choice" command failed to run. Are you using Windows XP or newer?'); - } - - // Fetch the char from mask - $char = substr($mask, $return - 1, 1); - } while ("" === $char || ($mask !== null && false === strstr($mask, $char))); - - return $char; - } - - // Try to use PowerShell, giving it console access. Because PowersShell - // interpreter can take a short while to load, we are emptying the - // whole keyboard buffer and picking the last key that has been pressed - // before or after PowerShell command has started. The ASCII code for - // that key is then converted to a character. - if ($mask === null) { - exec( - 'powershell -NonInteractive -NoProfile -NoLogo -OutputFormat Text -Command "' - . 'while ($Host.UI.RawUI.KeyAvailable) {$key = $Host.UI.RawUI.ReadKey(\'NoEcho,IncludeKeyDown\');}' - . 'write $key.VirtualKeyCode;' - . '"', - $result, - $return - ); - - // Retrieve char from the result. - $char = !empty($result) ? implode('', $result) : null; - - if (!empty($char) && !$return) { - // We have obtained an ASCII code, convert back to a char ... - $char = chr($char); - - // ... and return it... - return $char; - } - } else { - // Windows and DOS will return carriage-return char (ASCII 13) when - // the user presses [ENTER] key, but Console Adapter user might - // have provided a \n Newline (ASCII 10) in the mask, to allow [ENTER]. - // We are going to replace all CR with NL to conform. - $mask = strtr($mask, "\n", "\r"); - - // Prepare a list of ASCII codes from mask chars - $asciiMask = array_map(function ($char) { - return ord($char); - }, str_split($mask)); - $asciiMask = array_unique($asciiMask); - - // Char mask filtering is now handled by the PowerShell itself, - // because it's a much faster method than invoking PS interpreter - // after each mismatch. The command should return ASCII code of a - // matching key. - $result = $return = null; - - exec( - 'powershell -NonInteractive -NoProfile -NoLogo -OutputFormat Text -Command "' - . '[int[]] $mask = ' . join(',', $asciiMask) . ';' - . 'do {' - . '$key = $Host.UI.RawUI.ReadKey(\'NoEcho,IncludeKeyDown\').VirtualKeyCode;' - . '} while ( !($mask -contains $key) );' - . 'write $key;' - . '"', - $result, - $return - ); - - $char = !empty($result) ? trim(implode('', $result)) : null; - - if (!$return && $char && ($mask === null || in_array($char, $asciiMask))) { - // Normalize CR to LF - if ($char == 13) { - $char = 10; - } - - // Convert to a char - $char = chr($char); - - // ... and return it... - return $char; - } - } - - // Fall back to standard input, which on Windows does not allow reading - // a single character. This is a limitation of Windows streams - // implementation (not PHP) and this behavior cannot be changed with a - // command like "stty", known to POSIX systems. - $stream = fopen('php://stdin', 'rb'); - do { - $char = fgetc($stream); - $char = substr(trim($char), 0, 1); - } while (!$char || ($mask !== null && !stristr($mask, $char))); - fclose($stream); - - return $char; - } - - /** - * Read a single line from the console input. - * - * @param int $maxLength Maximum response length - * @return string - */ - public function readLine($maxLength = 2048) - { - $f = fopen('php://stdin', 'r'); - $line = rtrim(fread($f, $maxLength), "\r\n"); - fclose($f); - - return $line; - } -} diff --git a/library/Zend/Console/Adapter/WindowsAnsicon.php b/library/Zend/Console/Adapter/WindowsAnsicon.php deleted file mode 100755 index 3519a9e21..000000000 --- a/library/Zend/Console/Adapter/WindowsAnsicon.php +++ /dev/null @@ -1,302 +0,0 @@ - 0) { - return $width; - } - - // Try to read console size from ANSICON env var - if (preg_match('/\((\d+)x/', getenv('ANSICON'), $matches)) { - $width = $matches[1]; - } else { - $width = AbstractAdapter::getWidth(); - } - - return $width; - } - - /** - * Determine and return current console height. - * - * @return false|int - */ - public function getHeight() - { - static $height; - if ($height > 0) { - return $height; - } - - // Try to read console size from ANSICON env var - if (preg_match('/\(\d+x(\d+)/', getenv('ANSICON'), $matches)) { - $height = $matches[1]; - } else { - $height = AbstractAdapter::getHeight(); - } - return $height; - } - - /** - * Run and cache results of mode command - * - * @return void - */ - protected function runModeCommand() - { - exec('mode', $output, $return); - if ($return || !count($output)) { - $this->modeResult = ''; - } else { - $this->modeResult = trim(implode('', $output)); - } - } - - /** - * Check if console is UTF-8 compatible - * - * @return bool - */ - public function isUtf8() - { - // Try to read code page info from "mode" command - if ($this->modeResult === null) { - $this->runModeCommand(); - } - - if (preg_match('/Code page\:\s+(\d+)/', $this->modeResult, $matches)) { - return (int) $matches[1] == 65001; - } - - return false; - } - - /** - * Return current console window title. - * - * @return string - */ - public function getTitle() - { - // Try to use powershell to retrieve console window title - exec('powershell -command "write $Host.UI.RawUI.WindowTitle"', $output, $result); - if ($result || !$output) { - return ''; - } - - return trim($output, "\r\n"); - } - - /** - * Clear console screen - */ - public function clear() - { - echo chr(27) . '[1J' . chr(27) . '[u'; - } - - /** - * Clear line at cursor position - */ - public function clearLine() - { - echo chr(27) . '[1K'; - } - - /** - * Set Console charset to use. - * - * @param CharsetInterface $charset - */ - public function setCharset(CharsetInterface $charset) - { - $this->charset = $charset; - } - - /** - * Get charset currently in use by this adapter. - * - - * @return CharsetInterface $charset - */ - public function getCharset() - { - if ($this->charset === null) { - $this->charset = $this->getDefaultCharset(); - } - - return $this->charset; - } - - /** - * @return Charset\AsciiExtended - */ - public function getDefaultCharset() - { - return new Charset\AsciiExtended(); - } - - /** - * Read a single character from the console input - * - * @param string|null $mask A list of allowed chars - * @return string - * @throws Exception\RuntimeException - */ - public function readChar($mask = null) - { - // Decide if we can use `choice` tool - $useChoice = $mask !== null && preg_match('/^[a-zA-Z0-9]+$/D', $mask); - - if ($useChoice) { - // Use Windows 98+ "choice" command, which allows for reading a - // single character matching a mask, but is limited to lower ASCII - // range. - do { - exec('choice /n /cs /c:' . $mask, $output, $return); - if ($return == 255 || $return < 1 || $return > strlen($mask)) { - throw new Exception\RuntimeException('"choice" command failed to run. Are you using Windows XP or newer?'); - } - - // Fetch the char from mask - $char = substr($mask, $return - 1, 1); - } while ("" === $char || ($mask !== null && false === strstr($mask, $char))); - - return $char; - } - - // Try to use PowerShell, giving it console access. Because PowersShell - // interpreter can take a short while to load, we are emptying the - // whole keyboard buffer and picking the last key that has been pressed - // before or after PowerShell command has started. The ASCII code for - // that key is then converted to a character. - if ($mask === null) { - exec( - 'powershell -NonInteractive -NoProfile -NoLogo -OutputFormat Text -Command "' - . 'while ($Host.UI.RawUI.KeyAvailable) {$key = $Host.UI.RawUI.ReadKey(\'NoEcho,IncludeKeyDown\');}' - . 'write $key.VirtualKeyCode;' - . '"', - $result, - $return - ); - - // Retrieve char from the result. - $char = !empty($result) ? implode('', $result) : null; - - if (!empty($char) && !$return) { - // We have obtained an ASCII code, convert back to a char ... - $char = chr($char); - - // ... and return it... - return $char; - } - } else { - // Windows and DOS will return carriage-return char (ASCII 13) when - // the user presses [ENTER] key, but Console Adapter user might - // have provided a \n Newline (ASCII 10) in the mask, to allow - // [ENTER]. We are going to replace all CR with NL to conform. - $mask = strtr($mask, "\n", "\r"); - - // Prepare a list of ASCII codes from mask chars - $asciiMask = array_map(function ($char) { - return ord($char); - }, str_split($mask)); - $asciiMask = array_unique($asciiMask); - - // Char mask filtering is now handled by the PowerShell itself, - // because it's a much faster method than invoking PS interpreter - // after each mismatch. The command should return ASCII code of a - // matching key. - $result = $return = null; - exec( - 'powershell -NonInteractive -NoProfile -NoLogo -OutputFormat Text -Command "' - . '[int[]] $mask = '.join(',', $asciiMask).';' - . 'do {' - . '$key = $Host.UI.RawUI.ReadKey(\'NoEcho,IncludeKeyDown\').VirtualKeyCode;' - . '} while ( !($mask -contains $key) );' - . 'write $key;' - . '"', - $result, - $return - ); - - $char = !empty($result) ? trim(implode('', $result)) : null; - - if (!$return && $char && ($mask === null || in_array($char, $asciiMask))) { - // We have obtained an ASCII code, check if it is a carriage - // return and normalize it as needed - if ($char == 13) { - $char = 10; - } - - // Convert to a character - $char = chr($char); - - // ... and return it... - return $char; - } - } - - // Fall back to standard input, which on Windows does not allow reading - // a single character. This is a limitation of Windows streams - // implementation (not PHP) and this behavior cannot be changed with a - // command like "stty", known to POSIX systems. - $stream = fopen('php://stdin', 'rb'); - do { - $char = fgetc($stream); - $char = substr(trim($char), 0, 1); - } while (!$char || ($mask !== null && !stristr($mask, $char))); - fclose($stream); - - return $char; - } -} diff --git a/library/Zend/Console/CONTRIBUTING.md b/library/Zend/Console/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Console/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Console/Charset/Ascii.php b/library/Zend/Console/Charset/Ascii.php deleted file mode 100755 index 0cc326148..000000000 --- a/library/Zend/Console/Charset/Ascii.php +++ /dev/null @@ -1,48 +0,0 @@ - 0 ? (int) $val : 0; - }, $hex); - - $dhex = array_map('hexdec', $hex); - - if (array_fill(0, 3, $dhex[0]) === $dhex && (int) substr($dhex[0], -1) === 8) { - $x11 = 232 + (int) floor($dhex[0]/10); - return new static($x11); - } - - $x11 = $ahex[0] * 36 + $ahex[1] * 6 + $ahex[2] + 16; - - return new static($x11); - } -} diff --git a/library/Zend/Console/ColorInterface.php b/library/Zend/Console/ColorInterface.php deleted file mode 100755 index b2cc770b4..000000000 --- a/library/Zend/Console/ColorInterface.php +++ /dev/null @@ -1,34 +0,0 @@ -setCharset(new $className()); - } - - return static::$instance; - } - - /** - * Reset the console instance - */ - public static function resetInstance() - { - static::$instance = null; - } - - /** - * Check if currently running under MS Windows - * - * @see http://stackoverflow.com/questions/738823/possible-values-for-php-os - * @return bool - */ - public static function isWindows() - { - return - (defined('PHP_OS') && (substr_compare(PHP_OS, 'win', 0, 3, true) === 0)) || - (getenv('OS') != false && substr_compare(getenv('OS'), 'windows', 0, 7, true)) - ; - } - - /** - * Check if running under MS Windows Ansicon - * - * @return bool - */ - public static function isAnsicon() - { - return getenv('ANSICON') !== false; - } - - /** - * Check if running in a console environment (CLI) - * - * By default, returns value of PHP_SAPI global constant. If $isConsole is - * set, and a boolean value, that value will be returned. - * - * @return bool - */ - public static function isConsole() - { - if (null === static::$isConsole) { - static::$isConsole = (PHP_SAPI == 'cli'); - } - return static::$isConsole; - } - - /** - * Override the "is console environment" flag - * - * @param null|bool $flag - */ - public static function overrideIsConsole($flag) - { - if (null != $flag) { - $flag = (bool) $flag; - } - static::$isConsole = $flag; - } - - /** - * Try to detect best matching adapter - * @return string|null - */ - public static function detectBestAdapter() - { - // Check if we are in a console environment - if (!static::isConsole()) { - return null; - } - - // Check if we're on windows - if (static::isWindows()) { - if (static::isAnsicon()) { - $className = __NAMESPACE__ . '\Adapter\WindowsAnsicon'; - } else { - $className = __NAMESPACE__ . '\Adapter\Windows'; - } - - return $className; - } - - // Default is a Posix console - $className = __NAMESPACE__ . '\Adapter\Posix'; - return $className; - } - - /** - * Pass-thru static call to current AdapterInterface instance. - * - * @param $funcName - * @param $arguments - * @return mixed - */ - public static function __callStatic($funcName, $arguments) - { - $instance = static::getInstance(); - return call_user_func_array(array($instance, $funcName), $arguments); - } -} diff --git a/library/Zend/Console/Exception/BadMethodCallException.php b/library/Zend/Console/Exception/BadMethodCallException.php deleted file mode 100755 index aa650fc04..000000000 --- a/library/Zend/Console/Exception/BadMethodCallException.php +++ /dev/null @@ -1,14 +0,0 @@ -usage = $usage; - parent::__construct($message); - } - - /** - * Returns the usage - * - * @return string - */ - public function getUsageMessage() - { - return $this->usage; - } -} diff --git a/library/Zend/Console/Getopt.php b/library/Zend/Console/Getopt.php deleted file mode 100755 index 12493264a..000000000 --- a/library/Zend/Console/Getopt.php +++ /dev/null @@ -1,1056 +0,0 @@ - self::MODE_ZEND, - self::CONFIG_DASHDASH => true, - self::CONFIG_IGNORECASE => false, - self::CONFIG_PARSEALL => true, - self::CONFIG_CUMULATIVE_PARAMETERS => false, - self::CONFIG_CUMULATIVE_FLAGS => false, - self::CONFIG_PARAMETER_SEPARATOR => null, - self::CONFIG_FREEFORM_FLAGS => false, - self::CONFIG_NUMERIC_FLAGS => false - ); - - /** - * Stores the command-line arguments for the calling application. - * - * @var array - */ - protected $argv = array(); - - /** - * Stores the name of the calling application. - * - * @var string - */ - protected $progname = ''; - - /** - * Stores the list of legal options for this application. - * - * @var array - */ - protected $rules = array(); - - /** - * Stores alternate spellings of legal options. - * - * @var array - */ - protected $ruleMap = array(); - - /** - * Stores options given by the user in the current invocation - * of the application, as well as parameters given in options. - * - * @var array - */ - protected $options = array(); - - /** - * Stores the command-line arguments other than options. - * - * @var array - */ - protected $remainingArgs = array(); - - /** - * State of the options: parsed or not yet parsed? - * - * @var bool - */ - protected $parsed = false; - - /** - * A list of callbacks to call when a particular option is present. - * - * @var array - */ - protected $optionCallbacks = array(); - - /** - * The constructor takes one to three parameters. - * - * The first parameter is $rules, which may be a string for - * gnu-style format, or a structured array for Zend-style format. - * - * The second parameter is $argv, and it is optional. If not - * specified, $argv is inferred from the global argv. - * - * The third parameter is an array of configuration parameters - * to control the behavior of this instance of Getopt; it is optional. - * - * @param array $rules - * @param array $argv - * @param array $getoptConfig - * @throws Exception\InvalidArgumentException - */ - public function __construct($rules, $argv = null, $getoptConfig = array()) - { - if (!isset($_SERVER['argv'])) { - $errorDescription = (ini_get('register_argc_argv') == false) - ? "argv is not available, because ini option 'register_argc_argv' is set Off" - : '$_SERVER["argv"] is not set, but Zend\Console\Getopt cannot work without this information.'; - throw new Exception\InvalidArgumentException($errorDescription); - } - - $this->progname = $_SERVER['argv'][0]; - $this->setOptions($getoptConfig); - $this->addRules($rules); - if (!is_array($argv)) { - $argv = array_slice($_SERVER['argv'], 1); - } - if (isset($argv)) { - $this->addArguments((array) $argv); - } - } - - /** - * Return the state of the option seen on the command line of the - * current application invocation. This function returns true, or the - * parameter to the option, if any. If the option was not given, - * this function returns null. - * - * The magic __get method works in the context of naming the option - * as a virtual member of this class. - * - * @param string $key - * @return string - */ - public function __get($key) - { - return $this->getOption($key); - } - - /** - * Test whether a given option has been seen. - * - * @param string $key - * @return bool - */ - public function __isset($key) - { - $this->parse(); - if (isset($this->ruleMap[$key])) { - $key = $this->ruleMap[$key]; - return isset($this->options[$key]); - } - return false; - } - - /** - * Set the value for a given option. - * - * @param string $key - * @param string $value - */ - public function __set($key, $value) - { - $this->parse(); - if (isset($this->ruleMap[$key])) { - $key = $this->ruleMap[$key]; - $this->options[$key] = $value; - } - } - - /** - * Return the current set of options and parameters seen as a string. - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } - - /** - * Unset an option. - * - * @param string $key - */ - public function __unset($key) - { - $this->parse(); - if (isset($this->ruleMap[$key])) { - $key = $this->ruleMap[$key]; - unset($this->options[$key]); - } - } - - /** - * Define additional command-line arguments. - * These are appended to those defined when the constructor was called. - * - * @param array $argv - * @throws Exception\InvalidArgumentException When not given an array as parameter - * @return self - */ - public function addArguments($argv) - { - if (!is_array($argv)) { - throw new Exception\InvalidArgumentException("Parameter #1 to addArguments should be an array"); - } - $this->argv = array_merge($this->argv, $argv); - $this->parsed = false; - return $this; - } - - /** - * Define full set of command-line arguments. - * These replace any currently defined. - * - * @param array $argv - * @throws Exception\InvalidArgumentException When not given an array as parameter - * @return self - */ - public function setArguments($argv) - { - if (!is_array($argv)) { - throw new Exception\InvalidArgumentException("Parameter #1 to setArguments should be an array"); - } - $this->argv = $argv; - $this->parsed = false; - return $this; - } - - /** - * Define multiple configuration options from an associative array. - * These are not program options, but properties to configure - * the behavior of Zend\Console\Getopt. - * - * @param array $getoptConfig - * @return self - */ - public function setOptions($getoptConfig) - { - if (isset($getoptConfig)) { - foreach ($getoptConfig as $key => $value) { - $this->setOption($key, $value); - } - } - return $this; - } - - /** - * Define one configuration option as a key/value pair. - * These are not program options, but properties to configure - * the behavior of Zend\Console\Getopt. - * - * @param string $configKey - * @param string $configValue - * @return self - */ - public function setOption($configKey, $configValue) - { - if ($configKey !== null) { - $this->getoptConfig[$configKey] = $configValue; - } - return $this; - } - - /** - * Define additional option rules. - * These are appended to the rules defined when the constructor was called. - * - * @param array $rules - * @return self - */ - public function addRules($rules) - { - $ruleMode = $this->getoptConfig['ruleMode']; - switch ($this->getoptConfig['ruleMode']) { - case self::MODE_ZEND: - if (is_array($rules)) { - $this->_addRulesModeZend($rules); - break; - } - // intentional fallthrough - case self::MODE_GNU: - $this->_addRulesModeGnu($rules); - break; - default: - /** - * Call addRulesModeFoo() for ruleMode 'foo'. - * The developer should subclass Getopt and - * provide this method. - */ - $method = '_addRulesMode' . ucfirst($ruleMode); - $this->$method($rules); - } - $this->parsed = false; - return $this; - } - - /** - * Return the current set of options and parameters seen as a string. - * - * @return string - */ - public function toString() - { - $this->parse(); - $s = array(); - foreach ($this->options as $flag => $value) { - $s[] = $flag . '=' . ($value === true ? 'true' : $value); - } - return implode(' ', $s); - } - - /** - * Return the current set of options and parameters seen - * as an array of canonical options and parameters. - * - * Clusters have been expanded, and option aliases - * have been mapped to their primary option names. - * - * @return array - */ - public function toArray() - { - $this->parse(); - $s = array(); - foreach ($this->options as $flag => $value) { - $s[] = $flag; - if ($value !== true) { - $s[] = $value; - } - } - return $s; - } - - /** - * Return the current set of options and parameters seen in Json format. - * - * @return string - */ - public function toJson() - { - $this->parse(); - $j = array(); - foreach ($this->options as $flag => $value) { - $j['options'][] = array( - 'option' => array( - 'flag' => $flag, - 'parameter' => $value - ) - ); - } - - $json = \Zend\Json\Json::encode($j); - return $json; - } - - /** - * Return the current set of options and parameters seen in XML format. - * - * @return string - */ - public function toXml() - { - $this->parse(); - $doc = new \DomDocument('1.0', 'utf-8'); - $optionsNode = $doc->createElement('options'); - $doc->appendChild($optionsNode); - foreach ($this->options as $flag => $value) { - $optionNode = $doc->createElement('option'); - $optionNode->setAttribute('flag', utf8_encode($flag)); - if ($value !== true) { - $optionNode->setAttribute('parameter', utf8_encode($value)); - } - $optionsNode->appendChild($optionNode); - } - $xml = $doc->saveXML(); - return $xml; - } - - /** - * Return a list of options that have been seen in the current argv. - * - * @return array - */ - public function getOptions() - { - $this->parse(); - return array_keys($this->options); - } - - /** - * Return the state of the option seen on the command line of the - * current application invocation. - * - * This function returns true, or the parameter value to the option, if any. - * If the option was not given, this function returns false. - * - * @param string $flag - * @return mixed - */ - public function getOption($flag) - { - $this->parse(); - if ($this->getoptConfig[self::CONFIG_IGNORECASE]) { - $flag = strtolower($flag); - } - if (isset($this->ruleMap[$flag])) { - $flag = $this->ruleMap[$flag]; - if (isset($this->options[$flag])) { - return $this->options[$flag]; - } - } - return null; - } - - /** - * Return the arguments from the command-line following all options found. - * - * @return array - */ - public function getRemainingArgs() - { - $this->parse(); - return $this->remainingArgs; - } - - public function getArguments() - { - $result = $this->getRemainingArgs(); - foreach ($this->getOptions() as $option) { - $result[$option] = $this->getOption($option); - } - return $result; - } - - /** - * Return a useful option reference, formatted for display in an - * error message. - * - * Note that this usage information is provided in most Exceptions - * generated by this class. - * - * @return string - */ - public function getUsageMessage() - { - $usage = "Usage: {$this->progname} [ options ]\n"; - $maxLen = 20; - $lines = array(); - foreach ($this->rules as $rule) { - if (isset($rule['isFreeformFlag'])) { - continue; - } - $flags = array(); - if (is_array($rule['alias'])) { - foreach ($rule['alias'] as $flag) { - $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag; - } - } - $linepart['name'] = implode('|', $flags); - if (isset($rule['param']) && $rule['param'] != 'none') { - $linepart['name'] .= ' '; - switch ($rule['param']) { - case 'optional': - $linepart['name'] .= "[ <{$rule['paramType']}> ]"; - break; - case 'required': - $linepart['name'] .= "<{$rule['paramType']}>"; - break; - } - } - if (strlen($linepart['name']) > $maxLen) { - $maxLen = strlen($linepart['name']); - } - $linepart['help'] = ''; - if (isset($rule['help'])) { - $linepart['help'] .= $rule['help']; - } - $lines[] = $linepart; - } - foreach ($lines as $linepart) { - $usage .= sprintf( - "%s %s\n", - str_pad($linepart['name'], $maxLen), - $linepart['help'] - ); - } - return $usage; - } - - /** - * Define aliases for options. - * - * The parameter $aliasMap is an associative array - * mapping option name (short or long) to an alias. - * - * @param array $aliasMap - * @throws Exception\ExceptionInterface - * @return self - */ - public function setAliases($aliasMap) - { - foreach ($aliasMap as $flag => $alias) { - if ($this->getoptConfig[self::CONFIG_IGNORECASE]) { - $flag = strtolower($flag); - $alias = strtolower($alias); - } - if (!isset($this->ruleMap[$flag])) { - continue; - } - $flag = $this->ruleMap[$flag]; - if (isset($this->rules[$alias]) || isset($this->ruleMap[$alias])) { - $o = (strlen($alias) == 1 ? '-' : '--') . $alias; - throw new Exception\InvalidArgumentException("Option \"$o\" is being defined more than once."); - } - $this->rules[$flag]['alias'][] = $alias; - $this->ruleMap[$alias] = $flag; - } - return $this; - } - - /** - * Define help messages for options. - * - * The parameter $helpMap is an associative array - * mapping option name (short or long) to the help string. - * - * @param array $helpMap - * @return self - */ - public function setHelp($helpMap) - { - foreach ($helpMap as $flag => $help) { - if (!isset($this->ruleMap[$flag])) { - continue; - } - $flag = $this->ruleMap[$flag]; - $this->rules[$flag]['help'] = $help; - } - return $this; - } - - /** - * Parse command-line arguments and find both long and short - * options. - * - * Also find option parameters, and remaining arguments after - * all options have been parsed. - * - * @return self - */ - public function parse() - { - if ($this->parsed === true) { - return $this; - } - - $argv = $this->argv; - $this->options = array(); - $this->remainingArgs = array(); - while (count($argv) > 0) { - if ($argv[0] == '--') { - array_shift($argv); - if ($this->getoptConfig[self::CONFIG_DASHDASH]) { - $this->remainingArgs = array_merge($this->remainingArgs, $argv); - break; - } - } - if (substr($argv[0], 0, 2) == '--') { - $this->_parseLongOption($argv); - } elseif (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) { - $this->_parseShortOptionCluster($argv); - } elseif ($this->getoptConfig[self::CONFIG_PARSEALL]) { - $this->remainingArgs[] = array_shift($argv); - } else { - /* - * We should put all other arguments in remainingArgs and stop parsing - * since CONFIG_PARSEALL is false. - */ - $this->remainingArgs = array_merge($this->remainingArgs, $argv); - break; - } - } - $this->parsed = true; - - //go through parsed args and process callbacks - $this->triggerCallbacks(); - - return $this; - } - - /** - * @param string $option The name of the property which, if present, will call the passed - * callback with the value of this parameter. - * @param callable $callback The callback that will be called for this option. The first - * parameter will be the value of getOption($option), the second - * parameter will be a reference to $this object. If the callback returns - * false then an Exception\RuntimeException will be thrown indicating that - * there is a parse issue with this option. - * - * @return self - */ - public function setOptionCallback($option, \Closure $callback) - { - $this->optionCallbacks[$option] = $callback; - - return $this; - } - - /** - * Triggers all the registered callbacks. - */ - protected function triggerCallbacks() - { - foreach ($this->optionCallbacks as $option => $callback) { - if (null === $this->getOption($option)) { - continue; - } - //make sure we've resolved the alias, if using one - if (isset($this->ruleMap[$option]) && $option = $this->ruleMap[$option]) { - if (false === $callback($this->getOption($option), $this)) { - throw new Exception\RuntimeException( - "The option $option is invalid. See usage.", - $this->getUsageMessage() - ); - } - } - } - } - - /** - * Parse command-line arguments for a single long option. - * A long option is preceded by a double '--' character. - * Long options may not be clustered. - * - * @param mixed &$argv - */ - protected function _parseLongOption(&$argv) - { - $optionWithParam = ltrim(array_shift($argv), '-'); - $l = explode('=', $optionWithParam, 2); - $flag = array_shift($l); - $param = array_shift($l); - if (isset($param)) { - array_unshift($argv, $param); - } - $this->_parseSingleOption($flag, $argv); - } - - /** - * Parse command-line arguments for short options. - * Short options are those preceded by a single '-' character. - * Short options may be clustered. - * - * @param mixed &$argv - */ - protected function _parseShortOptionCluster(&$argv) - { - $flagCluster = ltrim(array_shift($argv), '-'); - foreach (str_split($flagCluster) as $flag) { - $this->_parseSingleOption($flag, $argv); - } - } - - /** - * Parse command-line arguments for a single option. - * - * @param string $flag - * @param mixed $argv - * @throws Exception\ExceptionInterface - */ - protected function _parseSingleOption($flag, &$argv) - { - if ($this->getoptConfig[self::CONFIG_IGNORECASE]) { - $flag = strtolower($flag); - } - - // Check if this option is numeric one - if (preg_match('/^\d+$/', $flag)) { - return $this->_setNumericOptionValue($flag); - } - - if (!isset($this->ruleMap[$flag])) { - // Don't throw Exception for flag-like param in case when freeform flags are allowed - if (!$this->getoptConfig[self::CONFIG_FREEFORM_FLAGS]) { - throw new Exception\RuntimeException( - "Option \"$flag\" is not recognized.", - $this->getUsageMessage() - ); - } - - // Magic methods in future will use this mark as real flag value - $this->ruleMap[$flag] = $flag; - $realFlag = $flag; - $this->rules[$realFlag] = array( - 'param' => 'optional', - 'isFreeformFlag' => true - ); - } else { - $realFlag = $this->ruleMap[$flag]; - } - - switch ($this->rules[$realFlag]['param']) { - case 'required': - if (count($argv) > 0) { - $param = array_shift($argv); - $this->_checkParameterType($realFlag, $param); - } else { - throw new Exception\RuntimeException( - "Option \"$flag\" requires a parameter.", - $this->getUsageMessage() - ); - } - break; - case 'optional': - if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') { - $param = array_shift($argv); - $this->_checkParameterType($realFlag, $param); - } else { - $param = true; - } - break; - default: - $param = true; - } - - $this->_setSingleOptionValue($realFlag, $param); - } - - /** - * Set given value as value of numeric option - * - * Throw runtime exception if this action is deny by configuration - * or no one numeric option handlers is defined - * - * @param int $value - * @throws Exception\RuntimeException - * @return void - */ - protected function _setNumericOptionValue($value) - { - if (!$this->getoptConfig[self::CONFIG_NUMERIC_FLAGS]) { - throw new Exception\RuntimeException("Using of numeric flags are deny by configuration"); - } - - if (empty($this->getoptConfig['numericFlagsOption'])) { - throw new Exception\RuntimeException("Any option for handling numeric flags are specified"); - } - - return $this->_setSingleOptionValue($this->getoptConfig['numericFlagsOption'], $value); - } - - /** - * Add relative to options' flag value - * - * If options list already has current flag as key - * and parser should follow cumulative params by configuration, - * we should to add new param to array, not to overwrite - * - * @param string $flag - * @param string $value - */ - protected function _setSingleOptionValue($flag, $value) - { - if (true === $value && $this->getoptConfig[self::CONFIG_CUMULATIVE_FLAGS]) { - // For boolean values we have to create new flag, or increase number of flags' usage count - return $this->_setBooleanFlagValue($flag); - } - - // Split multiple values, if necessary - // Filter empty values from splited array - $separator = $this->getoptConfig[self::CONFIG_PARAMETER_SEPARATOR]; - if (is_string($value) && !empty($separator) && is_string($separator) && substr_count($value, $separator)) { - $value = array_filter(explode($separator, $value)); - } - - if (!array_key_exists($flag, $this->options)) { - $this->options[$flag] = $value; - } elseif ($this->getoptConfig[self::CONFIG_CUMULATIVE_PARAMETERS]) { - $this->options[$flag] = (array) $this->options[$flag]; - array_push($this->options[$flag], $value); - } else { - $this->options[$flag] = $value; - } - } - - /** - * Set TRUE value to given flag, if this option does not exist yet - * In other case increase value to show count of flags' usage - * - * @param string $flag - */ - protected function _setBooleanFlagValue($flag) - { - $this->options[$flag] = array_key_exists($flag, $this->options) - ? (int) $this->options[$flag] + 1 - : true; - } - - /** - * Return true if the parameter is in a valid format for - * the option $flag. - * Throw an exception in most other cases. - * - * @param string $flag - * @param string $param - * @throws Exception\ExceptionInterface - * @return bool - */ - protected function _checkParameterType($flag, $param) - { - $type = 'string'; - if (isset($this->rules[$flag]['paramType'])) { - $type = $this->rules[$flag]['paramType']; - } - switch ($type) { - case 'word': - if (preg_match('/\W/', $param)) { - throw new Exception\RuntimeException( - "Option \"$flag\" requires a single-word parameter, but was given \"$param\".", - $this->getUsageMessage() - ); - } - break; - case 'integer': - if (preg_match('/\D/', $param)) { - throw new Exception\RuntimeException( - "Option \"$flag\" requires an integer parameter, but was given \"$param\".", - $this->getUsageMessage() - ); - } - break; - case 'string': - default: - break; - } - return true; - } - - /** - * Define legal options using the gnu-style format. - * - * @param string $rules - */ - protected function _addRulesModeGnu($rules) - { - $ruleArray = array(); - - /** - * Options may be single alphanumeric characters. - * Options may have a ':' which indicates a required string parameter. - * No long options or option aliases are supported in GNU style. - */ - preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray); - foreach ($ruleArray[1] as $rule) { - $r = array(); - $flag = substr($rule, 0, 1); - if ($this->getoptConfig[self::CONFIG_IGNORECASE]) { - $flag = strtolower($flag); - } - $r['alias'][] = $flag; - if (substr($rule, 1, 1) == ':') { - $r['param'] = 'required'; - $r['paramType'] = 'string'; - } else { - $r['param'] = 'none'; - } - $this->rules[$flag] = $r; - $this->ruleMap[$flag] = $flag; - } - } - - /** - * Define legal options using the Zend-style format. - * - * @param array $rules - * @throws Exception\ExceptionInterface - */ - protected function _addRulesModeZend($rules) - { - foreach ($rules as $ruleCode => $helpMessage) { - // this may have to translate the long parm type if there - // are any complaints that =string will not work (even though that use - // case is not documented) - if (in_array(substr($ruleCode, -2, 1), array('-', '='))) { - $flagList = substr($ruleCode, 0, -2); - $delimiter = substr($ruleCode, -2, 1); - $paramType = substr($ruleCode, -1); - } else { - $flagList = $ruleCode; - $delimiter = $paramType = null; - } - if ($this->getoptConfig[self::CONFIG_IGNORECASE]) { - $flagList = strtolower($flagList); - } - $flags = explode('|', $flagList); - $rule = array(); - $mainFlag = $flags[0]; - foreach ($flags as $flag) { - if (empty($flag)) { - throw new Exception\InvalidArgumentException("Blank flag not allowed in rule \"$ruleCode\"."); - } - if (strlen($flag) == 1) { - if (isset($this->ruleMap[$flag])) { - throw new Exception\InvalidArgumentException( - "Option \"-$flag\" is being defined more than once." - ); - } - $this->ruleMap[$flag] = $mainFlag; - $rule['alias'][] = $flag; - } else { - if (isset($this->rules[$flag]) || isset($this->ruleMap[$flag])) { - throw new Exception\InvalidArgumentException( - "Option \"--$flag\" is being defined more than once." - ); - } - $this->ruleMap[$flag] = $mainFlag; - $rule['alias'][] = $flag; - } - } - if (isset($delimiter)) { - switch ($delimiter) { - case self::PARAM_REQUIRED: - $rule['param'] = 'required'; - break; - case self::PARAM_OPTIONAL: - default: - $rule['param'] = 'optional'; - } - switch (substr($paramType, 0, 1)) { - case self::TYPE_WORD: - $rule['paramType'] = 'word'; - break; - case self::TYPE_INTEGER: - $rule['paramType'] = 'integer'; - break; - case self::TYPE_NUMERIC_FLAG: - $rule['paramType'] = 'numericFlag'; - $this->getoptConfig['numericFlagsOption'] = $mainFlag; - break; - case self::TYPE_STRING: - default: - $rule['paramType'] = 'string'; - } - } else { - $rule['param'] = 'none'; - } - $rule['help'] = $helpMessage; - $this->rules[$mainFlag] = $rule; - } - } -} diff --git a/library/Zend/Console/Prompt/AbstractPrompt.php b/library/Zend/Console/Prompt/AbstractPrompt.php deleted file mode 100755 index cd717cf35..000000000 --- a/library/Zend/Console/Prompt/AbstractPrompt.php +++ /dev/null @@ -1,85 +0,0 @@ -lastResponse; - } - - /** - * Return console adapter to use when showing prompt. - * - * @return ConsoleAdapter - */ - public function getConsole() - { - if (!$this->console) { - $this->console = Console::getInstance(); - } - - return $this->console; - } - - /** - * Set console adapter to use when showing prompt. - * - * @param ConsoleAdapter $adapter - */ - public function setConsole(ConsoleAdapter $adapter) - { - $this->console = $adapter; - } - - /** - * Create an instance of this prompt, show it and return response. - * - * This is a convenience method for creating statically creating prompts, i.e.: - * - * $name = Zend\Console\Prompt\Line::prompt("Enter your name: "); - * - * @return mixed - * @throws Exception\BadMethodCallException - */ - public static function prompt() - { - if (get_called_class() === __CLASS__) { - throw new Exception\BadMethodCallException( - 'Cannot call prompt() on AbstractPrompt class. Use one of the Zend\Console\Prompt\ subclasses.' - ); - } - - $refl = new ReflectionClass(get_called_class()); - $instance = $refl->newInstanceArgs(func_get_args()); - return $instance->show(); - } -} diff --git a/library/Zend/Console/Prompt/Char.php b/library/Zend/Console/Prompt/Char.php deleted file mode 100755 index b6c305145..000000000 --- a/library/Zend/Console/Prompt/Char.php +++ /dev/null @@ -1,186 +0,0 @@ -setPromptText($promptText); - $this->setAllowEmpty($allowEmpty); - $this->setIgnoreCase($ignoreCase); - - if (null != $allowedChars) { - if ($this->ignoreCase) { - $this->setAllowedChars(strtolower($allowedChars)); - } else { - $this->setAllowedChars($allowedChars); - } - } - - $this->setEcho($echo); - } - - /** - * Show the prompt to user and return a single char. - * - * @return string - */ - public function show() - { - $this->getConsole()->write($this->promptText); - $mask = $this->getAllowedChars(); - - /** - * Normalize the mask if case is irrelevant - */ - if ($this->ignoreCase) { - $mask = strtolower($mask); // lowercase all - $mask .= strtoupper($mask); // uppercase and append - $mask = str_split($mask); // convert to array - $mask = array_unique($mask); // remove duplicates - $mask = implode("", $mask); // convert back to string - } - - /** - * Read char from console - */ - $char = $this->getConsole()->readChar($mask); - - if ($this->echo) { - echo trim($char)."\n"; - } else { - if ($this->promptText) { - echo "\n"; // skip to next line but only if we had any prompt text - } - } - - return $this->lastResponse = $char; - } - - /** - * @param bool $allowEmpty - */ - public function setAllowEmpty($allowEmpty) - { - $this->allowEmpty = (bool) $allowEmpty; - } - - /** - * @return bool - */ - public function getAllowEmpty() - { - return $this->allowEmpty; - } - - /** - * @param string $promptText - */ - public function setPromptText($promptText) - { - $this->promptText = $promptText; - } - - /** - * @return string - */ - public function getPromptText() - { - return $this->promptText; - } - - /** - * @param string $allowedChars - */ - public function setAllowedChars($allowedChars) - { - $this->allowedChars = $allowedChars; - } - - /** - * @return string - */ - public function getAllowedChars() - { - return $this->allowedChars; - } - - /** - * @param bool $ignoreCase - */ - public function setIgnoreCase($ignoreCase) - { - $this->ignoreCase = (bool) $ignoreCase; - } - - /** - * @return bool - */ - public function getIgnoreCase() - { - return $this->ignoreCase; - } - - /** - * @param bool $echo - */ - public function setEcho($echo) - { - $this->echo = (bool) $echo; - } - - /** - * @return bool - */ - public function getEcho() - { - return $this->echo; - } -} diff --git a/library/Zend/Console/Prompt/Confirm.php b/library/Zend/Console/Prompt/Confirm.php deleted file mode 100755 index f660452be..000000000 --- a/library/Zend/Console/Prompt/Confirm.php +++ /dev/null @@ -1,113 +0,0 @@ -setPromptText($promptText); - } - - if ($yesChar !== null) { - $this->setYesChar($yesChar); - } - - if ($noChar !== null) { - $this->setNoChar($noChar); - } - } - - /** - * Show the confirmation message and return result. - * - * @return bool - */ - public function show() - { - $char = parent::show(); - if ($this->ignoreCase) { - $response = strtolower($char) === strtolower($this->yesChar); - } else { - $response = $char === $this->yesChar; - } - return $this->lastResponse = $response; - } - - /** - * @param string $noChar - */ - public function setNoChar($noChar) - { - $this->noChar = $noChar; - $this->setAllowedChars($this->yesChar . $this->noChar); - } - - /** - * @return string - */ - public function getNoChar() - { - return $this->noChar; - } - - /** - * @param string $yesChar - */ - public function setYesChar($yesChar) - { - $this->yesChar = $yesChar; - $this->setAllowedChars($this->yesChar . $this->noChar); - } - - /** - * @return string - */ - public function getYesChar() - { - return $this->yesChar; - } -} diff --git a/library/Zend/Console/Prompt/Line.php b/library/Zend/Console/Prompt/Line.php deleted file mode 100755 index 7a7427d7a..000000000 --- a/library/Zend/Console/Prompt/Line.php +++ /dev/null @@ -1,113 +0,0 @@ -setPromptText($promptText); - } - - if ($allowEmpty !== null) { - $this->setAllowEmpty($allowEmpty); - } - - if ($maxLength !== null) { - $this->setMaxLength($maxLength); - } - } - - /** - * Show the prompt to user and return the answer. - * - * @return string - */ - public function show() - { - do { - $this->getConsole()->write($this->promptText); - $line = $this->getConsole()->readLine($this->maxLength); - } while (!$this->allowEmpty && !$line); - - return $this->lastResponse = $line; - } - - /** - * @param bool $allowEmpty - */ - public function setAllowEmpty($allowEmpty) - { - $this->allowEmpty = $allowEmpty; - } - - /** - * @return bool - */ - public function getAllowEmpty() - { - return $this->allowEmpty; - } - - /** - * @param int $maxLength - */ - public function setMaxLength($maxLength) - { - $this->maxLength = $maxLength; - } - - /** - * @return int - */ - public function getMaxLength() - { - return $this->maxLength; - } - - /** - * @param string $promptText - */ - public function setPromptText($promptText) - { - $this->promptText = $promptText; - } - - /** - * @return string - */ - public function getPromptText() - { - return $this->promptText; - } -} diff --git a/library/Zend/Console/Prompt/Number.php b/library/Zend/Console/Prompt/Number.php deleted file mode 100755 index 8ce533005..000000000 --- a/library/Zend/Console/Prompt/Number.php +++ /dev/null @@ -1,208 +0,0 @@ -setPromptText($promptText); - } - - if ($allowEmpty !== null) { - $this->setAllowEmpty($allowEmpty); - } - - if ($min !== null) { - $this->setMin($min); - } - - if ($max !== null) { - $this->setMax($max); - } - - if ($allowFloat !== null) { - $this->setAllowFloat($allowFloat); - } - } - - /** - * Show the prompt to user and return the answer. - * - * @return mixed - */ - public function show() - { - /** - * Ask for a number and validate it. - */ - do { - $valid = true; - $number = parent::show(); - if ($number === "" && !$this->allowEmpty) { - $valid = false; - } elseif ($number === "") { - $number = null; - } elseif (!is_numeric($number)) { - $this->getConsole()->writeLine("$number is not a number\n"); - $valid = false; - } elseif (!$this->allowFloat && (round($number) != $number)) { - $this->getConsole()->writeLine("Please enter a non-floating number, i.e. " . round($number) . "\n"); - $valid = false; - } elseif ($this->max !== null && $number > $this->max) { - $this->getConsole()->writeLine("Please enter a number not greater than " . $this->max . "\n"); - $valid = false; - } elseif ($this->min !== null && $number < $this->min) { - $this->getConsole()->writeLine("Please enter a number not smaller than " . $this->min . "\n"); - $valid = false; - } - } while (!$valid); - - /** - * Cast proper type - */ - if ($number !== null) { - $number = $this->allowFloat ? (double) $number : (int) $number; - } - - return $this->lastResponse = $number; - } - - /** - * @param bool $allowEmpty - */ - public function setAllowEmpty($allowEmpty) - { - $this->allowEmpty = $allowEmpty; - } - - /** - * @return bool - */ - public function getAllowEmpty() - { - return $this->allowEmpty; - } - - /** - * @param int $maxLength - */ - public function setMaxLength($maxLength) - { - $this->maxLength = $maxLength; - } - - /** - * @return int - */ - public function getMaxLength() - { - return $this->maxLength; - } - - /** - * @param string $promptText - */ - public function setPromptText($promptText) - { - $this->promptText = $promptText; - } - - /** - * @return string - */ - public function getPromptText() - { - return $this->promptText; - } - - /** - * @param int $max - */ - public function setMax($max) - { - $this->max = $max; - } - - /** - * @return int - */ - public function getMax() - { - return $this->max; - } - - /** - * @param int $min - */ - public function setMin($min) - { - $this->min = $min; - } - - /** - * @return int - */ - public function getMin() - { - return $this->min; - } - - /** - * @param bool $allowFloat - */ - public function setAllowFloat($allowFloat) - { - $this->allowFloat = $allowFloat; - } - - /** - * @return bool - */ - public function getAllowFloat() - { - return $this->allowFloat; - } -} diff --git a/library/Zend/Console/Prompt/PromptInterface.php b/library/Zend/Console/Prompt/PromptInterface.php deleted file mode 100755 index da1b6215c..000000000 --- a/library/Zend/Console/Prompt/PromptInterface.php +++ /dev/null @@ -1,44 +0,0 @@ -setPromptText($promptText); - } - - if (!count($options)) { - throw new Exception\BadMethodCallException( - 'Cannot construct a "select" prompt without any options' - ); - } - - $this->setOptions($options); - - if ($allowEmpty !== null) { - $this->setAllowEmpty($allowEmpty); - } - - if ($echo !== null) { - $this->setEcho($echo); - } - } - - /** - * Show a list of options and prompt the user to select one of them. - * - * @return string Selected option - */ - public function show() - { - // Show prompt text and available options - $console = $this->getConsole(); - $console->writeLine($this->promptText); - foreach ($this->options as $k => $v) { - $console->writeLine(' ' . $k . ') ' . $v); - } - - // Prepare mask - $mask = implode("", array_keys($this->options)); - if ($this->allowEmpty) { - $mask .= "\r\n"; - } - - // Prepare other params for parent class - $this->setAllowedChars($mask); - $oldPrompt = $this->promptText; - $oldEcho = $this->echo; - $this->echo = false; - $this->promptText = null; - - // Retrieve a single character - $response = parent::show(); - - // Restore old params - $this->promptText = $oldPrompt; - $this->echo = $oldEcho; - - // Display selected option if echo is enabled - if ($this->echo) { - if (isset($this->options[$response])) { - $console->writeLine($this->options[$response]); - } else { - $console->writeLine(); - } - } - - $this->lastResponse = $response; - return $response; - } - - /** - * Set allowed options - * - * @param array|\Traversable $options - * @throws Exception\BadMethodCallException - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof \Traversable) { - throw new Exception\BadMethodCallException( - 'Please specify an array or Traversable object as options' - ); - } - - if (!is_array($options)) { - $this->options = array(); - foreach ($options as $k => $v) { - $this->options[$k] = $v; - } - } else { - $this->options = $options; - } - } - - /** - * @return array - */ - public function getOptions() - { - return $this->options; - } -} diff --git a/library/Zend/Console/README.md b/library/Zend/Console/README.md deleted file mode 100755 index eb8566c0f..000000000 --- a/library/Zend/Console/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Console Component from ZF2 -========================== - -This is the Console component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Console/Request.php b/library/Zend/Console/Request.php deleted file mode 100755 index 57b48bb2c..000000000 --- a/library/Zend/Console/Request.php +++ /dev/null @@ -1,197 +0,0 @@ - 0) { - $this->setScriptName(array_shift($args)); - } - - /** - * Store runtime params - */ - $this->params()->fromArray($args); - $this->setContent($args); - - /** - * Store environment data - */ - $this->env()->fromArray($env); - } - - /** - * Exchange parameters object - * - * @param \Zend\Stdlib\Parameters $params - * @return Request - */ - public function setParams(Parameters $params) - { - $this->params = $params; - $this->setContent($params); - return $this; - } - - /** - * Return the container responsible for parameters - * - * @return \Zend\Stdlib\Parameters - */ - public function getParams() - { - if ($this->params === null) { - $this->params = new Parameters(); - } - - return $this->params; - } - - /** - * Return a single parameter. - * Shortcut for $request->params()->get() - * - * @param string $name Parameter name - * @param string $default (optional) default value in case the parameter does not exist - * @return mixed - */ - public function getParam($name, $default = null) - { - return $this->params()->get($name, $default); - } - - /** - * Return the container responsible for parameters - * - * @return \Zend\Stdlib\Parameters - */ - public function params() - { - return $this->getParams(); - } - - /** - * Provide an alternate Parameter Container implementation for env parameters in this object, (this is NOT the - * primary API for value setting, for that see env()) - * - * @param \Zend\Stdlib\Parameters $env - * @return \Zend\Console\Request - */ - public function setEnv(Parameters $env) - { - $this->envParams = $env; - return $this; - } - - /** - * Return a single parameter container responsible for env parameters - * - * @param string $name Parameter name - * @param string $default (optional) default value in case the parameter does not exist - * @return \Zend\Stdlib\Parameters - */ - public function getEnv($name, $default = null) - { - return $this->env()->get($name, $default); - } - - /** - * Return the parameter container responsible for env parameters - * - * @return \Zend\Stdlib\Parameters - */ - public function env() - { - if ($this->envParams === null) { - $this->envParams = new Parameters(); - } - - return $this->envParams; - } - - /** - * @return string - */ - public function toString() - { - return trim(implode(' ', $this->params()->toArray())); - } - - /** - * Allow PHP casting of this object - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } - - /** - * @param string $scriptName - */ - public function setScriptName($scriptName) - { - $this->scriptName = $scriptName; - } - - /** - * @return string - */ - public function getScriptName() - { - return $this->scriptName; - } -} diff --git a/library/Zend/Console/Response.php b/library/Zend/Console/Response.php deleted file mode 100755 index 75a068614..000000000 --- a/library/Zend/Console/Response.php +++ /dev/null @@ -1,80 +0,0 @@ -contentSent; - } - - /** - * Set the error level that will be returned to shell. - * - * @param int $errorLevel - * @return Response - */ - public function setErrorLevel($errorLevel) - { - $this->setMetadata('errorLevel', $errorLevel); - return $this; - } - - /** - * Get response error level that will be returned to shell. - * - * @return int|0 - */ - public function getErrorLevel() - { - return $this->getMetadata('errorLevel', 0); - } - - /** - * Send content - * - * @return Response - * @deprecated - */ - public function sendContent() - { - if ($this->contentSent()) { - return $this; - } - echo $this->getContent(); - $this->contentSent = true; - return $this; - } - - /** - * @deprecated - */ - public function send() - { - $this->sendContent(); - $errorLevel = (int) $this->getMetadata('errorLevel', 0); - exit($errorLevel); - } -} diff --git a/library/Zend/Console/RouteMatcher/DefaultRouteMatcher.php b/library/Zend/Console/RouteMatcher/DefaultRouteMatcher.php deleted file mode 100755 index a5f8fae57..000000000 --- a/library/Zend/Console/RouteMatcher/DefaultRouteMatcher.php +++ /dev/null @@ -1,780 +0,0 @@ -defaults = $defaults; - $this->constraints = $constraints; - $this->aliases = $aliases; - - if ($filters !== null) { - foreach ($filters as $name => $filter) { - if (!$filter instanceof FilterInterface) { - throw new Exception\InvalidArgumentException('Cannot use ' . gettype($filters) . ' as filter for ' . __CLASS__); - } - $this->filters[$name] = $filter; - } - } - - if ($validators !== null) { - foreach ($validators as $name => $validator) { - if (!$validator instanceof ValidatorInterface) { - throw new Exception\InvalidArgumentException('Cannot use ' . gettype($validator) . ' as validator for ' . __CLASS__); - } - $this->validators[$name] = $validator; - } - } - - $this->parts = $this->parseDefinition($route); - } - - /** - * Parse a route definition. - * - * @param string $def - * @return array - * @throws Exception\InvalidArgumentException - */ - protected function parseDefinition($def) - { - $def = trim($def); - $pos = 0; - $length = strlen($def); - $parts = array(); - $unnamedGroupCounter = 1; - - while ($pos < $length) { - /** - * Optional value param, i.e. - * [SOMETHING] - */ - if (preg_match('/\G\[(?P[A-Z][A-Z0-9\_\-]*?)\](?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => strtolower($m['name']), - 'literal' => false, - 'required' => false, - 'positional' => true, - 'hasValue' => true, - ); - } - /** - * Mandatory value param, i.e. - * SOMETHING - */ - elseif (preg_match('/\G(?P[A-Z][A-Z0-9\_\-]*?)(?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => strtolower($m['name']), - 'literal' => false, - 'required' => true, - 'positional' => true, - 'hasValue' => true, - ); - } - /** - * Optional literal param, i.e. - * [something] - */ - elseif (preg_match('/\G\[ *?(?P[a-zA-Z][a-zA-Z0-9\_\-]*?) *?\](?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'literal' => true, - 'required' => false, - 'positional' => true, - 'hasValue' => false, - ); - } - /** - * Optional value param, syntax 2, i.e. - * [] - */ - elseif (preg_match('/\G\[ *\<(?P[a-zA-Z][a-zA-Z0-9\_\-]*?)\> *\](?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'literal' => false, - 'required' => false, - 'positional' => true, - 'hasValue' => true, - ); - } - /** - * Mandatory value param, i.e. - * - */ - elseif (preg_match('/\G\< *(?P[a-zA-Z][a-zA-Z0-9\_\-]*?) *\>(?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'literal' => false, - 'required' => true, - 'positional' => true, - 'hasValue' => true, - ); - } - /** - * Mandatory literal param, i.e. - * something - */ - elseif (preg_match('/\G(?P[a-zA-Z][a-zA-Z0-9\_\-]*?)(?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'literal' => true, - 'required' => true, - 'positional' => true, - 'hasValue' => false, - ); - } - /** - * Mandatory long param - * --param= - * --param=whatever - */ - elseif (preg_match('/\G--(?P[a-zA-Z0-9][a-zA-Z0-9\_\-]+)(?P=\S*?)?(?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'short' => false, - 'literal' => false, - 'required' => true, - 'positional' => false, - 'hasValue' => !empty($m['hasValue']), - ); - } - /** - * Optional long flag - * [--param] - */ - elseif (preg_match( - '/\G\[ *?--(?P[a-zA-Z0-9][a-zA-Z0-9\_\-]+) *?\](?: +|$)/s', $def, $m, 0, $pos - )) { - $item = array( - 'name' => $m['name'], - 'short' => false, - 'literal' => false, - 'required' => false, - 'positional' => false, - 'hasValue' => false, - ); - } - /** - * Optional long param - * [--param=] - * [--param=whatever] - */ - elseif (preg_match( - '/\G\[ *?--(?P[a-zA-Z0-9][a-zA-Z0-9\_\-]+)(?P=\S*?)? *?\](?: +|$)/s', $def, $m, 0, $pos - )) { - $item = array( - 'name' => $m['name'], - 'short' => false, - 'literal' => false, - 'required' => false, - 'positional' => false, - 'hasValue' => !empty($m['hasValue']), - ); - } - /** - * Mandatory short param - * -a - * -a=i - * -a=s - * -a=w - */ - elseif (preg_match('/\G-(?P[a-zA-Z0-9])(?:=(?P[ns]))?(?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'short' => true, - 'literal' => false, - 'required' => true, - 'positional' => false, - 'hasValue' => !empty($m['type']) ? $m['type'] : null, - ); - } - /** - * Optional short param - * [-a] - * [-a=n] - * [-a=s] - */ - elseif (preg_match('/\G\[ *?-(?P[a-zA-Z0-9])(?:=(?P[ns]))? *?\](?: +|$)/s', $def, $m, 0, $pos)) { - $item = array( - 'name' => $m['name'], - 'short' => true, - 'literal' => false, - 'required' => false, - 'positional' => false, - 'hasValue' => !empty($m['type']) ? $m['type'] : null, - ); - } - /** - * Optional literal param alternative - * [ something | somethingElse | anotherOne ] - * [ something | somethingElse | anotherOne ]:namedGroup - */ - elseif (preg_match('/ - \G - \[ - (?P - (?: - \ *? - (?P[a-zA-Z][a-zA-Z0-9_\-]*?) - \ *? - (?:\||(?=\])) - \ *? - )+ - ) - \] - (?:\:(?P[a-zA-Z0-9]+))? - (?:\ +|$) - /sx', $def, $m, 0, $pos - ) - ) { - // extract available options - $options = preg_split('/ *\| */', trim($m['options']), 0, PREG_SPLIT_NO_EMPTY); - - // remove dupes - array_unique($options); - - // prepare item - $item = array( - 'name' => isset($m['groupName']) ? $m['groupName'] : 'unnamedGroup' . $unnamedGroupCounter++, - 'literal' => true, - 'required' => false, - 'positional' => true, - 'alternatives' => $options, - 'hasValue' => false, - ); - } - - /** - * Required literal param alternative - * ( something | somethingElse | anotherOne ) - * ( something | somethingElse | anotherOne ):namedGroup - */ - elseif (preg_match('/ - \G - \( - (?P - (?: - \ *? - (?P[a-zA-Z][a-zA-Z0-9_\-]+) - \ *? - (?:\||(?=\))) - \ *? - )+ - ) - \) - (?:\:(?P[a-zA-Z0-9]+))? - (?:\ +|$) - /sx', $def, $m, 0, $pos - )) { - // extract available options - $options = preg_split('/ *\| */', trim($m['options']), 0, PREG_SPLIT_NO_EMPTY); - - // remove dupes - array_unique($options); - - // prepare item - $item = array( - 'name' => isset($m['groupName']) ? $m['groupName']:'unnamedGroupAt' . $unnamedGroupCounter++, - 'literal' => true, - 'required' => true, - 'positional' => true, - 'alternatives' => $options, - 'hasValue' => false, - ); - } - /** - * Required long/short flag alternative - * ( --something | --somethingElse | --anotherOne | -s | -a ) - * ( --something | --somethingElse | --anotherOne | -s | -a ):namedGroup - */ - elseif (preg_match('/ - \G - \( - (?P - (?: - \ *? - \-+(?P[a-zA-Z0-9][a-zA-Z0-9_\-]*?) - \ *? - (?:\||(?=\))) - \ *? - )+ - ) - \) - (?:\:(?P[a-zA-Z0-9]+))? - (?:\ +|$) - /sx', $def, $m, 0, $pos - )) { - // extract available options - $options = preg_split('/ *\| */', trim($m['options']), 0, PREG_SPLIT_NO_EMPTY); - - // remove dupes - array_unique($options); - - // remove prefix - array_walk($options, function (&$val, $key) { - $val = ltrim($val, '-'); - }); - - // prepare item - $item = array( - 'name' => isset($m['groupName']) ? $m['groupName']:'unnamedGroupAt' . $unnamedGroupCounter++, - 'literal' => false, - 'required' => true, - 'positional' => false, - 'alternatives' => $options, - 'hasValue' => false, - ); - } - /** - * Optional flag alternative - * [ --something | --somethingElse | --anotherOne | -s | -a ] - * [ --something | --somethingElse | --anotherOne | -s | -a ]:namedGroup - */ - elseif (preg_match('/ - \G - \[ - (?P - (?: - \ *? - \-+(?P[a-zA-Z0-9][a-zA-Z0-9_\-]*?) - \ *? - (?:\||(?=\])) - \ *? - )+ - ) - \] - (?:\:(?P[a-zA-Z0-9]+))? - (?:\ +|$) - /sx', $def, $m, 0, $pos - )) { - // extract available options - $options = preg_split('/ *\| */', trim($m['options']), 0, PREG_SPLIT_NO_EMPTY); - - // remove dupes - array_unique($options); - - // remove prefix - array_walk($options, function (&$val, $key) { - $val = ltrim($val, '-'); - }); - - // prepare item - $item = array( - 'name' => isset($m['groupName']) ? $m['groupName']:'unnamedGroupAt' . $unnamedGroupCounter++, - 'literal' => false, - 'required' => false, - 'positional' => false, - 'alternatives' => $options, - 'hasValue' => false, - ); - } else { - throw new Exception\InvalidArgumentException( - 'Cannot understand Console route at "' . substr($def, $pos) . '"' - ); - } - - $pos += strlen($m[0]); - $parts[] = $item; - } - - return $parts; - } - - /** - * Returns list of names representing single parameter - * - * @param string $name - * @return string - */ - private function getAliases($name) - { - $namesToMatch = array($name); - foreach ($this->aliases as $alias => $canonical) { - if ($name == $canonical) { - $namesToMatch[] = $alias; - } - } - return $namesToMatch; - } - - /** - * Returns canonical name of a parameter - * - * @param string $name - * @return string - */ - private function getCanonicalName($name) - { - if (isset($this->aliases[$name])) { - return $this->aliases[$name]; - } - return $name; - } - - /** - * Match parameters against route passed to constructor - * - * @param array $params - * @return array|null - */ - public function match($params) - { - $matches = array(); - - /* - * Extract positional and named parts - */ - $positional = $named = array(); - foreach ($this->parts as &$part) { - if ($part['positional']) { - $positional[] = &$part; - } else { - $named[] = &$part; - } - } - - /* - * Scan for named parts inside Console params - */ - foreach ($named as &$part) { - /* - * Prepare match regex - */ - if (isset($part['alternatives'])) { - // an alternative of flags - $regex = '/^\-+(?P'; - - $alternativeAliases = array(); - foreach ($part['alternatives'] as $alternative) { - $alternativeAliases[] = '(?:' . implode('|', $this->getAliases($alternative)) . ')'; - } - - $regex .= join('|', $alternativeAliases); - - if ($part['hasValue']) { - $regex .= ')(?:\=(?P.*?)$)?$/'; - } else { - $regex .= ')$/i'; - } - } else { - // a single named flag - $name = '(?:' . implode('|', $this->getAliases($part['name'])) . ')'; - - if ($part['short'] === true) { - // short variant - if ($part['hasValue']) { - $regex = '/^\-' . $name . '(?:\=(?P.*?)$)?$/i'; - } else { - $regex = '/^\-' . $name . '$/i'; - } - } elseif ($part['short'] === false) { - // long variant - if ($part['hasValue']) { - $regex = '/^\-{2,}' . $name . '(?:\=(?P.*?)$)?$/i'; - } else { - $regex = '/^\-{2,}' . $name . '$/i'; - } - } - } - - /* - * Look for param - */ - $value = $param = null; - for ($x = 0, $count = count($params); $x < $count; $x++) { - if (preg_match($regex, $params[$x], $m)) { - // found param - $param = $params[$x]; - - // prevent further scanning of this param - array_splice($params, $x, 1); - - if (isset($m['value'])) { - $value = $m['value']; - } - - if (isset($m['name'])) { - $matchedName = $this->getCanonicalName($m['name']); - } - - break; - } - } - - - if (!$param) { - /* - * Drop out if that was a mandatory param - */ - if ($part['required']) { - return null; - } - - /* - * Continue to next positional param - */ - else { - continue; - } - } - - - /* - * Value for flags is always boolean - */ - if ($param && !$part['hasValue']) { - $value = true; - } - - /* - * Try to retrieve value if it is expected - */ - if ((null === $value || "" === $value) && $part['hasValue']) { - if ($x < count($params)+1 && isset($params[$x])) { - // retrieve value from adjacent param - $value = $params[$x]; - - // prevent further scanning of this param - array_splice($params, $x, 1); - } else { - // there are no more params available - return null; - } - } - - /* - * Validate the value against constraints - */ - if ($part['hasValue'] && isset($this->constraints[$part['name']])) { - if ( - !preg_match($this->constraints[$part['name']], $value) - ) { - // constraint failed - return null; - } - } - - /* - * Store the value - */ - if ($part['hasValue']) { - $matches[$part['name']] = $value; - } else { - $matches[$part['name']] = true; - } - - /* - * If there are alternatives, fill them - */ - if (isset($part['alternatives'])) { - if ($part['hasValue']) { - foreach ($part['alternatives'] as $alt) { - if ($alt === $matchedName && !isset($matches[$alt])) { - $matches[$alt] = $value; - } elseif (!isset($matches[$alt])) { - $matches[$alt] = null; - } - } - } else { - foreach ($part['alternatives'] as $alt) { - if ($alt === $matchedName && !isset($matches[$alt])) { - $matches[$alt] = isset($this->defaults[$alt])? $this->defaults[$alt] : true; - } elseif (!isset($matches[$alt])) { - $matches[$alt] = false; - } - } - } - } - } - - /* - * Scan for left-out flags that should result in a mismatch - */ - foreach ($params as $param) { - if (preg_match('#^\-+#', $param)) { - return null; // there is an unrecognized flag - } - } - - /* - * Go through all positional params - */ - $argPos = 0; - foreach ($positional as &$part) { - /* - * Check if param exists - */ - if (!isset($params[$argPos])) { - if ($part['required']) { - // cannot find required positional param - return null; - } else { - // stop matching - break; - } - } - - $value = $params[$argPos]; - - /* - * Check if literal param matches - */ - if ($part['literal']) { - if ( - (isset($part['alternatives']) && !in_array($value, $part['alternatives'])) || - (!isset($part['alternatives']) && $value != $part['name']) - ) { - return null; - } - } - - /* - * Validate the value against constraints - */ - if ($part['hasValue'] && isset($this->constraints[$part['name']])) { - if ( - !preg_match($this->constraints[$part['name']], $value) - ) { - // constraint failed - return null; - } - } - - /* - * Store the value - */ - if ($part['hasValue']) { - $matches[$part['name']] = $value; - } elseif (isset($part['alternatives'])) { - // from all alternatives set matching parameter to TRUE and the rest to FALSE - foreach ($part['alternatives'] as $alt) { - if ($alt == $value) { - $matches[$alt] = isset($this->defaults[$alt])? $this->defaults[$alt] : true; - } else { - $matches[$alt] = false; - } - } - - // set alternatives group value - $matches[$part['name']] = $value; - } elseif (!$part['required']) { - // set optional parameter flag - $name = $part['name']; - $matches[$name] = isset($this->defaults[$name])? $this->defaults[$name] : true; - } - - /* - * Advance to next argument - */ - $argPos++; - } - - /* - * Check if we have consumed all positional parameters - */ - if ($argPos < count($params)) { - return null; // there are extraneous params that were not consumed - } - - /* - * Any optional flags that were not entered have value false - */ - foreach ($this->parts as &$part) { - if (!$part['required'] && !$part['hasValue']) { - if (!isset($matches[$part['name']])) { - $matches[$part['name']] = false; - } - // unset alternatives also should be false - if (isset($part['alternatives'])) { - foreach ($part['alternatives'] as $alt) { - if (!isset($matches[$alt])) { - $matches[$alt] = false; - } - } - } - } - } - - // run filters - foreach ($matches as $name => $value) { - if (isset($this->filters[$name])) { - $matches[$name] = $this->filters[$name]->filter($value); - } - } - - // run validators - $valid = true; - foreach ($matches as $name => $value) { - if (isset($this->validators[$name])) { - $valid &= $this->validators[$name]->isValid($value); - } - } - - if (!$valid) { - return null; - } - - return array_replace($this->defaults, $matches); - } -} diff --git a/library/Zend/Console/RouteMatcher/RouteMatcherInterface.php b/library/Zend/Console/RouteMatcher/RouteMatcherInterface.php deleted file mode 100755 index 62f463c33..000000000 --- a/library/Zend/Console/RouteMatcher/RouteMatcherInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -=5.3.23", - "zendframework/zend-stdlib": "self.version" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Crypt/BlockCipher.php b/library/Zend/Crypt/BlockCipher.php deleted file mode 100755 index 9b2a713ec..000000000 --- a/library/Zend/Crypt/BlockCipher.php +++ /dev/null @@ -1,489 +0,0 @@ -cipher = $cipher; - } - - /** - * Factory. - * - * @param string $adapter - * @param array $options - * @return BlockCipher - */ - public static function factory($adapter, $options = array()) - { - $plugins = static::getSymmetricPluginManager(); - $adapter = $plugins->get($adapter, (array) $options); - - return new static($adapter); - } - - /** - * Returns the symmetric cipher plugin manager. If it doesn't exist it's created. - * - * @return SymmetricPluginManager - */ - public static function getSymmetricPluginManager() - { - if (static::$symmetricPlugins === null) { - static::setSymmetricPluginManager(new SymmetricPluginManager()); - } - - return static::$symmetricPlugins; - } - - /** - * Set the symmetric cipher plugin manager - * - * @param string|SymmetricPluginManager $plugins - * @throws Exception\InvalidArgumentException - */ - public static function setSymmetricPluginManager($plugins) - { - if (is_string($plugins)) { - if (!class_exists($plugins)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Unable to locate symmetric cipher plugins using class "%s"; class does not exist', - $plugins - )); - } - $plugins = new $plugins(); - } - if (!$plugins instanceof SymmetricPluginManager) { - throw new Exception\InvalidArgumentException(sprintf( - 'Expected an instance or extension of %s\SymmetricPluginManager; received "%s"', - __NAMESPACE__, - (is_object($plugins) ? get_class($plugins) : gettype($plugins)) - )); - } - static::$symmetricPlugins = $plugins; - } - - /** - * Set the symmetric cipher - * - * @param SymmetricInterface $cipher - * @return BlockCipher - */ - public function setCipher(SymmetricInterface $cipher) - { - $this->cipher = $cipher; - return $this; - } - - /** - * Get symmetric cipher - * - * @return SymmetricInterface - */ - public function getCipher() - { - return $this->cipher; - } - - /** - * Set the number of iterations for Pbkdf2 - * - * @param int $num - * @return BlockCipher - */ - public function setKeyIteration($num) - { - $this->keyIteration = (int) $num; - - return $this; - } - - /** - * Get the number of iterations for Pbkdf2 - * - * @return int - */ - public function getKeyIteration() - { - return $this->keyIteration; - } - - /** - * Set the salt (IV) - * - * @param string $salt - * @return BlockCipher - * @throws Exception\InvalidArgumentException - */ - public function setSalt($salt) - { - try { - $this->cipher->setSalt($salt); - } catch (Symmetric\Exception\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException("The salt is not valid: " . $e->getMessage()); - } - $this->saltSetted = true; - - return $this; - } - - /** - * Get the salt (IV) according to the size requested by the algorithm - * - * @return string - */ - public function getSalt() - { - return $this->cipher->getSalt(); - } - - /** - * Get the original salt value - * - * @return string - */ - public function getOriginalSalt() - { - return $this->cipher->getOriginalSalt(); - } - - /** - * Enable/disable the binary output - * - * @param bool $value - * @return BlockCipher - */ - public function setBinaryOutput($value) - { - $this->binaryOutput = (bool) $value; - - return $this; - } - - /** - * Get the value of binary output - * - * @return bool - */ - public function getBinaryOutput() - { - return $this->binaryOutput; - } - - /** - * Set the encryption/decryption key - * - * @param string $key - * @return BlockCipher - * @throws Exception\InvalidArgumentException - */ - public function setKey($key) - { - if (empty($key)) { - throw new Exception\InvalidArgumentException('The key cannot be empty'); - } - $this->key = $key; - - return $this; - } - - /** - * Get the key - * - * @return string - */ - public function getKey() - { - return $this->key; - } - - /** - * Set algorithm of the symmetric cipher - * - * @param string $algo - * @return BlockCipher - * @throws Exception\InvalidArgumentException - */ - public function setCipherAlgorithm($algo) - { - if (empty($this->cipher)) { - throw new Exception\InvalidArgumentException('No symmetric cipher specified'); - } - try { - $this->cipher->setAlgorithm($algo); - } catch (Symmetric\Exception\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException($e->getMessage()); - } - - return $this; - } - - /** - * Get the cipher algorithm - * - * @return string|bool - */ - public function getCipherAlgorithm() - { - if (!empty($this->cipher)) { - return $this->cipher->getAlgorithm(); - } - - return false; - } - - /** - * Get the supported algorithms of the symmetric cipher - * - * @return array - */ - public function getCipherSupportedAlgorithms() - { - if (!empty($this->cipher)) { - return $this->cipher->getSupportedAlgorithms(); - } - - return array(); - } - - /** - * Set the hash algorithm for HMAC authentication - * - * @param string $hash - * @return BlockCipher - * @throws Exception\InvalidArgumentException - */ - public function setHashAlgorithm($hash) - { - if (!Hash::isSupported($hash)) { - throw new Exception\InvalidArgumentException( - "The specified hash algorithm '{$hash}' is not supported by Zend\Crypt\Hash" - ); - } - $this->hash = $hash; - - return $this; - } - - /** - * Get the hash algorithm for HMAC authentication - * - * @return string - */ - public function getHashAlgorithm() - { - return $this->hash; - } - - /** - * Set the hash algorithm for the Pbkdf2 - * - * @param string $hash - * @return BlockCipher - * @throws Exception\InvalidArgumentException - */ - public function setPbkdf2HashAlgorithm($hash) - { - if (!Hash::isSupported($hash)) { - throw new Exception\InvalidArgumentException( - "The specified hash algorithm '{$hash}' is not supported by Zend\Crypt\Hash" - ); - } - $this->pbkdf2Hash = $hash; - - return $this; - } - - /** - * Get the Pbkdf2 hash algorithm - * - * @return string - */ - public function getPbkdf2HashAlgorithm() - { - return $this->pbkdf2Hash; - } - - /** - * Encrypt then authenticate using HMAC - * - * @param string $data - * @return string - * @throws Exception\InvalidArgumentException - */ - public function encrypt($data) - { - // 0 (as integer), 0.0 (as float) & '0' (as string) will return false, though these should be allowed - // Must be a string, integer, or float in order to encrypt - if ((is_string($data) && $data === '') - || is_array($data) - || is_object($data) - ) { - throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty'); - } - - // Cast to string prior to encrypting - if (!is_string($data)) { - $data = (string) $data; - } - - if (empty($this->cipher)) { - throw new Exception\InvalidArgumentException('No symmetric cipher specified'); - } - if (empty($this->key)) { - throw new Exception\InvalidArgumentException('No key specified for the encryption'); - } - $keySize = $this->cipher->getKeySize(); - // generate a random salt (IV) if the salt has not been set - if (!$this->saltSetted) { - $this->cipher->setSalt(Rand::getBytes($this->cipher->getSaltSize(), true)); - } - // generate the encryption key and the HMAC key for the authentication - $hash = Pbkdf2::calc( - $this->getPbkdf2HashAlgorithm(), - $this->getKey(), - $this->getSalt(), - $this->keyIteration, - $keySize * 2 - ); - // set the encryption key - $this->cipher->setKey(substr($hash, 0, $keySize)); - // set the key for HMAC - $keyHmac = substr($hash, $keySize); - // encryption - $ciphertext = $this->cipher->encrypt($data); - // HMAC - $hmac = Hmac::compute($keyHmac, $this->hash, $this->cipher->getAlgorithm() . $ciphertext); - if (!$this->binaryOutput) { - $ciphertext = base64_encode($ciphertext); - } - - return $hmac . $ciphertext; - } - - /** - * Decrypt - * - * @param string $data - * @return string|bool - * @throws Exception\InvalidArgumentException - */ - public function decrypt($data) - { - if (!is_string($data)) { - throw new Exception\InvalidArgumentException('The data to decrypt must be a string'); - } - if ('' === $data) { - throw new Exception\InvalidArgumentException('The data to decrypt cannot be empty'); - } - if (empty($this->key)) { - throw new Exception\InvalidArgumentException('No key specified for the decryption'); - } - if (empty($this->cipher)) { - throw new Exception\InvalidArgumentException('No symmetric cipher specified'); - } - $hmacSize = Hmac::getOutputSize($this->hash); - $hmac = substr($data, 0, $hmacSize); - $ciphertext = substr($data, $hmacSize); - if (!$this->binaryOutput) { - $ciphertext = base64_decode($ciphertext); - } - $iv = substr($ciphertext, 0, $this->cipher->getSaltSize()); - $keySize = $this->cipher->getKeySize(); - // generate the encryption key and the HMAC key for the authentication - $hash = Pbkdf2::calc( - $this->getPbkdf2HashAlgorithm(), - $this->getKey(), - $iv, - $this->keyIteration, - $keySize * 2 - ); - // set the decryption key - $this->cipher->setKey(substr($hash, 0, $keySize)); - // set the key for HMAC - $keyHmac = substr($hash, $keySize); - $hmacNew = Hmac::compute($keyHmac, $this->hash, $this->cipher->getAlgorithm() . $ciphertext); - if (!Utils::compareStrings($hmacNew, $hmac)) { - return false; - } - - return $this->cipher->decrypt($ciphertext); - } -} diff --git a/library/Zend/Crypt/CONTRIBUTING.md b/library/Zend/Crypt/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Crypt/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Crypt/Exception/ExceptionInterface.php b/library/Zend/Crypt/Exception/ExceptionInterface.php deleted file mode 100755 index ef9374361..000000000 --- a/library/Zend/Crypt/Exception/ExceptionInterface.php +++ /dev/null @@ -1,14 +0,0 @@ - MHASH_MD2, - 'md4' => MHASH_MD4, - 'md5' => MHASH_MD5, - 'sha1' => MHASH_SHA1, - 'sha224' => MHASH_SHA224, - 'sha256' => MHASH_SHA256, - 'sha384' => MHASH_SHA384, - 'sha512' => MHASH_SHA512, - 'ripemd128' => MHASH_RIPEMD128, - 'ripemd256' => MHASH_RIPEMD256, - 'ripemd320' => MHASH_RIPEMD320, - 'haval128,3' => MHASH_HAVAL128, - 'haval160,3' => MHASH_HAVAL160, - 'haval192,3' => MHASH_HAVAL192, - 'haval224,3' => MHASH_HAVAL224, - 'haval256,3' => MHASH_HAVAL256, - 'tiger128,3' => MHASH_TIGER128, - 'riger160,3' => MHASH_TIGER160, - 'whirpool' => MHASH_WHIRLPOOL, - 'snefru256' => MHASH_SNEFRU256, - 'gost' => MHASH_GOST, - 'crc32' => MHASH_CRC32, - 'crc32b' => MHASH_CRC32B - ); - - /** - * Generate the new key - * - * @param string $hash The hash algorithm to be used by HMAC - * @param string $password The source password/key - * @param int $bytes The output size in bytes - * @param string $salt The salt of the algorithm - * @throws Exception\InvalidArgumentException - * @return string - */ - public static function calc($hash, $password, $salt, $bytes) - { - if (!in_array($hash, array_keys(static::$supportedMhashAlgos))) { - throw new Exception\InvalidArgumentException("The hash algorithm $hash is not supported by " . __CLASS__); - } - if (strlen($salt)<8) { - throw new Exception\InvalidArgumentException('The salt size must be at least of 8 bytes'); - } - return mhash_keygen_s2k(static::$supportedMhashAlgos[$hash], $password, $salt, $bytes); - } -} diff --git a/library/Zend/Crypt/Key/Derivation/Scrypt.php b/library/Zend/Crypt/Key/Derivation/Scrypt.php deleted file mode 100755 index da2a78367..000000000 --- a/library/Zend/Crypt/Key/Derivation/Scrypt.php +++ /dev/null @@ -1,340 +0,0 @@ - 0 and a power of 2"); - } - if ($n > PHP_INT_MAX / 128 / $r) { - throw new Exception\InvalidArgumentException("Parameter n is too large"); - } - if ($r > PHP_INT_MAX / 128 / $p) { - throw new Exception\InvalidArgumentException("Parameter r is too large"); - } - - if (extension_loaded('Scrypt')) { - if ($length < 16) { - throw new Exception\InvalidArgumentException("Key length is too low, must be greater or equal to 16"); - } - return self::hex2bin(scrypt($password, $salt, $n, $r, $p, $length)); - } - - $b = Pbkdf2::calc('sha256', $password, $salt, 1, $p * 128 * $r); - - $s = ''; - for ($i = 0; $i < $p; $i++) { - $s .= self::scryptROMix(substr($b, $i * 128 * $r, 128 * $r), $n, $r); - } - - return Pbkdf2::calc('sha256', $password, $s, 1, $length); - } - - /** - * scryptROMix - * - * @param string $b - * @param int $n - * @param int $r - * @return string - * @see https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01#section-4 - */ - protected static function scryptROMix($b, $n, $r) - { - $x = $b; - $v = array(); - for ($i = 0; $i < $n; $i++) { - $v[$i] = $x; - $x = self::scryptBlockMix($x, $r); - } - for ($i = 0; $i < $n; $i++) { - $j = self::integerify($x) % $n; - $t = $x ^ $v[$j]; - $x = self::scryptBlockMix($t, $r); - } - return $x; - } - - /** - * scryptBlockMix - * - * @param string $b - * @param int $r - * @return string - * @see https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01#section-3 - */ - protected static function scryptBlockMix($b, $r) - { - $x = substr($b, -64); - $even = ''; - $odd = ''; - $len = 2 * $r; - - for ($i = 0; $i < $len; $i++) { - if (PHP_INT_SIZE === 4) { - $x = self::salsa208Core32($x ^ substr($b, 64 * $i, 64)); - } else { - $x = self::salsa208Core64($x ^ substr($b, 64 * $i, 64)); - } - if ($i % 2 == 0) { - $even .= $x; - } else { - $odd .= $x; - } - } - return $even . $odd; - } - - /** - * Salsa 20/8 core (32 bit version) - * - * @param string $b - * @return string - * @see https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01#section-2 - * @see http://cr.yp.to/salsa20.html - */ - protected static function salsa208Core32($b) - { - $b32 = array(); - for ($i = 0; $i < 16; $i++) { - list(, $b32[$i]) = unpack("V", substr($b, $i * 4, 4)); - } - - $x = $b32; - for ($i = 0; $i < 8; $i += 2) { - $a = ($x[ 0] + $x[12]); - $x[ 4] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[ 4] + $x[ 0]); - $x[ 8] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[ 8] + $x[ 4]); - $x[12] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[12] + $x[ 8]); - $x[ 0] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[ 5] + $x[ 1]); - $x[ 9] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[ 9] + $x[ 5]); - $x[13] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[13] + $x[ 9]); - $x[ 1] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[ 1] + $x[13]); - $x[ 5] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[10] + $x[ 6]); - $x[14] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[14] + $x[10]); - $x[ 2] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[ 2] + $x[14]); - $x[ 6] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[ 6] + $x[ 2]); - $x[10] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[15] + $x[11]); - $x[ 3] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[ 3] + $x[15]); - $x[ 7] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[ 7] + $x[ 3]); - $x[11] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[11] + $x[ 7]); - $x[15] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[ 0] + $x[ 3]); - $x[ 1] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[ 1] + $x[ 0]); - $x[ 2] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[ 2] + $x[ 1]); - $x[ 3] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[ 3] + $x[ 2]); - $x[ 0] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[ 5] + $x[ 4]); - $x[ 6] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[ 6] + $x[ 5]); - $x[ 7] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[ 7] + $x[ 6]); - $x[ 4] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[ 4] + $x[ 7]); - $x[ 5] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[10] + $x[ 9]); - $x[11] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[11] + $x[10]); - $x[ 8] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[ 8] + $x[11]); - $x[ 9] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[ 9] + $x[ 8]); - $x[10] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - $a = ($x[15] + $x[14]); - $x[12] ^= ($a << 7) | ($a >> 25) & 0x7f; - $a = ($x[12] + $x[15]); - $x[13] ^= ($a << 9) | ($a >> 23) & 0x1ff; - $a = ($x[13] + $x[12]); - $x[14] ^= ($a << 13) | ($a >> 19) & 0x1fff; - $a = ($x[14] + $x[13]); - $x[15] ^= ($a << 18) | ($a >> 14) & 0x3ffff; - } - for ($i = 0; $i < 16; $i++) { - $b32[$i] = $b32[$i] + $x[$i]; - } - $result = ''; - for ($i = 0; $i < 16; $i++) { - $result .= pack("V", $b32[$i]); - } - - return $result; - } - - /** - * Salsa 20/8 core (64 bit version) - * - * @param string $b - * @return string - * @see https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01#section-2 - * @see http://cr.yp.to/salsa20.html - */ - protected static function salsa208Core64($b) - { - $b32 = array(); - for ($i = 0; $i < 16; $i++) { - list(, $b32[$i]) = unpack("V", substr($b, $i * 4, 4)); - } - - $x = $b32; - for ($i = 0; $i < 8; $i += 2) { - $a = ($x[ 0] + $x[12]) & 0xffffffff; - $x[ 4] ^= ($a << 7) | ($a >> 25); - $a = ($x[ 4] + $x[ 0]) & 0xffffffff; - $x[ 8] ^= ($a << 9) | ($a >> 23); - $a = ($x[ 8] + $x[ 4]) & 0xffffffff; - $x[12] ^= ($a << 13) | ($a >> 19); - $a = ($x[12] + $x[ 8]) & 0xffffffff; - $x[ 0] ^= ($a << 18) | ($a >> 14); - $a = ($x[ 5] + $x[ 1]) & 0xffffffff; - $x[ 9] ^= ($a << 7) | ($a >> 25); - $a = ($x[ 9] + $x[ 5]) & 0xffffffff; - $x[13] ^= ($a << 9) | ($a >> 23); - $a = ($x[13] + $x[ 9]) & 0xffffffff; - $x[ 1] ^= ($a << 13) | ($a >> 19); - $a = ($x[ 1] + $x[13]) & 0xffffffff; - $x[ 5] ^= ($a << 18) | ($a >> 14); - $a = ($x[10] + $x[ 6]) & 0xffffffff; - $x[14] ^= ($a << 7) | ($a >> 25); - $a = ($x[14] + $x[10]) & 0xffffffff; - $x[ 2] ^= ($a << 9) | ($a >> 23); - $a = ($x[ 2] + $x[14]) & 0xffffffff; - $x[ 6] ^= ($a << 13) | ($a >> 19); - $a = ($x[ 6] + $x[ 2]) & 0xffffffff; - $x[10] ^= ($a << 18) | ($a >> 14); - $a = ($x[15] + $x[11]) & 0xffffffff; - $x[ 3] ^= ($a << 7) | ($a >> 25); - $a = ($x[ 3] + $x[15]) & 0xffffffff; - $x[ 7] ^= ($a << 9) | ($a >> 23); - $a = ($x[ 7] + $x[ 3]) & 0xffffffff; - $x[11] ^= ($a << 13) | ($a >> 19); - $a = ($x[11] + $x[ 7]) & 0xffffffff; - $x[15] ^= ($a << 18) | ($a >> 14); - $a = ($x[ 0] + $x[ 3]) & 0xffffffff; - $x[ 1] ^= ($a << 7) | ($a >> 25); - $a = ($x[ 1] + $x[ 0]) & 0xffffffff; - $x[ 2] ^= ($a << 9) | ($a >> 23); - $a = ($x[ 2] + $x[ 1]) & 0xffffffff; - $x[ 3] ^= ($a << 13) | ($a >> 19); - $a = ($x[ 3] + $x[ 2]) & 0xffffffff; - $x[ 0] ^= ($a << 18) | ($a >> 14); - $a = ($x[ 5] + $x[ 4]) & 0xffffffff; - $x[ 6] ^= ($a << 7) | ($a >> 25); - $a = ($x[ 6] + $x[ 5]) & 0xffffffff; - $x[ 7] ^= ($a << 9) | ($a >> 23); - $a = ($x[ 7] + $x[ 6]) & 0xffffffff; - $x[ 4] ^= ($a << 13) | ($a >> 19); - $a = ($x[ 4] + $x[ 7]) & 0xffffffff; - $x[ 5] ^= ($a << 18) | ($a >> 14); - $a = ($x[10] + $x[ 9]) & 0xffffffff; - $x[11] ^= ($a << 7) | ($a >> 25); - $a = ($x[11] + $x[10]) & 0xffffffff; - $x[ 8] ^= ($a << 9) | ($a >> 23); - $a = ($x[ 8] + $x[11]) & 0xffffffff; - $x[ 9] ^= ($a << 13) | ($a >> 19); - $a = ($x[ 9] + $x[ 8]) & 0xffffffff; - $x[10] ^= ($a << 18) | ($a >> 14); - $a = ($x[15] + $x[14]) & 0xffffffff; - $x[12] ^= ($a << 7) | ($a >> 25); - $a = ($x[12] + $x[15]) & 0xffffffff; - $x[13] ^= ($a << 9) | ($a >> 23); - $a = ($x[13] + $x[12]) & 0xffffffff; - $x[14] ^= ($a << 13) | ($a >> 19); - $a = ($x[14] + $x[13]) & 0xffffffff; - $x[15] ^= ($a << 18) | ($a >> 14); - } - for ($i = 0; $i < 16; $i++) { - $b32[$i] = ($b32[$i] + $x[$i]) & 0xffffffff; - } - $result = ''; - for ($i = 0; $i < 16; $i++) { - $result .= pack("V", $b32[$i]); - } - - return $result; - } - - /** - * Integerify - * - * Integerify (B[0] ... B[2 * r - 1]) is defined as the result - * of interpreting B[2 * r - 1] as a little-endian integer. - * Each block B is a string of 64 bytes. - * - * @param string $b - * @return int - * @see https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01#section-4 - */ - protected static function integerify($b) - { - $v = 'v'; - if (PHP_INT_SIZE === 8) { - $v = 'V'; - } - list(,$n) = unpack($v, substr($b, -64)); - return $n; - } - - /** - * Convert hex string in a binary string - * - * @param string $hex - * @return string - */ - protected static function hex2bin($hex) - { - if (PHP_VERSION_ID >= 50400) { - return hex2bin($hex); - } - $len = strlen($hex); - $result = ''; - for ($i = 0; $i < $len; $i+=2) { - $result .= chr(hexdec($hex[$i] . $hex[$i+1])); - } - return $result; - } -} diff --git a/library/Zend/Crypt/Password/Apache.php b/library/Zend/Crypt/Password/Apache.php deleted file mode 100755 index d9359827a..000000000 --- a/library/Zend/Crypt/Password/Apache.php +++ /dev/null @@ -1,301 +0,0 @@ - $value) { - switch (strtolower($key)) { - case 'format': - $this->setFormat($value); - break; - case 'authname': - $this->setAuthName($value); - break; - case 'username': - $this->setUserName($value); - break; - } - } - } - - /** - * Generate the hash of a password - * - * @param string $password - * @throws Exception\RuntimeException - * @return string - */ - public function create($password) - { - if (empty($this->format)) { - throw new Exception\RuntimeException( - 'You must specify a password format' - ); - } - switch ($this->format) { - case 'crypt': - $hash = crypt($password, Rand::getString(2, self::ALPHA64)); - break; - case 'sha1': - $hash = '{SHA}' . base64_encode(sha1($password, true)); - break; - case 'md5': - $hash = $this->apr1Md5($password); - break; - case 'digest': - if (empty($this->userName) || empty($this->authName)) { - throw new Exception\RuntimeException( - 'You must specify UserName and AuthName (realm) to generate the digest' - ); - } - $hash = md5($this->userName . ':' . $this->authName . ':' .$password); - break; - } - - return $hash; - } - - /** - * Verify if a password is correct against a hash value - * - * @param string $password - * @param string $hash - * @return bool - */ - public function verify($password, $hash) - { - if (substr($hash, 0, 5) === '{SHA}') { - $hash2 = '{SHA}' . base64_encode(sha1($password, true)); - return ($hash === $hash2); - } - if (substr($hash, 0, 6) === '$apr1$') { - $token = explode('$', $hash); - if (empty($token[2])) { - throw new Exception\InvalidArgumentException( - 'The APR1 password format is not valid' - ); - } - $hash2 = $this->apr1Md5($password, $token[2]); - return ($hash === $hash2); - } - if (strlen($hash) > 13) { // digest - if (empty($this->userName) || empty($this->authName)) { - throw new Exception\RuntimeException( - 'You must specify UserName and AuthName (realm) to verify the digest' - ); - } - $hash2 = md5($this->userName . ':' . $this->authName . ':' .$password); - return ($hash === $hash2); - } - return (crypt($password, $hash) === $hash); - } - - /** - * Set the format of the password - * - * @param string $format - * @throws Exception\InvalidArgumentException - * @return Apache - */ - public function setFormat($format) - { - $format = strtolower($format); - if (!in_array($format, $this->supportedFormat)) { - throw new Exception\InvalidArgumentException(sprintf( - 'The format %s specified is not valid. The supported formats are: %s', - $format, - implode(',', $this->supportedFormat) - )); - } - $this->format = $format; - - return $this; - } - - /** - * Get the format of the password - * - * @return string - */ - public function getFormat() - { - return $this->format; - } - - /** - * Set the AuthName (for digest authentication) - * - * @param string $name - * @return Apache - */ - public function setAuthName($name) - { - $this->authName = $name; - - return $this; - } - - /** - * Get the AuthName (for digest authentication) - * - * @return string - */ - public function getAuthName() - { - return $this->authName; - } - - /** - * Set the username - * - * @param string $name - * @return Apache - */ - public function setUserName($name) - { - $this->userName = $name; - - return $this; - } - - /** - * Get the username - * - * @return string - */ - public function getUserName() - { - return $this->userName; - } - - /** - * Convert a binary string using the alphabet "./0-9A-Za-z" - * - * @param string $value - * @return string - */ - protected function toAlphabet64($value) - { - return strtr(strrev(substr(base64_encode($value), 2)), self::BASE64, self::ALPHA64); - } - - /** - * APR1 MD5 algorithm - * - * @param string $password - * @param null|string $salt - * @return string - */ - protected function apr1Md5($password, $salt = null) - { - if (null === $salt) { - $salt = Rand::getString(8, self::ALPHA64); - } else { - if (strlen($salt) !== 8) { - throw new Exception\InvalidArgumentException( - 'The salt value for APR1 algorithm must be 8 characters long' - ); - } - for ($i = 0; $i < 8; $i++) { - if (strpos(self::ALPHA64, $salt[$i]) === false) { - throw new Exception\InvalidArgumentException( - 'The salt value must be a string in the alphabet "./0-9A-Za-z"' - ); - } - } - } - $len = strlen($password); - $text = $password . '$apr1$' . $salt; - $bin = pack("H32", md5($password . $salt . $password)); - for ($i = $len; $i > 0; $i -= 16) { - $text .= substr($bin, 0, min(16, $i)); - } - for ($i = $len; $i > 0; $i >>= 1) { - $text .= ($i & 1) ? chr(0) : $password[0]; - } - $bin = pack("H32", md5($text)); - for ($i = 0; $i < 1000; $i++) { - $new = ($i & 1) ? $password : $bin; - if ($i % 3) { - $new .= $salt; - } - if ($i % 7) { - $new .= $password; - } - $new .= ($i & 1) ? $bin : $password; - $bin = pack("H32", md5($new)); - } - $tmp = ''; - for ($i = 0; $i < 5; $i++) { - $k = $i + 6; - $j = $i + 12; - if ($j == 16) { - $j = 5; - } - $tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp; - } - $tmp = chr(0) . chr(0) . $bin[11] . $tmp; - - return '$apr1$' . $salt . '$' . $this->toAlphabet64($tmp); - } -} diff --git a/library/Zend/Crypt/Password/Bcrypt.php b/library/Zend/Crypt/Password/Bcrypt.php deleted file mode 100755 index b489ddd48..000000000 --- a/library/Zend/Crypt/Password/Bcrypt.php +++ /dev/null @@ -1,207 +0,0 @@ - $value) { - switch (strtolower($key)) { - case 'salt': - $this->setSalt($value); - break; - case 'cost': - $this->setCost($value); - break; - } - } - } - } - - /** - * Bcrypt - * - * @param string $password - * @throws Exception\RuntimeException - * @return string - */ - public function create($password) - { - if (empty($this->salt)) { - $salt = Rand::getBytes(self::MIN_SALT_SIZE); - } else { - $salt = $this->salt; - } - $salt64 = substr(str_replace('+', '.', base64_encode($salt)), 0, 22); - /** - * Check for security flaw in the bcrypt implementation used by crypt() - * @see http://php.net/security/crypt_blowfish.php - */ - if ((PHP_VERSION_ID >= 50307) && !$this->backwardCompatibility) { - $prefix = '$2y$'; - } else { - $prefix = '$2a$'; - // check if the password contains 8-bit character - if (preg_match('/[\x80-\xFF]/', $password)) { - throw new Exception\RuntimeException( - 'The bcrypt implementation used by PHP can contain a security flaw ' . - 'using password with 8-bit character. ' . - 'We suggest to upgrade to PHP 5.3.7+ or use passwords with only 7-bit characters' - ); - } - } - $hash = crypt($password, $prefix . $this->cost . '$' . $salt64); - if (strlen($hash) < 13) { - throw new Exception\RuntimeException('Error during the bcrypt generation'); - } - return $hash; - } - - /** - * Verify if a password is correct against a hash value - * - * @param string $password - * @param string $hash - * @throws Exception\RuntimeException when the hash is unable to be processed - * @return bool - */ - public function verify($password, $hash) - { - $result = crypt($password, $hash); - if ($result === $hash) { - return true; - } - return false; - } - - /** - * Set the cost parameter - * - * @param int|string $cost - * @throws Exception\InvalidArgumentException - * @return Bcrypt - */ - public function setCost($cost) - { - if (!empty($cost)) { - $cost = (int) $cost; - if ($cost < 4 || $cost > 31) { - throw new Exception\InvalidArgumentException( - 'The cost parameter of bcrypt must be in range 04-31' - ); - } - $this->cost = sprintf('%1$02d', $cost); - } - return $this; - } - - /** - * Get the cost parameter - * - * @return string - */ - public function getCost() - { - return $this->cost; - } - - /** - * Set the salt value - * - * @param string $salt - * @throws Exception\InvalidArgumentException - * @return Bcrypt - */ - public function setSalt($salt) - { - if (strlen($salt) < self::MIN_SALT_SIZE) { - throw new Exception\InvalidArgumentException( - 'The length of the salt must be at least ' . self::MIN_SALT_SIZE . ' bytes' - ); - } - $this->salt = $salt; - return $this; - } - - /** - * Get the salt value - * - * @return string - */ - public function getSalt() - { - return $this->salt; - } - - /** - * Set the backward compatibility $2a$ instead of $2y$ for PHP 5.3.7+ - * - * @param bool $value - * @return Bcrypt - */ - public function setBackwardCompatibility($value) - { - $this->backwardCompatibility = (bool) $value; - return $this; - } - - /** - * Get the backward compatibility - * - * @return bool - */ - public function getBackwardCompatibility() - { - return $this->backwardCompatibility; - } -} diff --git a/library/Zend/Crypt/Password/Exception/ExceptionInterface.php b/library/Zend/Crypt/Password/Exception/ExceptionInterface.php deleted file mode 100755 index 5c65fb781..000000000 --- a/library/Zend/Crypt/Password/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -setPrime($prime); - $this->setGenerator($generator); - if ($privateKey !== null) { - $this->setPrivateKey($privateKey, $privateKeyFormat); - } - - // set up BigInteger adapter - $this->math = Math\BigInteger\BigInteger::factory(); - } - - /** - * Set whether to use openssl extension - * - * @static - * @param bool $flag - */ - public static function useOpensslExtension($flag = true) - { - static::$useOpenssl = (bool) $flag; - } - - /** - * Generate own public key. If a private number has not already been set, - * one will be generated at this stage. - * - * @return DiffieHellman - * @throws \Zend\Crypt\Exception\RuntimeException - */ - public function generateKeys() - { - if (function_exists('openssl_dh_compute_key') && static::$useOpenssl !== false) { - $details = array( - 'p' => $this->convert($this->getPrime(), self::FORMAT_NUMBER, self::FORMAT_BINARY), - 'g' => $this->convert($this->getGenerator(), self::FORMAT_NUMBER, self::FORMAT_BINARY) - ); - if ($this->hasPrivateKey()) { - $details['priv_key'] = $this->convert( - $this->privateKey, - self::FORMAT_NUMBER, - self::FORMAT_BINARY - ); - $opensslKeyResource = openssl_pkey_new(array('dh' => $details)); - } else { - $opensslKeyResource = openssl_pkey_new(array( - 'dh' => $details, - 'private_key_bits' => self::DEFAULT_KEY_SIZE, - 'private_key_type' => OPENSSL_KEYTYPE_DH - )); - } - - if (false === $opensslKeyResource) { - throw new Exception\RuntimeException( - 'Can not generate new key; openssl ' . openssl_error_string() - ); - } - - $data = openssl_pkey_get_details($opensslKeyResource); - - $this->setPrivateKey($data['dh']['priv_key'], self::FORMAT_BINARY); - $this->setPublicKey($data['dh']['pub_key'], self::FORMAT_BINARY); - - $this->opensslKeyResource = $opensslKeyResource; - } else { - // Private key is lazy generated in the absence of ext/openssl - $publicKey = $this->math->powmod($this->getGenerator(), $this->getPrivateKey(), $this->getPrime()); - $this->setPublicKey($publicKey); - } - - return $this; - } - - /** - * Setter for the value of the public number - * - * @param string $number - * @param string $format - * @return DiffieHellman - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function setPublicKey($number, $format = self::FORMAT_NUMBER) - { - $number = $this->convert($number, $format, self::FORMAT_NUMBER); - if (!preg_match('/^\d+$/', $number)) { - throw new Exception\InvalidArgumentException('Invalid parameter; not a positive natural number'); - } - $this->publicKey = (string) $number; - - return $this; - } - - /** - * Returns own public key for communication to the second party to this transaction - * - * @param string $format - * @return string - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function getPublicKey($format = self::FORMAT_NUMBER) - { - if ($this->publicKey === null) { - throw new Exception\InvalidArgumentException( - 'A public key has not yet been generated using a prior call to generateKeys()' - ); - } - - return $this->convert($this->publicKey, self::FORMAT_NUMBER, $format); - } - - /** - * Compute the shared secret key based on the public key received from the - * the second party to this transaction. This should agree to the secret - * key the second party computes on our own public key. - * Once in agreement, the key is known to only to both parties. - * By default, the function expects the public key to be in binary form - * which is the typical format when being transmitted. - * - * If you need the binary form of the shared secret key, call - * getSharedSecretKey() with the optional parameter for Binary output. - * - * @param string $publicKey - * @param string $publicKeyFormat - * @param string $secretKeyFormat - * @return string - * @throws \Zend\Crypt\Exception\InvalidArgumentException - * @throws \Zend\Crypt\Exception\RuntimeException - */ - public function computeSecretKey( - $publicKey, - $publicKeyFormat = self::FORMAT_NUMBER, - $secretKeyFormat = self::FORMAT_NUMBER - ) { - if (function_exists('openssl_dh_compute_key') && static::$useOpenssl !== false) { - $publicKey = $this->convert($publicKey, $publicKeyFormat, self::FORMAT_BINARY); - $secretKey = openssl_dh_compute_key($publicKey, $this->opensslKeyResource); - if (false === $secretKey) { - throw new Exception\RuntimeException( - 'Can not compute key; openssl ' . openssl_error_string() - ); - } - $this->secretKey = $this->convert($secretKey, self::FORMAT_BINARY, self::FORMAT_NUMBER); - } else { - $publicKey = $this->convert($publicKey, $publicKeyFormat, self::FORMAT_NUMBER); - if (!preg_match('/^\d+$/', $publicKey)) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter; not a positive natural number' - ); - } - $this->secretKey = $this->math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime()); - } - - return $this->getSharedSecretKey($secretKeyFormat); - } - - /** - * Return the computed shared secret key from the DiffieHellman transaction - * - * @param string $format - * @return string - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function getSharedSecretKey($format = self::FORMAT_NUMBER) - { - if (!isset($this->secretKey)) { - throw new Exception\InvalidArgumentException( - 'A secret key has not yet been computed; call computeSecretKey() first' - ); - } - - return $this->convert($this->secretKey, self::FORMAT_NUMBER, $format); - } - - /** - * Setter for the value of the prime number - * - * @param string $number - * @return DiffieHellman - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function setPrime($number) - { - if (!preg_match('/^\d+$/', $number) || $number < 11) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter; not a positive natural number or too small: ' . - 'should be a large natural number prime' - ); - } - $this->prime = (string) $number; - - return $this; - } - - /** - * Getter for the value of the prime number - * - * @param string $format - * @return string - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function getPrime($format = self::FORMAT_NUMBER) - { - if (!isset($this->prime)) { - throw new Exception\InvalidArgumentException('No prime number has been set'); - } - - return $this->convert($this->prime, self::FORMAT_NUMBER, $format); - } - - /** - * Setter for the value of the generator number - * - * @param string $number - * @return DiffieHellman - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function setGenerator($number) - { - if (!preg_match('/^\d+$/', $number) || $number < 2) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter; not a positive natural number greater than 1' - ); - } - $this->generator = (string) $number; - - return $this; - } - - /** - * Getter for the value of the generator number - * - * @param string $format - * @return string - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function getGenerator($format = self::FORMAT_NUMBER) - { - if (!isset($this->generator)) { - throw new Exception\InvalidArgumentException('No generator number has been set'); - } - - return $this->convert($this->generator, self::FORMAT_NUMBER, $format); - } - - /** - * Setter for the value of the private number - * - * @param string $number - * @param string $format - * @return DiffieHellman - * @throws \Zend\Crypt\Exception\InvalidArgumentException - */ - public function setPrivateKey($number, $format = self::FORMAT_NUMBER) - { - $number = $this->convert($number, $format, self::FORMAT_NUMBER); - if (!preg_match('/^\d+$/', $number)) { - throw new Exception\InvalidArgumentException('Invalid parameter; not a positive natural number'); - } - $this->privateKey = (string) $number; - - return $this; - } - - /** - * Getter for the value of the private number - * - * @param string $format - * @return string - */ - public function getPrivateKey($format = self::FORMAT_NUMBER) - { - if (!$this->hasPrivateKey()) { - $this->setPrivateKey($this->generatePrivateKey(), self::FORMAT_BINARY); - } - - return $this->convert($this->privateKey, self::FORMAT_NUMBER, $format); - } - - /** - * Check whether a private key currently exists. - * - * @return bool - */ - public function hasPrivateKey() - { - return isset($this->privateKey); - } - - /** - * Convert number between formats - * - * @param string $number - * @param string $inputFormat - * @param string $outputFormat - * @return string - */ - protected function convert($number, $inputFormat = self::FORMAT_NUMBER, $outputFormat = self::FORMAT_BINARY) - { - if ($inputFormat == $outputFormat) { - return $number; - } - - // convert to number - switch ($inputFormat) { - case self::FORMAT_BINARY: - case self::FORMAT_BTWOC: - $number = $this->math->binToInt($number); - break; - case self::FORMAT_NUMBER: - default: - // do nothing - break; - } - - // convert to output format - switch ($outputFormat) { - case self::FORMAT_BINARY: - return $this->math->intToBin($number); - break; - case self::FORMAT_BTWOC: - return $this->math->intToBin($number, true); - break; - case self::FORMAT_NUMBER: - default: - return $number; - break; - } - } - - /** - * In the event a private number/key has not been set by the user, - * or generated by ext/openssl, a best attempt will be made to - * generate a random key. Having a random number generator installed - * on linux/bsd is highly recommended! The alternative is not recommended - * for production unless without any other option. - * - * @return string - */ - protected function generatePrivateKey() - { - return Math\Rand::getBytes(strlen($this->getPrime()), true); - } -} diff --git a/library/Zend/Crypt/PublicKey/Rsa.php b/library/Zend/Crypt/PublicKey/Rsa.php deleted file mode 100755 index 44faaa7d7..000000000 --- a/library/Zend/Crypt/PublicKey/Rsa.php +++ /dev/null @@ -1,333 +0,0 @@ -setPrivateKey($privateKey); - } - if ($publicKey instanceof Rsa\PublicKey) { - $options->setPublicKey($publicKey); - } - - return new Rsa($options); - } - - /** - * Class constructor - * - * @param RsaOptions $options - * @throws Rsa\Exception\RuntimeException - */ - public function __construct(RsaOptions $options = null) - { - if (!extension_loaded('openssl')) { - throw new Exception\RuntimeException( - 'Zend\Crypt\PublicKey\Rsa requires openssl extension to be loaded' - ); - } - - if ($options === null) { - $this->options = new RsaOptions(); - } else { - $this->options = $options; - } - } - - /** - * Set options - * - * @param RsaOptions $options - * @return Rsa - */ - public function setOptions(RsaOptions $options) - { - $this->options = $options; - return $this; - } - - /** - * Get options - * - * @return RsaOptions - */ - public function getOptions() - { - return $this->options; - } - - /** - * Return last openssl error(s) - * - * @return string - */ - public function getOpensslErrorString() - { - $message = ''; - while (false !== ($error = openssl_error_string())) { - $message .= $error . "\n"; - } - return trim($message); - } - - /** - * Sign with private key - * - * @param string $data - * @param Rsa\PrivateKey $privateKey - * @return string - * @throws Rsa\Exception\RuntimeException - */ - public function sign($data, Rsa\PrivateKey $privateKey = null) - { - $signature = ''; - if (null === $privateKey) { - $privateKey = $this->options->getPrivateKey(); - } - - $result = openssl_sign( - $data, - $signature, - $privateKey->getOpensslKeyResource(), - $this->options->getOpensslSignatureAlgorithm() - ); - if (false === $result) { - throw new Exception\RuntimeException( - 'Can not generate signature; openssl ' . $this->getOpensslErrorString() - ); - } - - if ($this->options->getBinaryOutput()) { - return $signature; - } - - return base64_encode($signature); - } - - /** - * Verify signature with public key - * - * $signature can be encoded in base64 or not. $mode sets how the input must be processed: - * - MODE_AUTO: Check if the $signature is encoded in base64. Not recommended for performance. - * - MODE_BASE64: Decode $signature using base64 algorithm. - * - MODE_RAW: $signature is not encoded. - * - * @param string $data - * @param string $signature - * @param null|Rsa\PublicKey $publicKey - * @param int $mode Input encoding - * @return bool - * @throws Rsa\Exception\RuntimeException - * @see Rsa::MODE_AUTO - * @see Rsa::MODE_BASE64 - * @see Rsa::MODE_RAW - */ - public function verify( - $data, - $signature, - Rsa\PublicKey $publicKey = null, - $mode = self::MODE_AUTO - ) { - if (null === $publicKey) { - $publicKey = $this->options->getPublicKey(); - } - - switch ($mode) { - case self::MODE_AUTO: - // check if data is encoded in Base64 - $output = base64_decode($signature, true); - if ((false !== $output) && ($signature === base64_encode($output))) { - $signature = $output; - } - break; - case self::MODE_BASE64: - $signature = base64_decode($signature); - break; - case self::MODE_RAW: - default: - break; - } - - $result = openssl_verify( - $data, - $signature, - $publicKey->getOpensslKeyResource(), - $this->options->getOpensslSignatureAlgorithm() - ); - if (-1 === $result) { - throw new Exception\RuntimeException( - 'Can not verify signature; openssl ' . $this->getOpensslErrorString() - ); - } - - return ($result === 1); - } - - /** - * Encrypt with private/public key - * - * @param string $data - * @param Rsa\AbstractKey $key - * @return string - * @throws Rsa\Exception\InvalidArgumentException - */ - public function encrypt($data, Rsa\AbstractKey $key = null) - { - if (null === $key) { - $key = $this->options->getPublicKey(); - } - - if (null === $key) { - throw new Exception\InvalidArgumentException('No key specified for the decryption'); - } - - $encrypted = $key->encrypt($data); - - if ($this->options->getBinaryOutput()) { - return $encrypted; - } - - return base64_encode($encrypted); - } - - /** - * Decrypt with private/public key - * - * $data can be encoded in base64 or not. $mode sets how the input must be processed: - * - MODE_AUTO: Check if the $signature is encoded in base64. Not recommended for performance. - * - MODE_BASE64: Decode $data using base64 algorithm. - * - MODE_RAW: $data is not encoded. - * - * @param string $data - * @param Rsa\AbstractKey $key - * @param int $mode Input encoding - * @return string - * @throws Rsa\Exception\InvalidArgumentException - * @see Rsa::MODE_AUTO - * @see Rsa::MODE_BASE64 - * @see Rsa::MODE_RAW - */ - public function decrypt( - $data, - Rsa\AbstractKey $key = null, - $mode = self::MODE_AUTO - ) { - if (null === $key) { - $key = $this->options->getPrivateKey(); - } - - if (null === $key) { - throw new Exception\InvalidArgumentException('No key specified for the decryption'); - } - - switch ($mode) { - case self::MODE_AUTO: - // check if data is encoded in Base64 - $output = base64_decode($data, true); - if ((false !== $output) && ($data === base64_encode($output))) { - $data = $output; - } - break; - case self::MODE_BASE64: - $data = base64_decode($data); - break; - case self::MODE_RAW: - default: - break; - } - - return $key->decrypt($data); - } - - /** - * Generate new private/public key pair - * @see RsaOptions::generateKeys() - * - * @param array $opensslConfig - * @return Rsa - * @throws Rsa\Exception\RuntimeException - */ - public function generateKeys(array $opensslConfig = array()) - { - $this->options->generateKeys($opensslConfig); - return $this; - } -} diff --git a/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php b/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php deleted file mode 100755 index 5051c7716..000000000 --- a/library/Zend/Crypt/PublicKey/Rsa/AbstractKey.php +++ /dev/null @@ -1,90 +0,0 @@ -details['bits']; - } - - /** - * Retrieve openssl key resource - * - * @return resource - */ - public function getOpensslKeyResource() - { - return $this->opensslKeyResource; - } - - /** - * Encrypt using this key - * - * @abstract - * @param string $data - * @return string - */ - abstract public function encrypt($data); - - /** - * Decrypt using this key - * - * @abstract - * @param string $data - * @return string - */ - abstract public function decrypt($data); - - /** - * Get string representation of this key - * - * @abstract - * @return string - */ - abstract public function toString(); - - /** - * @return string - */ - public function __toString() - { - return $this->toString(); - } -} diff --git a/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php b/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php deleted file mode 100755 index ccaad1b39..000000000 --- a/library/Zend/Crypt/PublicKey/Rsa/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -pemString = $pemString; - $this->opensslKeyResource = $result; - $this->details = openssl_pkey_get_details($this->opensslKeyResource); - } - - /** - * Get the public key - * - * @return PublicKey - */ - public function getPublicKey() - { - if ($this->publicKey === null) { - $this->publicKey = new PublicKey($this->details['key']); - } - - return $this->publicKey; - } - - /** - * Encrypt using this key - * - * @param string $data - * @return string - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - */ - public function encrypt($data) - { - if (empty($data)) { - throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty'); - } - - $encrypted = ''; - $result = openssl_private_encrypt($data, $encrypted, $this->getOpensslKeyResource()); - if (false === $result) { - throw new Exception\RuntimeException( - 'Can not encrypt; openssl ' . openssl_error_string() - ); - } - - return $encrypted; - } - - /** - * Decrypt using this key - * - * @param string $data - * @return string - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - */ - public function decrypt($data) - { - if (!is_string($data)) { - throw new Exception\InvalidArgumentException('The data to decrypt must be a string'); - } - if ('' === $data) { - throw new Exception\InvalidArgumentException('The data to decrypt cannot be empty'); - } - - $decrypted = ''; - $result = openssl_private_decrypt($data, $decrypted, $this->getOpensslKeyResource()); - if (false === $result) { - throw new Exception\RuntimeException( - 'Can not decrypt; openssl ' . openssl_error_string() - ); - } - - return $decrypted; - } - - /** - * @return string - */ - public function toString() - { - return $this->pemString; - } -} diff --git a/library/Zend/Crypt/PublicKey/Rsa/PublicKey.php b/library/Zend/Crypt/PublicKey/Rsa/PublicKey.php deleted file mode 100755 index d73078d28..000000000 --- a/library/Zend/Crypt/PublicKey/Rsa/PublicKey.php +++ /dev/null @@ -1,146 +0,0 @@ -certificateString = $pemStringOrCertificate; - } else { - $this->pemString = $pemStringOrCertificate; - } - - $this->opensslKeyResource = $result; - $this->details = openssl_pkey_get_details($this->opensslKeyResource); - } - - /** - * Encrypt using this key - * - * @param string $data - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - * @return string - */ - public function encrypt($data) - { - if (empty($data)) { - throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty'); - } - - $encrypted = ''; - $result = openssl_public_encrypt($data, $encrypted, $this->getOpensslKeyResource()); - if (false === $result) { - throw new Exception\RuntimeException( - 'Can not encrypt; openssl ' . openssl_error_string() - ); - } - - return $encrypted; - } - - /** - * Decrypt using this key - * - * @param string $data - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - * @return string - */ - public function decrypt($data) - { - if (!is_string($data)) { - throw new Exception\InvalidArgumentException('The data to decrypt must be a string'); - } - if ('' === $data) { - throw new Exception\InvalidArgumentException('The data to decrypt cannot be empty'); - } - - $decrypted = ''; - $result = openssl_public_decrypt($data, $decrypted, $this->getOpensslKeyResource()); - if (false === $result) { - throw new Exception\RuntimeException( - 'Can not decrypt; openssl ' . openssl_error_string() - ); - } - - return $decrypted; - } - - /** - * Get certificate string - * - * @return string - */ - public function getCertificate() - { - return $this->certificateString; - } - - /** - * To string - * - * @return string - * @throws Exception\RuntimeException - */ - public function toString() - { - if (!empty($this->certificateString)) { - return $this->certificateString; - } elseif (!empty($this->pemString)) { - return $this->pemString; - } - throw new Exception\RuntimeException('No public key string representation is available'); - } -} diff --git a/library/Zend/Crypt/PublicKey/RsaOptions.php b/library/Zend/Crypt/PublicKey/RsaOptions.php deleted file mode 100755 index 54cd7c55b..000000000 --- a/library/Zend/Crypt/PublicKey/RsaOptions.php +++ /dev/null @@ -1,224 +0,0 @@ -privateKey = $key; - $this->publicKey = $this->privateKey->getPublicKey(); - return $this; - } - - /** - * Get private key - * - * @return null|Rsa\PrivateKey - */ - public function getPrivateKey() - { - return $this->privateKey; - } - - /** - * Set public key - * - * @param Rsa\PublicKey $key - * @return RsaOptions - */ - public function setPublicKey(Rsa\PublicKey $key) - { - $this->publicKey = $key; - return $this; - } - - /** - * Get public key - * - * @return null|Rsa\PublicKey - */ - public function getPublicKey() - { - return $this->publicKey; - } - - /** - * Set pass phrase - * - * @param string $phrase - * @return RsaOptions - */ - public function setPassPhrase($phrase) - { - $this->passPhrase = (string) $phrase; - return $this; - } - - /** - * Get pass phrase - * - * @return string - */ - public function getPassPhrase() - { - return $this->passPhrase; - } - - /** - * Set hash algorithm - * - * @param string $hash - * @return RsaOptions - * @throws Rsa\Exception\RuntimeException - * @throws Rsa\Exception\InvalidArgumentException - */ - public function setHashAlgorithm($hash) - { - $hashUpper = strtoupper($hash); - if (!defined('OPENSSL_ALGO_' . $hashUpper)) { - throw new Exception\InvalidArgumentException( - "Hash algorithm '{$hash}' is not supported" - ); - } - - $this->hashAlgorithm = strtolower($hash); - $this->opensslSignatureAlgorithm = constant('OPENSSL_ALGO_' . $hashUpper); - return $this; - } - - /** - * Get hash algorithm - * - * @return string - */ - public function getHashAlgorithm() - { - return $this->hashAlgorithm; - } - - public function getOpensslSignatureAlgorithm() - { - if (!isset($this->opensslSignatureAlgorithm)) { - $this->opensslSignatureAlgorithm = constant('OPENSSL_ALGO_' . strtoupper($this->hashAlgorithm)); - } - return $this->opensslSignatureAlgorithm; - } - - /** - * Enable/disable the binary output - * - * @param bool $value - * @return RsaOptions - */ - public function setBinaryOutput($value) - { - $this->binaryOutput = (bool) $value; - return $this; - } - - /** - * Get the value of binary output - * - * @return bool - */ - public function getBinaryOutput() - { - return $this->binaryOutput; - } - - /** - * Generate new private/public key pair - * - * @param array $opensslConfig - * @return RsaOptions - * @throws Rsa\Exception\RuntimeException - */ - public function generateKeys(array $opensslConfig = array()) - { - $opensslConfig = array_replace( - array( - 'private_key_type' => OPENSSL_KEYTYPE_RSA, - 'private_key_bits' => Rsa\PrivateKey::DEFAULT_KEY_SIZE, - 'digest_alg' => $this->getHashAlgorithm() - ), - $opensslConfig - ); - - // generate - $resource = openssl_pkey_new($opensslConfig); - if (false === $resource) { - throw new Exception\RuntimeException( - 'Can not generate keys; openssl ' . openssl_error_string() - ); - } - - // export key - $passPhrase = $this->getPassPhrase(); - $result = openssl_pkey_export($resource, $private, $passPhrase, $opensslConfig); - if (false === $result) { - throw new Exception\RuntimeException( - 'Can not export key; openssl ' . openssl_error_string() - ); - } - - $details = openssl_pkey_get_details($resource); - $this->privateKey = new Rsa\PrivateKey($private, $passPhrase); - $this->publicKey = new Rsa\PublicKey($details['key']); - - return $this; - } -} diff --git a/library/Zend/Crypt/README.md b/library/Zend/Crypt/README.md deleted file mode 100755 index 1e2e5af91..000000000 --- a/library/Zend/Crypt/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Crypt Component from ZF2 -======================== - -This is the Crypt component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php b/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php deleted file mode 100755 index 7e62c51b2..000000000 --- a/library/Zend/Crypt/Symmetric/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - 'rijndael-128', - 'blowfish' => 'blowfish', - 'des' => 'des', - '3des' => 'tripledes', - 'tripledes' => 'tripledes', - 'cast-128' => 'cast-128', - 'cast-256' => 'cast-256', - 'rijndael-128' => 'rijndael-128', - 'rijndael-192' => 'rijndael-192', - 'rijndael-256' => 'rijndael-256', - 'saferplus' => 'saferplus', - 'serpent' => 'serpent', - 'twofish' => 'twofish' - ); - - /** - * Supported encryption modes - * - * @var array - */ - protected $supportedModes = array( - 'cbc' => 'cbc', - 'cfb' => 'cfb', - 'ctr' => 'ctr', - 'ofb' => 'ofb', - 'nofb' => 'nofb', - 'ncfb' => 'ncfb' - ); - - /** - * Constructor - * - * @param array|Traversable $options - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - */ - public function __construct($options = array()) - { - if (!extension_loaded('mcrypt')) { - throw new Exception\RuntimeException( - 'You cannot use ' . __CLASS__ . ' without the Mcrypt extension' - ); - } - if (!empty($options)) { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } elseif (!is_array($options)) { - throw new Exception\InvalidArgumentException( - 'The options parameter must be an array, a Zend\Config\Config object or a Traversable' - ); - } - foreach ($options as $key => $value) { - switch (strtolower($key)) { - case 'algo': - case 'algorithm': - $this->setAlgorithm($value); - break; - case 'mode': - $this->setMode($value); - break; - case 'key': - $this->setKey($value); - break; - case 'iv': - case 'salt': - $this->setSalt($value); - break; - case 'padding': - $plugins = static::getPaddingPluginManager(); - $padding = $plugins->get($value); - $this->padding = $padding; - break; - } - } - } - $this->setDefaultOptions($options); - } - - /** - * Set default options - * - * @param array $options - * @return void - */ - protected function setDefaultOptions($options = array()) - { - if (!isset($options['padding'])) { - $plugins = static::getPaddingPluginManager(); - $padding = $plugins->get(self::DEFAULT_PADDING); - $this->padding = $padding; - } - } - - /** - * Returns the padding plugin manager. If it doesn't exist it's created. - * - * @return PaddingPluginManager - */ - public static function getPaddingPluginManager() - { - if (static::$paddingPlugins === null) { - self::setPaddingPluginManager(new PaddingPluginManager()); - } - - return static::$paddingPlugins; - } - - /** - * Set the padding plugin manager - * - * @param string|PaddingPluginManager $plugins - * @throws Exception\InvalidArgumentException - * @return void - */ - public static function setPaddingPluginManager($plugins) - { - if (is_string($plugins)) { - if (!class_exists($plugins)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Unable to locate padding plugin manager via class "%s"; class does not exist', - $plugins - )); - } - $plugins = new $plugins(); - } - if (!$plugins instanceof PaddingPluginManager) { - throw new Exception\InvalidArgumentException(sprintf( - 'Padding plugins must extend %s\PaddingPluginManager; received "%s"', - __NAMESPACE__, - (is_object($plugins) ? get_class($plugins) : gettype($plugins)) - )); - } - static::$paddingPlugins = $plugins; - } - - /** - * Get the maximum key size for the selected cipher and mode of operation - * - * @return int - */ - public function getKeySize() - { - return mcrypt_get_key_size($this->supportedAlgos[$this->algo], $this->supportedModes[$this->mode]); - } - - /** - * Set the encryption key - * If the key is longer than maximum supported, it will be truncated by getKey(). - * - * @param string $key - * @throws Exception\InvalidArgumentException - * @return Mcrypt - */ - public function setKey($key) - { - $keyLen = strlen($key); - - if (!$keyLen) { - throw new Exception\InvalidArgumentException('The key cannot be empty'); - } - $keySizes = mcrypt_module_get_supported_key_sizes($this->supportedAlgos[$this->algo]); - $maxKey = $this->getKeySize(); - - /* - * blowfish has $keySizes empty, meaning it can have arbitrary key length. - * the others are more picky. - */ - if (!empty($keySizes) && $keyLen < $maxKey) { - if (!in_array($keyLen, $keySizes)) { - throw new Exception\InvalidArgumentException( - "The size of the key must be one of " . implode(", ", $keySizes) . " bytes or longer" - ); - } - } - $this->key = $key; - - return $this; - } - - /** - * Get the encryption key - * - * @return string - */ - public function getKey() - { - if (empty($this->key)) { - return null; - } - return substr($this->key, 0, $this->getKeySize()); - } - - /** - * Set the encryption algorithm (cipher) - * - * @param string $algo - * @throws Exception\InvalidArgumentException - * @return Mcrypt - */ - public function setAlgorithm($algo) - { - if (!array_key_exists($algo, $this->supportedAlgos)) { - throw new Exception\InvalidArgumentException( - "The algorithm $algo is not supported by " . __CLASS__ - ); - } - $this->algo = $algo; - - return $this; - } - - /** - * Get the encryption algorithm - * - * @return string - */ - public function getAlgorithm() - { - return $this->algo; - } - - /** - * Set the padding object - * - * @param Padding\PaddingInterface $padding - * @return Mcrypt - */ - public function setPadding(Padding\PaddingInterface $padding) - { - $this->padding = $padding; - - return $this; - } - - /** - * Get the padding object - * - * @return Padding\PaddingInterface - */ - public function getPadding() - { - return $this->padding; - } - - /** - * Encrypt - * - * @param string $data - * @throws Exception\InvalidArgumentException - * @return string - */ - public function encrypt($data) - { - // Cannot encrypt empty string - if (!is_string($data) || $data === '') { - throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty'); - } - if (null === $this->getKey()) { - throw new Exception\InvalidArgumentException('No key specified for the encryption'); - } - if (null === $this->getSalt()) { - throw new Exception\InvalidArgumentException('The salt (IV) cannot be empty'); - } - if (null === $this->getPadding()) { - throw new Exception\InvalidArgumentException('You have to specify a padding method'); - } - // padding - $data = $this->padding->pad($data, $this->getBlockSize()); - $iv = $this->getSalt(); - // encryption - $result = mcrypt_encrypt( - $this->supportedAlgos[$this->algo], - $this->getKey(), - $data, - $this->supportedModes[$this->mode], - $iv - ); - - return $iv . $result; - } - - /** - * Decrypt - * - * @param string $data - * @throws Exception\InvalidArgumentException - * @return string - */ - public function decrypt($data) - { - if (empty($data)) { - throw new Exception\InvalidArgumentException('The data to decrypt cannot be empty'); - } - if (null === $this->getKey()) { - throw new Exception\InvalidArgumentException('No key specified for the decryption'); - } - if (null === $this->getPadding()) { - throw new Exception\InvalidArgumentException('You have to specify a padding method'); - } - $iv = substr($data, 0, $this->getSaltSize()); - $ciphertext = substr($data, $this->getSaltSize()); - $result = mcrypt_decrypt( - $this->supportedAlgos[$this->algo], - $this->getKey(), - $ciphertext, - $this->supportedModes[$this->mode], - $iv - ); - // unpadding - return $this->padding->strip($result); - } - - /** - * Get the salt (IV) size - * - * @return int - */ - public function getSaltSize() - { - return mcrypt_get_iv_size($this->supportedAlgos[$this->algo], $this->supportedModes[$this->mode]); - } - - /** - * Get the supported algorithms - * - * @return array - */ - public function getSupportedAlgorithms() - { - return array_keys($this->supportedAlgos); - } - - /** - * Set the salt (IV) - * - * @param string $salt - * @throws Exception\InvalidArgumentException - * @return Mcrypt - */ - public function setSalt($salt) - { - if (empty($salt)) { - throw new Exception\InvalidArgumentException('The salt (IV) cannot be empty'); - } - if (strlen($salt) < $this->getSaltSize()) { - throw new Exception\InvalidArgumentException( - 'The size of the salt (IV) must be at least ' . $this->getSaltSize() . ' bytes' - ); - } - $this->iv = $salt; - - return $this; - } - - /** - * Get the salt (IV) according to the size requested by the algorithm - * - * @return string - */ - public function getSalt() - { - if (empty($this->iv)) { - return null; - } - if (strlen($this->iv) < $this->getSaltSize()) { - throw new Exception\RuntimeException( - 'The size of the salt (IV) must be at least ' . $this->getSaltSize() . ' bytes' - ); - } - - return substr($this->iv, 0, $this->getSaltSize()); - } - - /** - * Get the original salt value - * - * @return string - */ - public function getOriginalSalt() - { - return $this->iv; - } - - /** - * Set the cipher mode - * - * @param string $mode - * @throws Exception\InvalidArgumentException - * @return Mcrypt - */ - public function setMode($mode) - { - if (!empty($mode)) { - $mode = strtolower($mode); - if (!array_key_exists($mode, $this->supportedModes)) { - throw new Exception\InvalidArgumentException( - "The mode $mode is not supported by " . __CLASS__ - ); - } - $this->mode = $mode; - } - - return $this; - } - - /** - * Get the cipher mode - * - * @return string - */ - public function getMode() - { - return $this->mode; - } - - /** - * Get all supported encryption modes - * - * @return array - */ - public function getSupportedModes() - { - return array_keys($this->supportedModes); - } - - /** - * Get the block size - * - * @return int - */ - public function getBlockSize() - { - return mcrypt_get_block_size($this->supportedAlgos[$this->algo], $this->supportedModes[$this->mode]); - } -} diff --git a/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php b/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php deleted file mode 100755 index 24050c311..000000000 --- a/library/Zend/Crypt/Symmetric/Padding/PaddingInterface.php +++ /dev/null @@ -1,30 +0,0 @@ - 'Zend\Crypt\Symmetric\Padding\Pkcs7' - ); - - /** - * Do not share by default - * - * @var bool - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the padding adapter loaded is an instance of Padding\PaddingInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Padding\PaddingInterface) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Padding\PaddingInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Crypt/Symmetric/SymmetricInterface.php b/library/Zend/Crypt/Symmetric/SymmetricInterface.php deleted file mode 100755 index acf160e96..000000000 --- a/library/Zend/Crypt/Symmetric/SymmetricInterface.php +++ /dev/null @@ -1,61 +0,0 @@ - 'Zend\Crypt\Symmetric\Mcrypt', - ); - - /** - * Do not share by default - * - * @var bool - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the adapter loaded is an instance - * of Symmetric\SymmetricInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Symmetric\SymmetricInterface) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Symmetric\SymmetricInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Crypt/Utils.php b/library/Zend/Crypt/Utils.php deleted file mode 100755 index ff013dcbc..000000000 --- a/library/Zend/Crypt/Utils.php +++ /dev/null @@ -1,45 +0,0 @@ -=5.3.23", - "zendframework/zend-math": "self.version", - "zendframework/zend-stdlib": "self.version", - "zendframework/zend-servicemanager": "self.version" - }, - "suggest": { - "ext-mcrypt": "Required for most features of Zend\\Crypt" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Db/Adapter/Adapter.php b/library/Zend/Db/Adapter/Adapter.php deleted file mode 100755 index b4c7edfff..000000000 --- a/library/Zend/Db/Adapter/Adapter.php +++ /dev/null @@ -1,387 +0,0 @@ -createProfiler($parameters); - } - $driver = $this->createDriver($parameters); - } elseif (!$driver instanceof Driver\DriverInterface) { - throw new Exception\InvalidArgumentException( - 'The supplied or instantiated driver object does not implement Zend\Db\Adapter\Driver\DriverInterface' - ); - } - - $driver->checkEnvironment(); - $this->driver = $driver; - - if ($platform == null) { - $platform = $this->createPlatform($parameters); - } - - $this->platform = $platform; - $this->queryResultSetPrototype = ($queryResultPrototype) ?: new ResultSet\ResultSet(); - - if ($profiler) { - $this->setProfiler($profiler); - } - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Adapter - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->driver instanceof Profiler\ProfilerAwareInterface) { - $this->driver->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * getDriver() - * - * @throws Exception\RuntimeException - * @return Driver\DriverInterface - */ - public function getDriver() - { - if ($this->driver == null) { - throw new Exception\RuntimeException('Driver has not been set or configured for this adapter.'); - } - return $this->driver; - } - - /** - * @return Platform\PlatformInterface - */ - public function getPlatform() - { - return $this->platform; - } - - /** - * @return ResultSet\ResultSetInterface - */ - public function getQueryResultSetPrototype() - { - return $this->queryResultSetPrototype; - } - - public function getCurrentSchema() - { - return $this->driver->getConnection()->getCurrentSchema(); - } - - /** - * query() is a convenience function - * - * @param string $sql - * @param string|array|ParameterContainer $parametersOrQueryMode - * @throws Exception\InvalidArgumentException - * @return Driver\StatementInterface|ResultSet\ResultSet - */ - public function query($sql, $parametersOrQueryMode = self::QUERY_MODE_PREPARE, ResultSet\ResultSetInterface $resultPrototype = null) - { - if (is_string($parametersOrQueryMode) && in_array($parametersOrQueryMode, array(self::QUERY_MODE_PREPARE, self::QUERY_MODE_EXECUTE))) { - $mode = $parametersOrQueryMode; - $parameters = null; - } elseif (is_array($parametersOrQueryMode) || $parametersOrQueryMode instanceof ParameterContainer) { - $mode = self::QUERY_MODE_PREPARE; - $parameters = $parametersOrQueryMode; - } else { - throw new Exception\InvalidArgumentException('Parameter 2 to this method must be a flag, an array, or ParameterContainer'); - } - - if ($mode == self::QUERY_MODE_PREPARE) { - $this->lastPreparedStatement = null; - $this->lastPreparedStatement = $this->driver->createStatement($sql); - $this->lastPreparedStatement->prepare(); - if (is_array($parameters) || $parameters instanceof ParameterContainer) { - $this->lastPreparedStatement->setParameterContainer((is_array($parameters)) ? new ParameterContainer($parameters) : $parameters); - $result = $this->lastPreparedStatement->execute(); - } else { - return $this->lastPreparedStatement; - } - } else { - $result = $this->driver->getConnection()->execute($sql); - } - - if ($result instanceof Driver\ResultInterface && $result->isQueryResult()) { - $resultSet = clone ($resultPrototype ?: $this->queryResultSetPrototype); - $resultSet->initialize($result); - return $resultSet; - } - - return $result; - } - - /** - * Create statement - * - * @param string $initialSql - * @param ParameterContainer $initialParameters - * @return Driver\StatementInterface - */ - public function createStatement($initialSql = null, $initialParameters = null) - { - $statement = $this->driver->createStatement($initialSql); - if ($initialParameters == null || !$initialParameters instanceof ParameterContainer && is_array($initialParameters)) { - $initialParameters = new ParameterContainer((is_array($initialParameters) ? $initialParameters : array())); - } - $statement->setParameterContainer($initialParameters); - return $statement; - } - - public function getHelpers(/* $functions */) - { - $functions = array(); - $platform = $this->platform; - foreach (func_get_args() as $arg) { - switch ($arg) { - case self::FUNCTION_QUOTE_IDENTIFIER: - $functions[] = function ($value) use ($platform) { return $platform->quoteIdentifier($value); }; - break; - case self::FUNCTION_QUOTE_VALUE: - $functions[] = function ($value) use ($platform) { return $platform->quoteValue($value); }; - break; - - } - } - } - - /** - * @param $name - * @throws Exception\InvalidArgumentException - * @return Driver\DriverInterface|Platform\PlatformInterface - */ - public function __get($name) - { - switch (strtolower($name)) { - case 'driver': - return $this->driver; - case 'platform': - return $this->platform; - default: - throw new Exception\InvalidArgumentException('Invalid magic property on adapter'); - } - } - - /** - * @param array $parameters - * @return Driver\DriverInterface - * @throws \InvalidArgumentException - * @throws Exception\InvalidArgumentException - */ - protected function createDriver($parameters) - { - if (!isset($parameters['driver'])) { - throw new Exception\InvalidArgumentException(__FUNCTION__ . ' expects a "driver" key to be present inside the parameters'); - } - - if ($parameters['driver'] instanceof Driver\DriverInterface) { - return $parameters['driver']; - } - - if (!is_string($parameters['driver'])) { - throw new Exception\InvalidArgumentException(__FUNCTION__ . ' expects a "driver" to be a string or instance of DriverInterface'); - } - - $options = array(); - if (isset($parameters['options'])) { - $options = (array) $parameters['options']; - unset($parameters['options']); - } - - $driverName = strtolower($parameters['driver']); - switch ($driverName) { - case 'mysqli': - $driver = new Driver\Mysqli\Mysqli($parameters, null, null, $options); - break; - case 'sqlsrv': - $driver = new Driver\Sqlsrv\Sqlsrv($parameters); - break; - case 'oci8': - $driver = new Driver\Oci8\Oci8($parameters); - break; - case 'pgsql': - $driver = new Driver\Pgsql\Pgsql($parameters); - break; - case 'ibmdb2': - $driver = new Driver\IbmDb2\IbmDb2($parameters); - break; - case 'pdo': - default: - if ($driverName == 'pdo' || strpos($driverName, 'pdo') === 0) { - $driver = new Driver\Pdo\Pdo($parameters); - } - } - - if (!isset($driver) || !$driver instanceof Driver\DriverInterface) { - throw new Exception\InvalidArgumentException('DriverInterface expected', null, null); - } - - return $driver; - } - - /** - * @param Driver\DriverInterface $driver - * @return Platform\PlatformInterface - */ - protected function createPlatform($parameters) - { - if (isset($parameters['platform'])) { - $platformName = $parameters['platform']; - } elseif ($this->driver instanceof Driver\DriverInterface) { - $platformName = $this->driver->getDatabasePlatformName(Driver\DriverInterface::NAME_FORMAT_CAMELCASE); - } else { - throw new Exception\InvalidArgumentException('A platform could not be determined from the provided configuration'); - } - - // currently only supported by the IbmDb2 & Oracle concrete implementations - $options = (isset($parameters['platform_options'])) ? $parameters['platform_options'] : array(); - - switch ($platformName) { - case 'Mysql': - // mysqli or pdo_mysql driver - $driver = ($this->driver instanceof Driver\Mysqli\Mysqli || $this->driver instanceof Driver\Pdo\Pdo) ? $this->driver : null; - return new Platform\Mysql($driver); - case 'SqlServer': - // PDO is only supported driver for quoting values in this platform - return new Platform\SqlServer(($this->driver instanceof Driver\Pdo\Pdo) ? $this->driver : null); - case 'Oracle': - // oracle does not accept a driver as an option, no driver specific quoting available - return new Platform\Oracle($options); - case 'Sqlite': - // PDO is only supported driver for quoting values in this platform - return new Platform\Sqlite(($this->driver instanceof Driver\Pdo\Pdo) ? $this->driver : null); - case 'Postgresql': - // pgsql or pdo postgres driver - $driver = ($this->driver instanceof Driver\Pgsql\Pgsql || $this->driver instanceof Driver\Pdo\Pdo) ? $this->driver : null; - return new Platform\Postgresql($driver); - case 'IbmDb2': - // ibm_db2 driver escaping does not need an action connection - return new Platform\IbmDb2($options); - default: - return new Platform\Sql92(); - } - } - - protected function createProfiler($parameters) - { - if ($parameters['profiler'] instanceof Profiler\ProfilerInterface) { - $profiler = $parameters['profiler']; - } elseif (is_bool($parameters['profiler'])) { - $profiler = ($parameters['profiler'] == true) ? new Profiler\Profiler : null; - } else { - throw new Exception\InvalidArgumentException( - '"profiler" parameter must be an instance of ProfilerInterface or a boolean' - ); - } - return $profiler; - } - - /** - * @param array $parameters - * @return Driver\DriverInterface - * @throws \InvalidArgumentException - * @throws Exception\InvalidArgumentException - * @deprecated - */ - protected function createDriverFromParameters(array $parameters) - { - return $this->createDriver($parameters); - } - - /** - * @param Driver\DriverInterface $driver - * @return Platform\PlatformInterface - * @deprecated - */ - protected function createPlatformFromDriver(Driver\DriverInterface $driver) - { - return $this->createPlatform($driver); - } -} diff --git a/library/Zend/Db/Adapter/AdapterAbstractServiceFactory.php b/library/Zend/Db/Adapter/AdapterAbstractServiceFactory.php deleted file mode 100755 index 42800a2ce..000000000 --- a/library/Zend/Db/Adapter/AdapterAbstractServiceFactory.php +++ /dev/null @@ -1,99 +0,0 @@ -getConfig($services); - if (empty($config)) { - return false; - } - - return ( - isset($config[$requestedName]) - && is_array($config[$requestedName]) - && !empty($config[$requestedName]) - ); - } - - /** - * Create a DB adapter - * - * @param ServiceLocatorInterface $services - * @param string $name - * @param string $requestedName - * @return Adapter - */ - public function createServiceWithName(ServiceLocatorInterface $services, $name, $requestedName) - { - $config = $this->getConfig($services); - return new Adapter($config[$requestedName]); - } - - /** - * Get db configuration, if any - * - * @param ServiceLocatorInterface $services - * @return array - */ - protected function getConfig(ServiceLocatorInterface $services) - { - if ($this->config !== null) { - return $this->config; - } - - if (!$services->has('Config')) { - $this->config = array(); - return $this->config; - } - - $config = $services->get('Config'); - if (!isset($config['db']) - || !is_array($config['db']) - ) { - $this->config = array(); - return $this->config; - } - - $config = $config['db']; - if (!isset($config['adapters']) - || !is_array($config['adapters']) - ) { - $this->config = array(); - return $this->config; - } - - $this->config = $config['adapters']; - return $this->config; - } -} diff --git a/library/Zend/Db/Adapter/AdapterAwareInterface.php b/library/Zend/Db/Adapter/AdapterAwareInterface.php deleted file mode 100755 index 95443a9a0..000000000 --- a/library/Zend/Db/Adapter/AdapterAwareInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -adapter = $adapter; - - return $this; - } -} diff --git a/library/Zend/Db/Adapter/AdapterInterface.php b/library/Zend/Db/Adapter/AdapterInterface.php deleted file mode 100755 index 57a6a7376..000000000 --- a/library/Zend/Db/Adapter/AdapterInterface.php +++ /dev/null @@ -1,28 +0,0 @@ -get('Config'); - return new Adapter($config['db']); - } -} diff --git a/library/Zend/Db/Adapter/Driver/ConnectionInterface.php b/library/Zend/Db/Adapter/Driver/ConnectionInterface.php deleted file mode 100755 index 2e27fd688..000000000 --- a/library/Zend/Db/Adapter/Driver/ConnectionInterface.php +++ /dev/null @@ -1,85 +0,0 @@ -driver = $driver; - } - - /** - * Get name - * - * @return string - */ - abstract public function getName(); -} diff --git a/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php b/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php deleted file mode 100755 index 10c96f773..000000000 --- a/library/Zend/Db/Adapter/Driver/Feature/DriverFeatureInterface.php +++ /dev/null @@ -1,37 +0,0 @@ -setConnectionParameters($connectionParameters); - } elseif (is_resource($connectionParameters)) { - $this->setResource($connectionParameters); - } elseif (null !== $connectionParameters) { - throw new Exception\InvalidArgumentException( - '$connection must be an array of parameters, a db2 connection resource or null' - ); - } - } - - /** - * Set driver - * - * @param IbmDb2 $driver - * @return Connection - */ - public function setDriver(IbmDb2 $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Connection - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * @param array $connectionParameters - * @return Connection - */ - public function setConnectionParameters(array $connectionParameters) - { - $this->connectionParameters = $connectionParameters; - return $this; - } - - /** - * @return array - */ - public function getConnectionParameters() - { - return $this->connectionParameters; - } - - /** - * @param resource $resource DB2 resource - * @return Connection - */ - public function setResource($resource) - { - if (!is_resource($resource) || get_resource_type($resource) !== 'DB2 Connection') { - throw new Exception\InvalidArgumentException('The resource provided must be of type "DB2 Connection"'); - } - $this->resource = $resource; - return $this; - } - - /** - * Get current schema - * - * @return string - */ - public function getCurrentSchema() - { - if (!$this->isConnected()) { - $this->connect(); - } - - $info = db2_server_info($this->resource); - return (isset($info->DB_NAME) ? $info->DB_NAME : ''); - } - - /** - * Get resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Connect - * - * @return self - */ - public function connect() - { - if (is_resource($this->resource)) { - return $this; - } - - // localize - $p = $this->connectionParameters; - - // given a list of key names, test for existence in $p - $findParameterValue = function (array $names) use ($p) { - foreach ($names as $name) { - if (isset($p[$name])) { - return $p[$name]; - } - } - - return null; - }; - - $database = $findParameterValue(array('database', 'db')); - $username = $findParameterValue(array('username', 'uid', 'UID')); - $password = $findParameterValue(array('password', 'pwd', 'PWD')); - $isPersistent = $findParameterValue(array('persistent', 'PERSISTENT', 'Persistent')); - $options = (isset($p['driver_options']) ? $p['driver_options'] : array()); - $connect = ((bool) $isPersistent) ? 'db2_pconnect' : 'db2_connect'; - - $this->resource = $connect($database, $username, $password, $options); - - if ($this->resource === false) { - throw new Exception\RuntimeException(sprintf( - '%s: Unable to connect to database', - __METHOD__ - )); - } - - return $this; - } - - /** - * Is connected - * - * @return bool - */ - public function isConnected() - { - return ($this->resource !== null); - } - - /** - * Disconnect - * - * @return ConnectionInterface - */ - public function disconnect() - { - if ($this->resource) { - db2_close($this->resource); - $this->resource = null; - } - - return $this; - } - - /** - * Begin transaction - * - * @return ConnectionInterface - */ - public function beginTransaction() - { - if ($this->isI5() && !ini_get('ibm_db2.i5_allow_commit')) { - throw new Exception\RuntimeException( - 'DB2 transactions are not enabled, you need to set the ibm_db2.i5_allow_commit=1 in your php.ini' - ); - } - - if (!$this->isConnected()) { - $this->connect(); - } - - $this->prevAutocommit = db2_autocommit($this->resource); - db2_autocommit($this->resource, DB2_AUTOCOMMIT_OFF); - $this->inTransaction = true; - return $this; - } - - /** - * In transaction - * - * @return bool - */ - public function inTransaction() - { - return $this->inTransaction; - } - - /** - * Commit - * - * @return ConnectionInterface - */ - public function commit() - { - if (!$this->isConnected()) { - $this->connect(); - } - - if (!db2_commit($this->resource)) { - throw new Exception\RuntimeException("The commit has not been successful"); - } - - if ($this->prevAutocommit) { - db2_autocommit($this->resource, $this->prevAutocommit); - } - - $this->inTransaction = false; - return $this; - } - - /** - * Rollback - * - * @return ConnectionInterface - */ - public function rollback() - { - if (!$this->resource) { - throw new Exception\RuntimeException('Must be connected before you can rollback.'); - } - - if (!$this->inTransaction) { - throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback.'); - } - - if (!db2_rollback($this->resource)) { - throw new Exception\RuntimeException('The rollback has not been successful'); - } - - if ($this->prevAutocommit) { - db2_autocommit($this->resource, $this->prevAutocommit); - } - - $this->inTransaction = false; - return $this; - } - - /** - * Execute - * - * @param string $sql - * @return Result - */ - public function execute($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - if ($this->profiler) { - $this->profiler->profilerStart($sql); - } - - set_error_handler(function () {}, E_WARNING); // suppress warnings - $resultResource = db2_exec($this->resource, $sql); - restore_error_handler(); - - if ($this->profiler) { - $this->profiler->profilerFinish($sql); - } - - // if the returnValue is something other than a pg result resource, bypass wrapping it - if ($resultResource === false) { - throw new Exception\InvalidQueryException(db2_stmt_errormsg()); - } - - return $this->driver->createResult(($resultResource === true) ? $this->resource : $resultResource); - } - - /** - * Get last generated id - * - * @param null $name Ignored - * @return int - */ - public function getLastGeneratedValue($name = null) - { - return db2_last_insert_id($this->resource); - } - - /** - * Determine if the OS is OS400 (AS400, IBM i) - * - * @return bool - */ - protected function isI5() - { - if (isset($this->i5)) { - return $this->i5; - } - - $this->i5 = php_uname('s') == 'OS400' ? true : false; - return $this->i5; - } -} diff --git a/library/Zend/Db/Adapter/Driver/IbmDb2/IbmDb2.php b/library/Zend/Db/Adapter/Driver/IbmDb2/IbmDb2.php deleted file mode 100755 index d129b49b3..000000000 --- a/library/Zend/Db/Adapter/Driver/IbmDb2/IbmDb2.php +++ /dev/null @@ -1,214 +0,0 @@ -registerConnection($connection); - $this->registerStatementPrototype(($statementPrototype) ?: new Statement()); - $this->registerResultPrototype(($resultPrototype) ?: new Result()); - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return IbmDb2 - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->connection instanceof Profiler\ProfilerAwareInterface) { - $this->connection->setProfiler($profiler); - } - if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) { - $this->statementPrototype->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * @param Connection $connection - * @return IbmDb2 - */ - public function registerConnection(Connection $connection) - { - $this->connection = $connection; - $this->connection->setDriver($this); - return $this; - } - - /** - * @param Statement $statementPrototype - * @return IbmDb2 - */ - public function registerStatementPrototype(Statement $statementPrototype) - { - $this->statementPrototype = $statementPrototype; - $this->statementPrototype->setDriver($this); - return $this; - } - - /** - * @param Result $resultPrototype - * @return IbmDb2 - */ - public function registerResultPrototype(Result $resultPrototype) - { - $this->resultPrototype = $resultPrototype; - return $this; - } - - /** - * Get database platform name - * - * @param string $nameFormat - * @return string - */ - public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE) - { - if ($nameFormat == self::NAME_FORMAT_CAMELCASE) { - return 'IbmDb2'; - } else { - return 'IBM DB2'; - } - } - - /** - * Check environment - * - * @return bool - */ - public function checkEnvironment() - { - if (!extension_loaded('ibm_db2')) { - throw new Exception\RuntimeException('The ibm_db2 extension is required by this driver.'); - } - } - - /** - * Get connection - * - * @return Connection - */ - public function getConnection() - { - return $this->connection; - } - - /** - * Create statement - * - * @param string|resource $sqlOrResource - * @return Statement - */ - public function createStatement($sqlOrResource = null) - { - $statement = clone $this->statementPrototype; - if (is_resource($sqlOrResource) && get_resource_type($sqlOrResource) == 'DB2 Statement') { - $statement->setResource($sqlOrResource); - } else { - if (is_string($sqlOrResource)) { - $statement->setSql($sqlOrResource); - } elseif ($sqlOrResource !== null) { - throw new Exception\InvalidArgumentException( - __FUNCTION__ . ' only accepts an SQL string or an ibm_db2 resource' - ); - } - if (!$this->connection->isConnected()) { - $this->connection->connect(); - } - $statement->initialize($this->connection->getResource()); - } - return $statement; - } - - /** - * Create result - * - * @param resource $resource - * @return Result - */ - public function createResult($resource) - { - $result = clone $this->resultPrototype; - $result->initialize($resource, $this->connection->getLastGeneratedValue()); - return $result; - } - - /** - * Get prepare type - * - * @return array - */ - public function getPrepareType() - { - return self::PARAMETERIZATION_POSITIONAL; - } - - /** - * Format parameter name - * - * @param string $name - * @param mixed $type - * @return string - */ - public function formatParameterName($name, $type = null) - { - return '?'; - } - - /** - * Get last generated value - * - * @return mixed - */ - public function getLastGeneratedValue() - { - return $this->connection->getLastGeneratedValue(); - } -} diff --git a/library/Zend/Db/Adapter/Driver/IbmDb2/Result.php b/library/Zend/Db/Adapter/Driver/IbmDb2/Result.php deleted file mode 100755 index add4e1e3f..000000000 --- a/library/Zend/Db/Adapter/Driver/IbmDb2/Result.php +++ /dev/null @@ -1,192 +0,0 @@ -resource = $resource; - $this->generatedValue = $generatedValue; - return $this; - } - - /** - * (PHP 5 >= 5.0.0)
        - * Return the current element - * @link http://php.net/manual/en/iterator.current.php - * @return mixed Can return any type. - */ - public function current() - { - if ($this->currentComplete) { - return $this->currentData; - } - - $this->currentData = db2_fetch_assoc($this->resource); - return $this->currentData; - } - - /** - * @return mixed - */ - public function next() - { - $this->currentData = db2_fetch_assoc($this->resource); - $this->currentComplete = true; - $this->position++; - return $this->currentData; - } - - /** - * @return int|string - */ - public function key() - { - return $this->position; - } - - /** - * @return bool - */ - public function valid() - { - return ($this->currentData !== false); - } - - /** - * (PHP 5 >= 5.0.0)
        - * Rewind the Iterator to the first element - * @link http://php.net/manual/en/iterator.rewind.php - * @return void Any returned value is ignored. - */ - public function rewind() - { - if ($this->position > 0) { - throw new Exception\RuntimeException( - 'This result is a forward only result set, calling rewind() after moving forward is not supported' - ); - } - $this->currentData = db2_fetch_assoc($this->resource); - $this->currentComplete = true; - $this->position = 1; - } - - /** - * Force buffering - * - * @return void - */ - public function buffer() - { - return null; - } - - /** - * Check if is buffered - * - * @return bool|null - */ - public function isBuffered() - { - return false; - } - - /** - * Is query result? - * - * @return bool - */ - public function isQueryResult() - { - return (db2_num_fields($this->resource) > 0); - } - - /** - * Get affected rows - * - * @return int - */ - public function getAffectedRows() - { - return db2_num_rows($this->resource); - } - - /** - * Get generated value - * - * @return mixed|null - */ - public function getGeneratedValue() - { - return $this->generatedValue; - } - - /** - * Get the resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Get field count - * - * @return int - */ - public function getFieldCount() - { - return db2_num_fields($this->resource); - } - - /** - * @return null|int - */ - public function count() - { - return null; - } -} diff --git a/library/Zend/Db/Adapter/Driver/IbmDb2/Statement.php b/library/Zend/Db/Adapter/Driver/IbmDb2/Statement.php deleted file mode 100755 index 029a9ed27..000000000 --- a/library/Zend/Db/Adapter/Driver/IbmDb2/Statement.php +++ /dev/null @@ -1,240 +0,0 @@ -db2 = $resource; - return $this; - } - - /** - * @param IbmDb2 $driver - * @return Statement - */ - public function setDriver(IbmDb2 $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Statement - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Set sql - * - * @param $sql - * @return mixed - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * Get sql - * - * @return mixed - */ - public function getSql() - { - return $this->sql; - } - - /** - * Set parameter container - * - * @param ParameterContainer $parameterContainer - * @return mixed - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * Get parameter container - * - * @return mixed - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } - - /** - * @param $resource - * @throws \Zend\Db\Adapter\Exception\InvalidArgumentException - */ - public function setResource($resource) - { - if (get_resource_type($resource) !== 'DB2 Statement') { - throw new Exception\InvalidArgumentException('Resource must be of type DB2 Statement'); - } - $this->resource = $resource; - } - - /** - * Get resource - * - * @return resource - */ - public function getResource() - { - return $this->resource; - } - - /** - * Prepare sql - * - * @param string|null $sql - * @return Statement - */ - public function prepare($sql = null) - { - if ($this->isPrepared) { - throw new Exception\RuntimeException('This statement has been prepared already'); - } - - if ($sql == null) { - $sql = $this->sql; - } - - $this->resource = db2_prepare($this->db2, $sql); - - if ($this->resource === false) { - throw new Exception\RuntimeException(db2_stmt_errormsg(), db2_stmt_error()); - } - - $this->isPrepared = true; - return $this; - } - - /** - * Check if is prepared - * - * @return bool - */ - public function isPrepared() - { - return $this->isPrepared; - } - - /** - * Execute - * - * @param null $parameters - * @return Result - */ - public function execute($parameters = null) - { - if (!$this->isPrepared) { - $this->prepare(); - } - - /** START Standard ParameterContainer Merging Block */ - if (!$this->parameterContainer instanceof ParameterContainer) { - if ($parameters instanceof ParameterContainer) { - $this->parameterContainer = $parameters; - $parameters = null; - } else { - $this->parameterContainer = new ParameterContainer(); - } - } - - if (is_array($parameters)) { - $this->parameterContainer->setFromArray($parameters); - } - /** END Standard ParameterContainer Merging Block */ - - if ($this->profiler) { - $this->profiler->profilerStart($this); - } - - set_error_handler(function () {}, E_WARNING); // suppress warnings - $response = db2_execute($this->resource, $this->parameterContainer->getPositionalArray()); - restore_error_handler(); - - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - - if ($response === false) { - throw new Exception\RuntimeException(db2_stmt_errormsg($this->resource)); - } - - $result = $this->driver->createResult($this->resource); - return $result; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php b/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php deleted file mode 100755 index d84db10fe..000000000 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Connection.php +++ /dev/null @@ -1,346 +0,0 @@ -setConnectionParameters($connectionInfo); - } elseif ($connectionInfo instanceof \mysqli) { - $this->setResource($connectionInfo); - } elseif (null !== $connectionInfo) { - throw new Exception\InvalidArgumentException('$connection must be an array of parameters, a mysqli object or null'); - } - } - - /** - * @param Mysqli $driver - * @return Connection - */ - public function setDriver(Mysqli $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Connection - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Set connection parameters - * - * @param array $connectionParameters - * @return Connection - */ - public function setConnectionParameters(array $connectionParameters) - { - $this->connectionParameters = $connectionParameters; - return $this; - } - - /** - * Get connection parameters - * - * @return array - */ - public function getConnectionParameters() - { - return $this->connectionParameters; - } - - /** - * Get current schema - * - * @return string - */ - public function getCurrentSchema() - { - if (!$this->isConnected()) { - $this->connect(); - } - - /** @var $result \mysqli_result */ - $result = $this->resource->query('SELECT DATABASE()'); - $r = $result->fetch_row(); - return $r[0]; - } - - /** - * Set resource - * - * @param \mysqli $resource - * @return Connection - */ - public function setResource(\mysqli $resource) - { - $this->resource = $resource; - return $this; - } - - /** - * Get resource - * - * @return \mysqli - */ - public function getResource() - { - $this->connect(); - return $this->resource; - } - - /** - * Connect - * - * @throws Exception\RuntimeException - * @return Connection - */ - public function connect() - { - if ($this->resource instanceof \mysqli) { - return $this; - } - - // localize - $p = $this->connectionParameters; - - // given a list of key names, test for existence in $p - $findParameterValue = function (array $names) use ($p) { - foreach ($names as $name) { - if (isset($p[$name])) { - return $p[$name]; - } - } - return; - }; - - $hostname = $findParameterValue(array('hostname', 'host')); - $username = $findParameterValue(array('username', 'user')); - $password = $findParameterValue(array('password', 'passwd', 'pw')); - $database = $findParameterValue(array('database', 'dbname', 'db', 'schema')); - $port = (isset($p['port'])) ? (int) $p['port'] : null; - $socket = (isset($p['socket'])) ? $p['socket'] : null; - - $this->resource = new \mysqli(); - $this->resource->init(); - - if (!empty($p['driver_options'])) { - foreach ($p['driver_options'] as $option => $value) { - if (is_string($option)) { - $option = strtoupper($option); - if (!defined($option)) { - continue; - } - $option = constant($option); - } - $this->resource->options($option, $value); - } - } - - $this->resource->real_connect($hostname, $username, $password, $database, $port, $socket); - - if ($this->resource->connect_error) { - throw new Exception\RuntimeException( - 'Connection error', - null, - new Exception\ErrorException($this->resource->connect_error, $this->resource->connect_errno) - ); - } - - if (!empty($p['charset'])) { - $this->resource->set_charset($p['charset']); - } - - return $this; - } - - /** - * Is connected - * - * @return bool - */ - public function isConnected() - { - return ($this->resource instanceof \mysqli); - } - - /** - * Disconnect - * - * @return void - */ - public function disconnect() - { - if ($this->resource instanceof \mysqli) { - $this->resource->close(); - } - $this->resource = null; - } - - /** - * Begin transaction - * - * @return void - */ - public function beginTransaction() - { - if (!$this->isConnected()) { - $this->connect(); - } - - $this->resource->autocommit(false); - $this->inTransaction = true; - } - - /** - * In transaction - * - * @return bool - */ - public function inTransaction() - { - return $this->inTransaction; - } - - /** - * Commit - * - * @return void - */ - public function commit() - { - if (!$this->resource) { - $this->connect(); - } - - $this->resource->commit(); - $this->inTransaction = false; - $this->resource->autocommit(true); - } - - /** - * Rollback - * - * @throws Exception\RuntimeException - * @return Connection - */ - public function rollback() - { - if (!$this->resource) { - throw new Exception\RuntimeException('Must be connected before you can rollback.'); - } - - if (!$this->inTransaction) { - throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback.'); - } - - $this->resource->rollback(); - $this->resource->autocommit(true); - return $this; - } - - /** - * Execute - * - * @param string $sql - * @throws Exception\InvalidQueryException - * @return Result - */ - public function execute($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - if ($this->profiler) { - $this->profiler->profilerStart($sql); - } - - $resultResource = $this->resource->query($sql); - - if ($this->profiler) { - $this->profiler->profilerFinish($sql); - } - - // if the returnValue is something other than a mysqli_result, bypass wrapping it - if ($resultResource === false) { - throw new Exception\InvalidQueryException($this->resource->error); - } - - $resultPrototype = $this->driver->createResult(($resultResource === true) ? $this->resource : $resultResource); - return $resultPrototype; - } - - /** - * Get last generated id - * - * @param null $name Ignored - * @return int - */ - public function getLastGeneratedValue($name = null) - { - return $this->resource->insert_id; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php b/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php deleted file mode 100755 index 443350ca1..000000000 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Mysqli.php +++ /dev/null @@ -1,256 +0,0 @@ - false - ); - - /** - * Constructor - * - * @param array|Connection|\mysqli $connection - * @param null|Statement $statementPrototype - * @param null|Result $resultPrototype - * @param array $options - */ - public function __construct($connection, Statement $statementPrototype = null, Result $resultPrototype = null, array $options = array()) - { - if (!$connection instanceof Connection) { - $connection = new Connection($connection); - } - - $options = array_intersect_key(array_merge($this->options, $options), $this->options); - - $this->registerConnection($connection); - $this->registerStatementPrototype(($statementPrototype) ?: new Statement($options['buffer_results'])); - $this->registerResultPrototype(($resultPrototype) ?: new Result()); - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Mysqli - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->connection instanceof Profiler\ProfilerAwareInterface) { - $this->connection->setProfiler($profiler); - } - if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) { - $this->statementPrototype->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Register connection - * - * @param Connection $connection - * @return Mysqli - */ - public function registerConnection(Connection $connection) - { - $this->connection = $connection; - $this->connection->setDriver($this); // needs access to driver to createStatement() - return $this; - } - - /** - * Register statement prototype - * - * @param Statement $statementPrototype - */ - public function registerStatementPrototype(Statement $statementPrototype) - { - $this->statementPrototype = $statementPrototype; - $this->statementPrototype->setDriver($this); // needs access to driver to createResult() - } - - /** - * Get statement prototype - * - * @return null|Statement - */ - public function getStatementPrototype() - { - return $this->statementPrototype; - } - - /** - * Register result prototype - * - * @param Result $resultPrototype - */ - public function registerResultPrototype(Result $resultPrototype) - { - $this->resultPrototype = $resultPrototype; - } - - /** - * @return null|Result - */ - public function getResultPrototype() - { - return $this->resultPrototype; - } - - /** - * Get database platform name - * - * @param string $nameFormat - * @return string - */ - public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE) - { - if ($nameFormat == self::NAME_FORMAT_CAMELCASE) { - return 'Mysql'; - } - - return 'MySQL'; - } - - /** - * Check environment - * - * @throws Exception\RuntimeException - * @return void - */ - public function checkEnvironment() - { - if (!extension_loaded('mysqli')) { - throw new Exception\RuntimeException('The Mysqli extension is required for this adapter but the extension is not loaded'); - } - } - - /** - * Get connection - * - * @return Connection - */ - public function getConnection() - { - return $this->connection; - } - - /** - * Create statement - * - * @param string $sqlOrResource - * @return Statement - */ - public function createStatement($sqlOrResource = null) - { - /** - * @todo Resource tracking - if (is_resource($sqlOrResource) && !in_array($sqlOrResource, $this->resources, true)) { - $this->resources[] = $sqlOrResource; - } - */ - - $statement = clone $this->statementPrototype; - if ($sqlOrResource instanceof mysqli_stmt) { - $statement->setResource($sqlOrResource); - } else { - if (is_string($sqlOrResource)) { - $statement->setSql($sqlOrResource); - } - if (!$this->connection->isConnected()) { - $this->connection->connect(); - } - $statement->initialize($this->connection->getResource()); - } - return $statement; - } - - /** - * Create result - * - * @param resource $resource - * @param null|bool $isBuffered - * @return Result - */ - public function createResult($resource, $isBuffered = null) - { - $result = clone $this->resultPrototype; - $result->initialize($resource, $this->connection->getLastGeneratedValue(), $isBuffered); - return $result; - } - - /** - * Get prepare type - * - * @return array - */ - public function getPrepareType() - { - return self::PARAMETERIZATION_POSITIONAL; - } - - /** - * Format parameter name - * - * @param string $name - * @param mixed $type - * @return string - */ - public function formatParameterName($name, $type = null) - { - return '?'; - } - - /** - * Get last generated value - * - * @return mixed - */ - public function getLastGeneratedValue() - { - return $this->getConnection()->getLastGeneratedValue(); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Result.php b/library/Zend/Db/Adapter/Driver/Mysqli/Result.php deleted file mode 100755 index 11622b15a..000000000 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Result.php +++ /dev/null @@ -1,341 +0,0 @@ - null, 'values' => array()); - - /** - * @var mixed - */ - protected $generatedValue = null; - - /** - * Initialize - * - * @param mixed $resource - * @param mixed $generatedValue - * @param bool|null $isBuffered - * @throws Exception\InvalidArgumentException - * @return Result - */ - public function initialize($resource, $generatedValue, $isBuffered = null) - { - if (!$resource instanceof \mysqli && !$resource instanceof \mysqli_result && !$resource instanceof \mysqli_stmt) { - throw new Exception\InvalidArgumentException('Invalid resource provided.'); - } - - if ($isBuffered !== null) { - $this->isBuffered = $isBuffered; - } else { - if ($resource instanceof \mysqli || $resource instanceof \mysqli_result - || $resource instanceof \mysqli_stmt && $resource->num_rows != 0) { - $this->isBuffered = true; - } - } - - $this->resource = $resource; - $this->generatedValue = $generatedValue; - return $this; - } - - /** - * Force buffering - * - * @throws Exception\RuntimeException - */ - public function buffer() - { - if ($this->resource instanceof \mysqli_stmt && $this->isBuffered !== true) { - if ($this->position > 0) { - throw new Exception\RuntimeException('Cannot buffer a result set that has started iteration.'); - } - $this->resource->store_result(); - $this->isBuffered = true; - } - } - - /** - * Check if is buffered - * - * @return bool|null - */ - public function isBuffered() - { - return $this->isBuffered; - } - - /** - * Return the resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Is query result? - * - * @return bool - */ - public function isQueryResult() - { - return ($this->resource->field_count > 0); - } - - /** - * Get affected rows - * - * @return int - */ - public function getAffectedRows() - { - if ($this->resource instanceof \mysqli || $this->resource instanceof \mysqli_stmt) { - return $this->resource->affected_rows; - } - - return $this->resource->num_rows; - } - - /** - * Current - * - * @return mixed - */ - public function current() - { - if ($this->currentComplete) { - return $this->currentData; - } - - if ($this->resource instanceof \mysqli_stmt) { - $this->loadDataFromMysqliStatement(); - return $this->currentData; - } else { - $this->loadFromMysqliResult(); - return $this->currentData; - } - } - - /** - * Mysqli's binding and returning of statement values - * - * Mysqli requires you to bind variables to the extension in order to - * get data out. These values have to be references: - * @see http://php.net/manual/en/mysqli-stmt.bind-result.php - * - * @throws Exception\RuntimeException - * @return bool - */ - protected function loadDataFromMysqliStatement() - { - $data = null; - // build the default reference based bind structure, if it does not already exist - if ($this->statementBindValues['keys'] === null) { - $this->statementBindValues['keys'] = array(); - $resultResource = $this->resource->result_metadata(); - foreach ($resultResource->fetch_fields() as $col) { - $this->statementBindValues['keys'][] = $col->name; - } - $this->statementBindValues['values'] = array_fill(0, count($this->statementBindValues['keys']), null); - $refs = array(); - foreach ($this->statementBindValues['values'] as $i => &$f) { - $refs[$i] = &$f; - } - call_user_func_array(array($this->resource, 'bind_result'), $this->statementBindValues['values']); - } - - if (($r = $this->resource->fetch()) === null) { - if (!$this->isBuffered) { - $this->resource->close(); - } - return false; - } elseif ($r === false) { - throw new Exception\RuntimeException($this->resource->error); - } - - // dereference - for ($i = 0, $count = count($this->statementBindValues['keys']); $i < $count; $i++) { - $this->currentData[$this->statementBindValues['keys'][$i]] = $this->statementBindValues['values'][$i]; - } - $this->currentComplete = true; - $this->nextComplete = true; - $this->position++; - return true; - } - - /** - * Load from mysqli result - * - * @return bool - */ - protected function loadFromMysqliResult() - { - $this->currentData = null; - - if (($data = $this->resource->fetch_assoc()) === null) { - return false; - } - - $this->position++; - $this->currentData = $data; - $this->currentComplete = true; - $this->nextComplete = true; - $this->position++; - return true; - } - - /** - * Next - * - * @return void - */ - public function next() - { - $this->currentComplete = false; - - if ($this->nextComplete == false) { - $this->position++; - } - - $this->nextComplete = false; - } - - /** - * Key - * - * @return mixed - */ - public function key() - { - return $this->position; - } - - /** - * Rewind - * - * @throws Exception\RuntimeException - * @return void - */ - public function rewind() - { - if ($this->position !== 0) { - if ($this->isBuffered === false) { - throw new Exception\RuntimeException('Unbuffered results cannot be rewound for multiple iterations'); - } - } - $this->resource->data_seek(0); // works for both mysqli_result & mysqli_stmt - $this->currentComplete = false; - $this->position = 0; - } - - /** - * Valid - * - * @return bool - */ - public function valid() - { - if ($this->currentComplete) { - return true; - } - - if ($this->resource instanceof \mysqli_stmt) { - return $this->loadDataFromMysqliStatement(); - } - - return $this->loadFromMysqliResult(); - } - - /** - * Count - * - * @throws Exception\RuntimeException - * @return int - */ - public function count() - { - if ($this->isBuffered === false) { - throw new Exception\RuntimeException('Row count is not available in unbuffered result sets.'); - } - return $this->resource->num_rows; - } - - /** - * Get field count - * - * @return int - */ - public function getFieldCount() - { - return $this->resource->field_count; - } - - /** - * Get generated value - * - * @return mixed|null - */ - public function getGeneratedValue() - { - return $this->generatedValue; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Mysqli/Statement.php b/library/Zend/Db/Adapter/Driver/Mysqli/Statement.php deleted file mode 100755 index d462cd177..000000000 --- a/library/Zend/Db/Adapter/Driver/Mysqli/Statement.php +++ /dev/null @@ -1,315 +0,0 @@ -bufferResults = (bool) $bufferResults; - } - - /** - * Set driver - * - * @param Mysqli $driver - * @return Statement - */ - public function setDriver(Mysqli $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Statement - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Initialize - * - * @param \mysqli $mysqli - * @return Statement - */ - public function initialize(\mysqli $mysqli) - { - $this->mysqli = $mysqli; - return $this; - } - - /** - * Set sql - * - * @param string $sql - * @return Statement - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * Set Parameter container - * - * @param ParameterContainer $parameterContainer - * @return Statement - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * Get resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Set resource - * - * @param \mysqli_stmt $mysqliStatement - * @return Statement - */ - public function setResource(\mysqli_stmt $mysqliStatement) - { - $this->resource = $mysqliStatement; - $this->isPrepared = true; - return $this; - } - - /** - * Get sql - * - * @return string - */ - public function getSql() - { - return $this->sql; - } - - /** - * Get parameter count - * - * @return ParameterContainer - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } - - /** - * Is prepared - * - * @return bool - */ - public function isPrepared() - { - return $this->isPrepared; - } - - /** - * Prepare - * - * @param string $sql - * @throws Exception\InvalidQueryException - * @throws Exception\RuntimeException - * @return Statement - */ - public function prepare($sql = null) - { - if ($this->isPrepared) { - throw new Exception\RuntimeException('This statement has already been prepared'); - } - - $sql = ($sql) ?: $this->sql; - - $this->resource = $this->mysqli->prepare($sql); - if (!$this->resource instanceof \mysqli_stmt) { - throw new Exception\InvalidQueryException( - 'Statement couldn\'t be produced with sql: ' . $sql, - null, - new Exception\ErrorException($this->mysqli->error, $this->mysqli->errno) - ); - } - - $this->isPrepared = true; - return $this; - } - - /** - * Execute - * - * @param ParameterContainer|array $parameters - * @throws Exception\RuntimeException - * @return mixed - */ - public function execute($parameters = null) - { - if (!$this->isPrepared) { - $this->prepare(); - } - - /** START Standard ParameterContainer Merging Block */ - if (!$this->parameterContainer instanceof ParameterContainer) { - if ($parameters instanceof ParameterContainer) { - $this->parameterContainer = $parameters; - $parameters = null; - } else { - $this->parameterContainer = new ParameterContainer(); - } - } - - if (is_array($parameters)) { - $this->parameterContainer->setFromArray($parameters); - } - - if ($this->parameterContainer->count() > 0) { - $this->bindParametersFromContainer(); - } - /** END Standard ParameterContainer Merging Block */ - - if ($this->profiler) { - $this->profiler->profilerStart($this); - } - - $return = $this->resource->execute(); - - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - - if ($return === false) { - throw new Exception\RuntimeException($this->resource->error); - } - - if ($this->bufferResults === true) { - $this->resource->store_result(); - $this->isPrepared = false; - $buffered = true; - } else { - $buffered = false; - } - - $result = $this->driver->createResult($this->resource, $buffered); - return $result; - } - - /** - * Bind parameters from container - * - * @return void - */ - protected function bindParametersFromContainer() - { - $parameters = $this->parameterContainer->getNamedArray(); - $type = ''; - $args = array(); - - foreach ($parameters as $name => &$value) { - if ($this->parameterContainer->offsetHasErrata($name)) { - switch ($this->parameterContainer->offsetGetErrata($name)) { - case ParameterContainer::TYPE_DOUBLE: - $type .= 'd'; - break; - case ParameterContainer::TYPE_NULL: - $value = null; // as per @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php#96148 - case ParameterContainer::TYPE_INTEGER: - $type .= 'i'; - break; - case ParameterContainer::TYPE_STRING: - default: - $type .= 's'; - break; - } - } else { - $type .= 's'; - } - $args[] = &$value; - } - - if ($args) { - array_unshift($args, $type); - call_user_func_array(array($this->resource, 'bind_param'), $args); - } - } -} diff --git a/library/Zend/Db/Adapter/Driver/Oci8/Connection.php b/library/Zend/Db/Adapter/Driver/Oci8/Connection.php deleted file mode 100755 index 73376521e..000000000 --- a/library/Zend/Db/Adapter/Driver/Oci8/Connection.php +++ /dev/null @@ -1,346 +0,0 @@ -setConnectionParameters($connectionInfo); - } elseif ($connectionInfo instanceof \oci8) { - $this->setResource($connectionInfo); - } elseif (null !== $connectionInfo) { - throw new Exception\InvalidArgumentException('$connection must be an array of parameters, an oci8 resource or null'); - } - } - - /** - * @param Oci8 $driver - * @return Connection - */ - public function setDriver(Oci8 $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Connection - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Set connection parameters - * - * @param array $connectionParameters - * @return Connection - */ - public function setConnectionParameters(array $connectionParameters) - { - $this->connectionParameters = $connectionParameters; - return $this; - } - - /** - * Get connection parameters - * - * @return array - */ - public function getConnectionParameters() - { - return $this->connectionParameters; - } - - /** - * Get current schema - * - * @return string - */ - public function getCurrentSchema() - { - if (!$this->isConnected()) { - $this->connect(); - } - - $query = "SELECT sys_context('USERENV', 'CURRENT_SCHEMA') as \"current_schema\" FROM DUAL"; - $stmt = oci_parse($this->resource, $query); - oci_execute($stmt); - $dbNameArray = oci_fetch_array($stmt, OCI_ASSOC); - return $dbNameArray['current_schema']; - } - - /** - * Set resource - * - * @param resource $resource - * @return Connection - */ - public function setResource($resource) - { - if (!is_resource($resource) || get_resource_type($resource) !== 'oci8 connection') { - throw new Exception\InvalidArgumentException('A resource of type "oci8 connection" was expected'); - } - $this->resource = $resource; - return $this; - } - - /** - * Get resource - * - * @return \oci8 - */ - public function getResource() - { - $this->connect(); - return $this->resource; - } - - /** - * Connect - * - * @return Connection - */ - public function connect() - { - if (is_resource($this->resource)) { - return $this; - } - - // localize - $p = $this->connectionParameters; - - // given a list of key names, test for existence in $p - $findParameterValue = function (array $names) use ($p) { - foreach ($names as $name) { - if (isset($p[$name])) { - return $p[$name]; - } - } - return null; - }; - - // http://www.php.net/manual/en/function.oci-connect.php - $username = $findParameterValue(array('username')); - $password = $findParameterValue(array('password')); - $connectionString = $findParameterValue(array('connection_string', 'connectionstring', 'connection', 'hostname', 'instance')); - $characterSet = $findParameterValue(array('character_set', 'charset', 'encoding')); - $sessionMode = $findParameterValue(array('session_mode')); - - // connection modifiers - $isUnique = $findParameterValue(array('unique')); - $isPersistent = $findParameterValue(array('persistent')); - - if ($isUnique == true) { - $this->resource = oci_new_connect($username, $password, $connectionString, $characterSet, $sessionMode); - } elseif ($isPersistent == true) { - $this->resource = oci_pconnect($username, $password, $connectionString, $characterSet, $sessionMode); - } else { - $this->resource = oci_connect($username, $password, $connectionString, $characterSet, $sessionMode); - } - - if (!$this->resource) { - $e = oci_error(); - throw new Exception\RuntimeException( - 'Connection error', - null, - new Exception\ErrorException($e['message'], $e['code']) - ); - } - - return $this; - } - - /** - * Is connected - * - * @return bool - */ - public function isConnected() - { - return (is_resource($this->resource)); - } - - /** - * Disconnect - */ - public function disconnect() - { - if (is_resource($this->resource)) { - oci_close($this->resource); - } - } - - /** - * Begin transaction - */ - public function beginTransaction() - { - if (!$this->isConnected()) { - $this->connect(); - } - - // A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. - $this->inTransaction = true; - } - - /** - * In transaction - * - * @return bool - */ - public function inTransaction() - { - return $this->inTransaction; - } - - /** - * Commit - */ - public function commit() - { - if (!$this->resource) { - $this->connect(); - } - - if ($this->inTransaction) { - $valid = oci_commit($this->resource); - if ($valid === false) { - $e = oci_error($this->resource); - throw new Exception\InvalidQueryException($e['message'], $e['code']); - } - } - } - - /** - * Rollback - * - * @return Connection - */ - public function rollback() - { - if (!$this->resource) { - throw new Exception\RuntimeException('Must be connected before you can rollback.'); - } - - if (!$this->inTransaction) { - throw new Exception\RuntimeException('Must call commit() before you can rollback.'); - } - - $valid = oci_rollback($this->resource); - if ($valid === false) { - $e = oci_error($this->resource); - throw new Exception\InvalidQueryException($e['message'], $e['code']); - } - - return $this; - } - - /** - * Execute - * - * @param string $sql - * @return Result - */ - public function execute($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - if ($this->profiler) { - $this->profiler->profilerStart($sql); - } - - $ociStmt = oci_parse($this->resource, $sql); - - if ($this->inTransaction) { - $valid = @oci_execute($ociStmt, OCI_NO_AUTO_COMMIT); - } else { - $valid = @oci_execute($ociStmt, OCI_COMMIT_ON_SUCCESS); - } - - if ($this->profiler) { - $this->profiler->profilerFinish($sql); - } - - if ($valid === false) { - $e = oci_error($ociStmt); - throw new Exception\InvalidQueryException($e['message'], $e['code']); - } - - $resultPrototype = $this->driver->createResult($ociStmt); - return $resultPrototype; - } - - /** - * Get last generated id - * - * @param null $name Ignored - * @return int - */ - public function getLastGeneratedValue($name = null) - { - // @todo Get Last Generated Value in Connection (this might not apply) - return null; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Oci8/Oci8.php b/library/Zend/Db/Adapter/Driver/Oci8/Oci8.php deleted file mode 100755 index 9685f8c41..000000000 --- a/library/Zend/Db/Adapter/Driver/Oci8/Oci8.php +++ /dev/null @@ -1,223 +0,0 @@ -registerConnection($connection); - $this->registerStatementPrototype(($statementPrototype) ?: new Statement()); - $this->registerResultPrototype(($resultPrototype) ?: new Result()); - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Oci8 - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->connection instanceof Profiler\ProfilerAwareInterface) { - $this->connection->setProfiler($profiler); - } - if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) { - $this->statementPrototype->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Register connection - * - * @param Connection $connection - * @return Oci8 - */ - public function registerConnection(Connection $connection) - { - $this->connection = $connection; - $this->connection->setDriver($this); // needs access to driver to createStatement() - return $this; - } - - /** - * Register statement prototype - * - * @param Statement $statementPrototype - * @return Oci8 - */ - public function registerStatementPrototype(Statement $statementPrototype) - { - $this->statementPrototype = $statementPrototype; - $this->statementPrototype->setDriver($this); // needs access to driver to createResult() - return $this; - } - - /** - * @return null|Statement - */ - public function getStatementPrototype() - { - return $this->statementPrototype; - } - - /** - * Register result prototype - * - * @param Result $resultPrototype - * @return Oci8 - */ - public function registerResultPrototype(Result $resultPrototype) - { - $this->resultPrototype = $resultPrototype; - return $this; - } - - /** - * @return null|Result - */ - public function getResultPrototype() - { - return $this->resultPrototype; - } - - /** - * Get database platform name - * - * @param string $nameFormat - * @return string - */ - public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE) - { - return 'Oracle'; - } - - /** - * Check environment - */ - public function checkEnvironment() - { - if (!extension_loaded('oci8')) { - throw new Exception\RuntimeException('The Oci8 extension is required for this adapter but the extension is not loaded'); - } - } - - /** - * @return Connection - */ - public function getConnection() - { - return $this->connection; - } - - /** - * @param string $sqlOrResource - * @return Statement - */ - public function createStatement($sqlOrResource = null) - { - $statement = clone $this->statementPrototype; - if (is_resource($sqlOrResource) && get_resource_type($sqlOrResource) == 'oci8 statement') { - $statement->setResource($sqlOrResource); - } else { - if (is_string($sqlOrResource)) { - $statement->setSql($sqlOrResource); - } elseif ($sqlOrResource !== null) { - throw new Exception\InvalidArgumentException( - 'Oci8 only accepts an SQL string or an oci8 resource in ' . __FUNCTION__ - ); - } - if (!$this->connection->isConnected()) { - $this->connection->connect(); - } - $statement->initialize($this->connection->getResource()); - } - return $statement; - } - - /** - * @param resource $resource - * @param null $isBuffered - * @return Result - */ - public function createResult($resource, $isBuffered = null) - { - $result = clone $this->resultPrototype; - $result->initialize($resource, $this->connection->getLastGeneratedValue(), $isBuffered); - return $result; - } - - /** - * @return array - */ - public function getPrepareType() - { - return self::PARAMETERIZATION_NAMED; - } - - /** - * @param string $name - * @param mixed $type - * @return string - */ - public function formatParameterName($name, $type = null) - { - return ':' . $name; - } - - /** - * @return mixed - */ - public function getLastGeneratedValue() - { - return $this->getConnection()->getLastGeneratedValue(); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Oci8/Result.php b/library/Zend/Db/Adapter/Driver/Oci8/Result.php deleted file mode 100755 index f0ae96abd..000000000 --- a/library/Zend/Db/Adapter/Driver/Oci8/Result.php +++ /dev/null @@ -1,224 +0,0 @@ - null, 'values' => array()); - - /** - * @var mixed - */ - protected $generatedValue = null; - - /** - * Initialize - * @param resource $resource - * @return Result - */ - public function initialize($resource /*, $generatedValue, $isBuffered = null*/) - { - if (!is_resource($resource) && get_resource_type($resource) !== 'oci8 statement') { - throw new Exception\InvalidArgumentException('Invalid resource provided.'); - } - $this->resource = $resource; - return $this; - } - - /** - * Force buffering at driver level - * - * Oracle does not support this, to my knowledge (@ralphschindler) - * - * @throws Exception\RuntimeException - */ - public function buffer() - { - return null; - } - - /** - * Is the result buffered? - * - * @return bool - */ - public function isBuffered() - { - return false; - } - - /** - * Return the resource - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Is query result? - * - * @return bool - */ - public function isQueryResult() - { - return (oci_num_fields($this->resource) > 0); - } - - /** - * Get affected rows - * @return int - */ - public function getAffectedRows() - { - return oci_num_rows($this->resource); - } - - /** - * Current - * @return mixed - */ - public function current() - { - if ($this->currentComplete == false) { - if ($this->loadData() === false) { - return false; - } - } - - return $this->currentData; - } - - /** - * Load from oci8 result - * - * @return bool - */ - protected function loadData() - { - $this->currentComplete = true; - $this->currentData = oci_fetch_assoc($this->resource); - - if ($this->currentData !== false) { - $this->position++; - return true; - } - return false; - } - - /** - * Next - */ - public function next() - { - return $this->loadData(); - } - - /** - * Key - * @return mixed - */ - public function key() - { - return $this->position; - } - - /** - * Rewind - */ - public function rewind() - { - if ($this->position > 0) { - throw new Exception\RuntimeException('Oci8 results cannot be rewound for multiple iterations'); - } - } - - /** - * Valid - * @return bool - */ - public function valid() - { - if ($this->currentComplete) { - return ($this->currentData !== false); - } - - return $this->loadData(); - } - - /** - * Count - * @return int - */ - public function count() - { - // @todo OCI8 row count in Driver Result - return null; - } - - /** - * @return int - */ - public function getFieldCount() - { - return oci_num_fields($this->resource); - } - - /** - * @return mixed|null - */ - public function getGeneratedValue() - { - // @todo OCI8 generated value in Driver Result - return null; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Oci8/Statement.php b/library/Zend/Db/Adapter/Driver/Oci8/Statement.php deleted file mode 100755 index 707442fde..000000000 --- a/library/Zend/Db/Adapter/Driver/Oci8/Statement.php +++ /dev/null @@ -1,311 +0,0 @@ -driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Statement - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Initialize - * - * @param resource $oci8 - * @return Statement - */ - public function initialize($oci8) - { - $this->oci8 = $oci8; - return $this; - } - - /** - * Set sql - * - * @param string $sql - * @return Statement - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * Set Parameter container - * - * @param ParameterContainer $parameterContainer - * @return Statement - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * Get resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Set resource - * - * @param resource $oci8Statement - * @return Statement - */ - public function setResource($oci8Statement) - { - $type = oci_statement_type($oci8Statement); - if (false === $type || 'UNKNOWN' == $type) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid statement provided to %s', - __METHOD__ - )); - } - $this->resource = $oci8Statement; - $this->isPrepared = true; - return $this; - } - - /** - * Get sql - * - * @return string - */ - public function getSql() - { - return $this->sql; - } - - /** - * @return ParameterContainer - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } - - /** - * @return bool - */ - public function isPrepared() - { - return $this->isPrepared; - } - - /** - * @param string $sql - * @return Statement - */ - public function prepare($sql = null) - { - if ($this->isPrepared) { - throw new Exception\RuntimeException('This statement has already been prepared'); - } - - $sql = ($sql) ?: $this->sql; - - // get oci8 statement resource - $this->resource = oci_parse($this->oci8, $sql); - - if (!$this->resource) { - $e = oci_error($this->oci8); - throw new Exception\InvalidQueryException( - 'Statement couldn\'t be produced with sql: ' . $sql, - null, - new Exception\ErrorException($e['message'], $e['code']) - ); - } - - $this->isPrepared = true; - return $this; - } - - /** - * Execute - * - * @param ParameterContainer $parameters - * @return mixed - */ - public function execute($parameters = null) - { - if (!$this->isPrepared) { - $this->prepare(); - } - - /** START Standard ParameterContainer Merging Block */ - if (!$this->parameterContainer instanceof ParameterContainer) { - if ($parameters instanceof ParameterContainer) { - $this->parameterContainer = $parameters; - $parameters = null; - } else { - $this->parameterContainer = new ParameterContainer(); - } - } - - if (is_array($parameters)) { - $this->parameterContainer->setFromArray($parameters); - } - - if ($this->parameterContainer->count() > 0) { - $this->bindParametersFromContainer(); - } - /** END Standard ParameterContainer Merging Block */ - - if ($this->profiler) { - $this->profiler->profilerStart($this); - } - - if ($this->driver->getConnection()->inTransaction()) { - $ret = @oci_execute($this->resource, OCI_NO_AUTO_COMMIT); - } else { - $ret = @oci_execute($this->resource, OCI_COMMIT_ON_SUCCESS); - } - - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - - if ($ret === false) { - $e = oci_error($this->resource); - throw new Exception\RuntimeException($e['message'], $e['code']); - } - - $result = $this->driver->createResult($this->resource); - return $result; - } - - /** - * Bind parameters from container - * - * @param ParameterContainer $pContainer - */ - protected function bindParametersFromContainer() - { - $parameters = $this->parameterContainer->getNamedArray(); - - foreach ($parameters as $name => &$value) { - if ($this->parameterContainer->offsetHasErrata($name)) { - switch ($this->parameterContainer->offsetGetErrata($name)) { - case ParameterContainer::TYPE_NULL: - $type = null; - $value = null; - break; - case ParameterContainer::TYPE_DOUBLE: - case ParameterContainer::TYPE_INTEGER: - $type = SQLT_INT; - if (is_string($value)) { - $value = (int) $value; - } - break; - case ParameterContainer::TYPE_BINARY: - $type = SQLT_BIN; - break; - case ParameterContainer::TYPE_LOB: - $type = OCI_B_CLOB; - $clob = oci_new_descriptor($this->driver->getConnection()->getResource(), OCI_DTYPE_LOB); - $clob->writetemporary($value, OCI_TEMP_CLOB); - $value = $clob; - break; - case ParameterContainer::TYPE_STRING: - default: - $type = SQLT_CHR; - break; - } - } else { - $type = SQLT_CHR; - } - - oci_bind_by_name($this->resource, $name, $value, -1, $type); - } - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Connection.php b/library/Zend/Db/Adapter/Driver/Pdo/Connection.php deleted file mode 100755 index 1cd2c6667..000000000 --- a/library/Zend/Db/Adapter/Driver/Pdo/Connection.php +++ /dev/null @@ -1,488 +0,0 @@ -setConnectionParameters($connectionParameters); - } elseif ($connectionParameters instanceof \PDO) { - $this->setResource($connectionParameters); - } elseif (null !== $connectionParameters) { - throw new Exception\InvalidArgumentException('$connection must be an array of parameters, a PDO object or null'); - } - } - - /** - * Set driver - * - * @param Pdo $driver - * @return Connection - */ - public function setDriver(Pdo $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Connection - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Get driver name - * - * @return null|string - */ - public function getDriverName() - { - return $this->driverName; - } - - /** - * Set connection parameters - * - * @param array $connectionParameters - * @return void - */ - public function setConnectionParameters(array $connectionParameters) - { - $this->connectionParameters = $connectionParameters; - if (isset($connectionParameters['dsn'])) { - $this->driverName = substr($connectionParameters['dsn'], 0, - strpos($connectionParameters['dsn'], ':') - ); - } elseif (isset($connectionParameters['pdodriver'])) { - $this->driverName = strtolower($connectionParameters['pdodriver']); - } elseif (isset($connectionParameters['driver'])) { - $this->driverName = strtolower(substr( - str_replace(array('-', '_', ' '), '', $connectionParameters['driver']), - 3 - )); - } - } - - /** - * Get connection parameters - * - * @return array - */ - public function getConnectionParameters() - { - return $this->connectionParameters; - } - - /** - * Get the dsn string for this connection - * @throws \Zend\Db\Adapter\Exception\RunTimeException - * @return string - */ - public function getDsn() - { - if (!$this->dsn) { - throw new Exception\RunTimeException("The DSN has not been set or constructed from parameters in connect() for this Connection"); - } - - return $this->dsn; - } - - /** - * Get current schema - * - * @return string - */ - public function getCurrentSchema() - { - if (!$this->isConnected()) { - $this->connect(); - } - - switch ($this->driverName) { - case 'mysql': - $sql = 'SELECT DATABASE()'; - break; - case 'sqlite': - return 'main'; - case 'sqlsrv': - case 'dblib': - $sql = 'SELECT SCHEMA_NAME()'; - break; - case 'pgsql': - default: - $sql = 'SELECT CURRENT_SCHEMA'; - break; - } - - /** @var $result \PDOStatement */ - $result = $this->resource->query($sql); - if ($result instanceof \PDOStatement) { - return $result->fetchColumn(); - } - return false; - } - - /** - * Set resource - * - * @param \PDO $resource - * @return Connection - */ - public function setResource(\PDO $resource) - { - $this->resource = $resource; - $this->driverName = strtolower($this->resource->getAttribute(\PDO::ATTR_DRIVER_NAME)); - return $this; - } - - /** - * Get resource - * - * @return \PDO - */ - public function getResource() - { - if (!$this->isConnected()) { - $this->connect(); - } - return $this->resource; - } - - /** - * Connect - * - * @return Connection - * @throws Exception\InvalidConnectionParametersException - * @throws Exception\RuntimeException - */ - public function connect() - { - if ($this->resource) { - return $this; - } - - $dsn = $username = $password = $hostname = $database = null; - $options = array(); - foreach ($this->connectionParameters as $key => $value) { - switch (strtolower($key)) { - case 'dsn': - $dsn = $value; - break; - case 'driver': - $value = strtolower($value); - if (strpos($value, 'pdo') === 0) { - $pdoDriver = strtolower(substr(str_replace(array('-', '_', ' '), '', $value), 3)); - } - break; - case 'pdodriver': - $pdoDriver = (string) $value; - break; - case 'user': - case 'username': - $username = (string) $value; - break; - case 'pass': - case 'password': - $password = (string) $value; - break; - case 'host': - case 'hostname': - $hostname = (string) $value; - break; - case 'port': - $port = (int) $value; - break; - case 'database': - case 'dbname': - $database = (string) $value; - break; - case 'charset': - $charset = (string) $value; - break; - case 'driver_options': - case 'options': - $value = (array) $value; - $options = array_diff_key($options, $value) + $value; - break; - default: - $options[$key] = $value; - break; - } - } - - if (!isset($dsn) && isset($pdoDriver)) { - $dsn = array(); - switch ($pdoDriver) { - case 'sqlite': - $dsn[] = $database; - break; - case 'sqlsrv': - if (isset($database)) { - $dsn[] = "database={$database}"; - } - if (isset($hostname)) { - $dsn[] = "server={$hostname}"; - } - break; - default: - if (isset($database)) { - $dsn[] = "dbname={$database}"; - } - if (isset($hostname)) { - $dsn[] = "host={$hostname}"; - } - if (isset($port)) { - $dsn[] = "port={$port}"; - } - if (isset($charset) && $pdoDriver != 'pgsql') { - $dsn[] = "charset={$charset}"; - } - break; - } - $dsn = $pdoDriver . ':' . implode(';', $dsn); - } elseif (!isset($dsn)) { - throw new Exception\InvalidConnectionParametersException( - 'A dsn was not provided or could not be constructed from your parameters', - $this->connectionParameters - ); - } - - $this->dsn = $dsn; - - try { - $this->resource = new \PDO($dsn, $username, $password, $options); - $this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - if (isset($charset) && $pdoDriver == 'pgsql') { - $this->resource->exec('SET NAMES ' . $this->resource->quote($charset)); - } - $this->driverName = strtolower($this->resource->getAttribute(\PDO::ATTR_DRIVER_NAME)); - } catch (\PDOException $e) { - $code = $e->getCode(); - if (!is_long($code)) { - $code = null; - } - throw new Exception\RuntimeException('Connect Error: ' . $e->getMessage(), $code, $e); - } - - return $this; - } - - /** - * Is connected - * - * @return bool - */ - public function isConnected() - { - return ($this->resource instanceof \PDO); - } - - /** - * Disconnect - * - * @return Connection - */ - public function disconnect() - { - if ($this->isConnected()) { - $this->resource = null; - } - return $this; - } - - /** - * Begin transaction - * - * @return Connection - */ - public function beginTransaction() - { - if (!$this->isConnected()) { - $this->connect(); - } - $this->resource->beginTransaction(); - $this->inTransaction = true; - return $this; - } - - /** - * In transaction - * - * @return bool - */ - public function inTransaction() - { - return $this->inTransaction; - } - - /** - * Commit - * - * @return Connection - */ - public function commit() - { - if (!$this->isConnected()) { - $this->connect(); - } - - $this->resource->commit(); - $this->inTransaction = false; - return $this; - } - - /** - * Rollback - * - * @return Connection - * @throws Exception\RuntimeException - */ - public function rollback() - { - if (!$this->isConnected()) { - throw new Exception\RuntimeException('Must be connected before you can rollback'); - } - - if (!$this->inTransaction) { - throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback'); - } - - $this->resource->rollBack(); - return $this; - } - - /** - * Execute - * - * @param $sql - * @return Result - * @throws Exception\InvalidQueryException - */ - public function execute($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - if ($this->profiler) { - $this->profiler->profilerStart($sql); - } - - $resultResource = $this->resource->query($sql); - - if ($this->profiler) { - $this->profiler->profilerFinish($sql); - } - - if ($resultResource === false) { - $errorInfo = $this->resource->errorInfo(); - throw new Exception\InvalidQueryException($errorInfo[2]); - } - - $result = $this->driver->createResult($resultResource, $sql); - return $result; - } - - /** - * Prepare - * - * @param string $sql - * @return Statement - */ - public function prepare($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - $statement = $this->driver->createStatement($sql); - return $statement; - } - - /** - * Get last generated id - * - * @param string $name - * @return string|null|false - */ - public function getLastGeneratedValue($name = null) - { - if ($name === null && $this->driverName == 'pgsql') { - return null; - } - - try { - return $this->resource->lastInsertId($name); - } catch (\Exception $e) { - // do nothing - } - return false; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Feature/OracleRowCounter.php b/library/Zend/Db/Adapter/Driver/Pdo/Feature/OracleRowCounter.php deleted file mode 100755 index 2a25cdd6b..000000000 --- a/library/Zend/Db/Adapter/Driver/Pdo/Feature/OracleRowCounter.php +++ /dev/null @@ -1,78 +0,0 @@ -getSql(); - if ($sql == '' || stripos($sql, 'select') === false) { - return null; - } - $countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')'; - $countStmt->prepare($countSql); - $result = $countStmt->execute(); - $countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC); - unset($statement, $result); - return $countRow['count']; - } - - /** - * @param $sql - * @return null|int - */ - public function getCountForSql($sql) - { - if (stripos($sql, 'select') === false) { - return null; - } - $countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')'; - /** @var $pdo \PDO */ - $pdo = $this->driver->getConnection()->getResource(); - $result = $pdo->query($countSql); - $countRow = $result->fetch(\PDO::FETCH_ASSOC); - return $countRow['count']; - } - - /** - * @param $context - * @return \Closure - */ - public function getRowCountClosure($context) - { - $oracleRowCounter = $this; - return function () use ($oracleRowCounter, $context) { - /** @var $oracleRowCounter OracleRowCounter */ - return ($context instanceof Pdo\Statement) - ? $oracleRowCounter->getCountForStatement($context) - : $oracleRowCounter->getCountForSql($context); - }; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php b/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php deleted file mode 100755 index 13c8d66d4..000000000 --- a/library/Zend/Db/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php +++ /dev/null @@ -1,78 +0,0 @@ -getSql(); - if ($sql == '' || stripos($sql, 'select') === false) { - return null; - } - $countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')'; - $countStmt->prepare($countSql); - $result = $countStmt->execute(); - $countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC); - unset($statement, $result); - return $countRow['count']; - } - - /** - * @param $sql - * @return null|int - */ - public function getCountForSql($sql) - { - if (stripos($sql, 'select') === false) { - return null; - } - $countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')'; - /** @var $pdo \PDO */ - $pdo = $this->driver->getConnection()->getResource(); - $result = $pdo->query($countSql); - $countRow = $result->fetch(\PDO::FETCH_ASSOC); - return $countRow['count']; - } - - /** - * @param $context - * @return \Closure - */ - public function getRowCountClosure($context) - { - $sqliteRowCounter = $this; - return function () use ($sqliteRowCounter, $context) { - /** @var $sqliteRowCounter SqliteRowCounter */ - return ($context instanceof Pdo\Statement) - ? $sqliteRowCounter->getCountForStatement($context) - : $sqliteRowCounter->getCountForSql($context); - }; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php b/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php deleted file mode 100755 index 3de7beb49..000000000 --- a/library/Zend/Db/Adapter/Driver/Pdo/Pdo.php +++ /dev/null @@ -1,314 +0,0 @@ -registerConnection($connection); - $this->registerStatementPrototype(($statementPrototype) ?: new Statement()); - $this->registerResultPrototype(($resultPrototype) ?: new Result()); - if (is_array($features)) { - foreach ($features as $name => $feature) { - $this->addFeature($name, $feature); - } - } elseif ($features instanceof AbstractFeature) { - $this->addFeature($features->getName(), $features); - } elseif ($features === self::FEATURES_DEFAULT) { - $this->setupDefaultFeatures(); - } - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Pdo - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->connection instanceof Profiler\ProfilerAwareInterface) { - $this->connection->setProfiler($profiler); - } - if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) { - $this->statementPrototype->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Register connection - * - * @param Connection $connection - * @return Pdo - */ - public function registerConnection(Connection $connection) - { - $this->connection = $connection; - $this->connection->setDriver($this); - return $this; - } - - /** - * Register statement prototype - * - * @param Statement $statementPrototype - */ - public function registerStatementPrototype(Statement $statementPrototype) - { - $this->statementPrototype = $statementPrototype; - $this->statementPrototype->setDriver($this); - } - - /** - * Register result prototype - * - * @param Result $resultPrototype - */ - public function registerResultPrototype(Result $resultPrototype) - { - $this->resultPrototype = $resultPrototype; - } - - /** - * Add feature - * - * @param string $name - * @param AbstractFeature $feature - * @return Pdo - */ - public function addFeature($name, $feature) - { - if ($feature instanceof AbstractFeature) { - $name = $feature->getName(); // overwrite the name, just in case - $feature->setDriver($this); - } - $this->features[$name] = $feature; - return $this; - } - - /** - * Setup the default features for Pdo - * - * @return Pdo - */ - public function setupDefaultFeatures() - { - $driverName = $this->connection->getDriverName(); - if ($driverName == 'sqlite') { - $this->addFeature(null, new Feature\SqliteRowCounter); - } elseif ($driverName == 'oci') { - $this->addFeature(null, new Feature\OracleRowCounter); - } - return $this; - } - - /** - * Get feature - * - * @param $name - * @return AbstractFeature|false - */ - public function getFeature($name) - { - if (isset($this->features[$name])) { - return $this->features[$name]; - } - return false; - } - - /** - * Get database platform name - * - * @param string $nameFormat - * @return string - */ - public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE) - { - $name = $this->getConnection()->getDriverName(); - if ($nameFormat == self::NAME_FORMAT_CAMELCASE) { - switch ($name) { - case 'pgsql': - return 'Postgresql'; - case 'oci': - return 'Oracle'; - case 'dblib': - case 'sqlsrv': - return 'SqlServer'; - default: - return ucfirst($name); - } - } else { - switch ($name) { - case 'sqlite': - return 'SQLite'; - case 'mysql': - return 'MySQL'; - case 'pgsql': - return 'PostgreSQL'; - case 'oci': - return 'Oracle'; - case 'dblib': - case 'sqlsrv': - return 'SQLServer'; - default: - return ucfirst($name); - } - } - } - - /** - * Check environment - */ - public function checkEnvironment() - { - if (!extension_loaded('PDO')) { - throw new Exception\RuntimeException('The PDO extension is required for this adapter but the extension is not loaded'); - } - } - - /** - * @return Connection - */ - public function getConnection() - { - return $this->connection; - } - - /** - * @param string|PDOStatement $sqlOrResource - * @return Statement - */ - public function createStatement($sqlOrResource = null) - { - $statement = clone $this->statementPrototype; - if ($sqlOrResource instanceof PDOStatement) { - $statement->setResource($sqlOrResource); - } else { - if (is_string($sqlOrResource)) { - $statement->setSql($sqlOrResource); - } - if (!$this->connection->isConnected()) { - $this->connection->connect(); - } - $statement->initialize($this->connection->getResource()); - } - return $statement; - } - - /** - * @param resource $resource - * @param mixed $context - * @return Result - */ - public function createResult($resource, $context = null) - { - $result = clone $this->resultPrototype; - $rowCount = null; - - // special feature, sqlite PDO counter - if ($this->connection->getDriverName() == 'sqlite' - && ($sqliteRowCounter = $this->getFeature('SqliteRowCounter')) - && $resource->columnCount() > 0) { - $rowCount = $sqliteRowCounter->getRowCountClosure($context); - } - - // special feature, oracle PDO counter - if ($this->connection->getDriverName() == 'oci' - && ($oracleRowCounter = $this->getFeature('OracleRowCounter')) - && $resource->columnCount() > 0) { - $rowCount = $oracleRowCounter->getRowCountClosure($context); - } - - - $result->initialize($resource, $this->connection->getLastGeneratedValue(), $rowCount); - return $result; - } - - /** - * @return array - */ - public function getPrepareType() - { - return self::PARAMETERIZATION_NAMED; - } - - /** - * @param string $name - * @param string|null $type - * @return string - */ - public function formatParameterName($name, $type = null) - { - if ($type == null && !is_numeric($name) || $type == self::PARAMETERIZATION_NAMED) { - return ':' . $name; - } - - return '?'; - } - - /** - * @return mixed - */ - public function getLastGeneratedValue($name = null) - { - return $this->connection->getLastGeneratedValue($name); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Result.php b/library/Zend/Db/Adapter/Driver/Pdo/Result.php deleted file mode 100755 index 9323282d6..000000000 --- a/library/Zend/Db/Adapter/Driver/Pdo/Result.php +++ /dev/null @@ -1,226 +0,0 @@ -resource = $resource; - $this->generatedValue = $generatedValue; - $this->rowCount = $rowCount; - - return $this; - } - - /** - * @return null - */ - public function buffer() - { - return null; - } - - /** - * @return bool|null - */ - public function isBuffered() - { - return false; - } - - /** - * Get resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Get the data - * @return array - */ - public function current() - { - if ($this->currentComplete) { - return $this->currentData; - } - - $this->currentData = $this->resource->fetch(\PDO::FETCH_ASSOC); - $this->currentComplete = true; - return $this->currentData; - } - - /** - * Next - * - * @return mixed - */ - public function next() - { - $this->currentData = $this->resource->fetch(\PDO::FETCH_ASSOC); - $this->currentComplete = true; - $this->position++; - return $this->currentData; - } - - /** - * Key - * - * @return mixed - */ - public function key() - { - return $this->position; - } - - /** - * @throws Exception\RuntimeException - * @return void - */ - public function rewind() - { - if ($this->statementMode == self::STATEMENT_MODE_FORWARD && $this->position > 0) { - throw new Exception\RuntimeException( - 'This result is a forward only result set, calling rewind() after moving forward is not supported' - ); - } - $this->currentData = $this->resource->fetch(\PDO::FETCH_ASSOC); - $this->currentComplete = true; - $this->position = 0; - } - - /** - * Valid - * - * @return bool - */ - public function valid() - { - return ($this->currentData !== false); - } - - /** - * Count - * - * @return int - */ - public function count() - { - if (is_int($this->rowCount)) { - return $this->rowCount; - } - if ($this->rowCount instanceof \Closure) { - $this->rowCount = (int) call_user_func($this->rowCount); - } else { - $this->rowCount = (int) $this->resource->rowCount(); - } - return $this->rowCount; - } - - /** - * @return int - */ - public function getFieldCount() - { - return $this->resource->columnCount(); - } - - /** - * Is query result - * - * @return bool - */ - public function isQueryResult() - { - return ($this->resource->columnCount() > 0); - } - - /** - * Get affected rows - * - * @return int - */ - public function getAffectedRows() - { - return $this->resource->rowCount(); - } - - /** - * @return mixed|null - */ - public function getGeneratedValue() - { - return $this->generatedValue; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pdo/Statement.php b/library/Zend/Db/Adapter/Driver/Pdo/Statement.php deleted file mode 100755 index 891bec9d7..000000000 --- a/library/Zend/Db/Adapter/Driver/Pdo/Statement.php +++ /dev/null @@ -1,310 +0,0 @@ -driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Statement - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Initialize - * - * @param \PDO $connectionResource - * @return Statement - */ - public function initialize(\PDO $connectionResource) - { - $this->pdo = $connectionResource; - return $this; - } - - /** - * Set resource - * - * @param \PDOStatement $pdoStatement - * @return Statement - */ - public function setResource(\PDOStatement $pdoStatement) - { - $this->resource = $pdoStatement; - return $this; - } - - /** - * Get resource - * - * @return mixed - */ - public function getResource() - { - return $this->resource; - } - - /** - * Set sql - * - * @param string $sql - * @return Statement - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * Get sql - * - * @return string - */ - public function getSql() - { - return $this->sql; - } - - /** - * @param ParameterContainer $parameterContainer - * @return Statement - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * @return ParameterContainer - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } - - /** - * @param string $sql - * @throws Exception\RuntimeException - */ - public function prepare($sql = null) - { - if ($this->isPrepared) { - throw new Exception\RuntimeException('This statement has been prepared already'); - } - - if ($sql == null) { - $sql = $this->sql; - } - - $this->resource = $this->pdo->prepare($sql); - - if ($this->resource === false) { - $error = $this->pdo->errorInfo(); - throw new Exception\RuntimeException($error[2]); - } - - $this->isPrepared = true; - } - - /** - * @return bool - */ - public function isPrepared() - { - return $this->isPrepared; - } - - /** - * @param mixed $parameters - * @throws Exception\InvalidQueryException - * @return Result - */ - public function execute($parameters = null) - { - if (!$this->isPrepared) { - $this->prepare(); - } - - /** START Standard ParameterContainer Merging Block */ - if (!$this->parameterContainer instanceof ParameterContainer) { - if ($parameters instanceof ParameterContainer) { - $this->parameterContainer = $parameters; - $parameters = null; - } else { - $this->parameterContainer = new ParameterContainer(); - } - } - - if (is_array($parameters)) { - $this->parameterContainer->setFromArray($parameters); - } - - if ($this->parameterContainer->count() > 0) { - $this->bindParametersFromContainer(); - } - /** END Standard ParameterContainer Merging Block */ - - if ($this->profiler) { - $this->profiler->profilerStart($this); - } - - try { - $this->resource->execute(); - } catch (\PDOException $e) { - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - throw new Exception\InvalidQueryException( - 'Statement could not be executed (' . implode(' - ', $this->resource->errorInfo()) . ')', - null, - $e - ); - } - - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - - $result = $this->driver->createResult($this->resource, $this); - return $result; - } - - /** - * Bind parameters from container - */ - protected function bindParametersFromContainer() - { - if ($this->parametersBound) { - return; - } - - $parameters = $this->parameterContainer->getNamedArray(); - foreach ($parameters as $name => &$value) { - if (is_bool($value)) { - $type = \PDO::PARAM_BOOL; - } elseif (is_int($value)) { - $type = \PDO::PARAM_INT; - } else { - $type = \PDO::PARAM_STR; - } - if ($this->parameterContainer->offsetHasErrata($name)) { - switch ($this->parameterContainer->offsetGetErrata($name)) { - case ParameterContainer::TYPE_INTEGER: - $type = \PDO::PARAM_INT; - break; - case ParameterContainer::TYPE_NULL: - $type = \PDO::PARAM_NULL; - break; - case ParameterContainer::TYPE_LOB: - $type = \PDO::PARAM_LOB; - break; - } - } - - // parameter is named or positional, value is reference - $parameter = is_int($name) ? ($name + 1) : $name; - $this->resource->bindParam($parameter, $value, $type); - } - } - - /** - * Perform a deep clone - * @return Statement A cloned statement - */ - public function __clone() - { - $this->isPrepared = false; - $this->parametersBound = false; - $this->resource = null; - if ($this->parameterContainer) { - $this->parameterContainer = clone $this->parameterContainer; - } - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php b/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php deleted file mode 100755 index fa91289a4..000000000 --- a/library/Zend/Db/Adapter/Driver/Pgsql/Connection.php +++ /dev/null @@ -1,311 +0,0 @@ -setConnectionParameters($connectionInfo); - } elseif (is_resource($connectionInfo)) { - $this->setResource($connectionInfo); - } - } - - /** - * Set connection parameters - * - * @param array $connectionParameters - * @return Connection - */ - public function setConnectionParameters(array $connectionParameters) - { - $this->connectionParameters = $connectionParameters; - return $this; - } - - /** - * Set driver - * - * @param Pgsql $driver - * @return Connection - */ - public function setDriver(Pgsql $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Connection - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Set resource - * - * @param resource $resource - * @return Connection - */ - public function setResource($resource) - { - $this->resource = $resource; - return; - } - - /** - * Get current schema - * - * @return null|string - */ - public function getCurrentSchema() - { - if (!$this->isConnected()) { - $this->connect(); - } - - $result = pg_query($this->resource, 'SELECT CURRENT_SCHEMA AS "currentschema"'); - if ($result == false) { - return null; - } - return pg_fetch_result($result, 0, 'currentschema'); - } - - /** - * Get resource - * - * @return resource - */ - public function getResource() - { - if (!$this->isConnected()) { - $this->connect(); - } - return $this->resource; - } - - /** - * Connect to the database - * - * @return Connection - * @throws Exception\RuntimeException on failure - */ - public function connect() - { - if (is_resource($this->resource)) { - return $this; - } - - // localize - $p = $this->connectionParameters; - - // given a list of key names, test for existence in $p - $findParameterValue = function (array $names) use ($p) { - foreach ($names as $name) { - if (isset($p[$name])) { - return $p[$name]; - } - } - return null; - }; - - $connection = array(); - $connection['host'] = $findParameterValue(array('hostname', 'host')); - $connection['user'] = $findParameterValue(array('username', 'user')); - $connection['password'] = $findParameterValue(array('password', 'passwd', 'pw')); - $connection['dbname'] = $findParameterValue(array('database', 'dbname', 'db', 'schema')); - $connection['port'] = (isset($p['port'])) ? (int) $p['port'] : null; - $connection['socket'] = (isset($p['socket'])) ? $p['socket'] : null; - - $connection = array_filter($connection); // remove nulls - $connection = http_build_query($connection, null, ' '); // @link http://php.net/pg_connect - - set_error_handler(function ($number, $string) { - throw new Exception\RuntimeException( - __METHOD__ . ': Unable to connect to database', null, new Exception\ErrorException($string, $number) - ); - }); - $this->resource = pg_connect($connection); - restore_error_handler(); - - if ($this->resource === false) { - throw new Exception\RuntimeException(sprintf( - '%s: Unable to connect to database', - __METHOD__ - )); - } - - return $this; - } - - /** - * @return bool - */ - public function isConnected() - { - return (is_resource($this->resource)); - } - - /** - * @return void - */ - public function disconnect() - { - pg_close($this->resource); - } - - /** - * @return void - */ - public function beginTransaction() - { - if ($this->inTransaction) { - throw new Exception\RuntimeException('Nested transactions are not supported'); - } - - if (!$this->isConnected()) { - $this->connect(); - } - - pg_query($this->resource, 'BEGIN'); - $this->inTransaction = true; - } - - /** - * In transaction - * - * @return bool - */ - public function inTransaction() - { - return $this->inTransaction; - } - - /** - * @return void - */ - public function commit() - { - if (!$this->inTransaction) { - return; // We ignore attempts to commit non-existing transaction - } - - pg_query($this->resource, 'COMMIT'); - $this->inTransaction = false; - } - - /** - * @return void - */ - public function rollback() - { - if (!$this->inTransaction) { - return; - } - - pg_query($this->resource, 'ROLLBACK'); - $this->inTransaction = false; - } - - /** - * @param string $sql - * @throws Exception\InvalidQueryException - * @return resource|\Zend\Db\ResultSet\ResultSetInterface - */ - public function execute($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - if ($this->profiler) { - $this->profiler->profilerStart($sql); - } - - $resultResource = pg_query($this->resource, $sql); - - if ($this->profiler) { - $this->profiler->profilerFinish($sql); - } - - // if the returnValue is something other than a pg result resource, bypass wrapping it - if ($resultResource === false) { - throw new Exception\InvalidQueryException(pg_errormessage()); - } - - $resultPrototype = $this->driver->createResult(($resultResource === true) ? $this->resource : $resultResource); - return $resultPrototype; - } - - /** - * @param null $name Ignored - * @return string - */ - public function getLastGeneratedValue($name = null) - { - if ($name == null) { - return null; - } - $result = pg_query($this->resource, 'SELECT CURRVAL(\'' . str_replace('\'', '\\\'', $name) . '\') as "currval"'); - return pg_fetch_result($result, 0, 'currval'); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pgsql/Pgsql.php b/library/Zend/Db/Adapter/Driver/Pgsql/Pgsql.php deleted file mode 100755 index 36e5e0f29..000000000 --- a/library/Zend/Db/Adapter/Driver/Pgsql/Pgsql.php +++ /dev/null @@ -1,227 +0,0 @@ - false - ); - - /** - * Constructor - * - * @param array|Connection|resource $connection - * @param null|Statement $statementPrototype - * @param null|Result $resultPrototype - * @param array $options - */ - public function __construct($connection, Statement $statementPrototype = null, Result $resultPrototype = null, $options = null) - { - if (!$connection instanceof Connection) { - $connection = new Connection($connection); - } - - $this->registerConnection($connection); - $this->registerStatementPrototype(($statementPrototype) ?: new Statement()); - $this->registerResultPrototype(($resultPrototype) ?: new Result()); - } - - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->connection instanceof Profiler\ProfilerAwareInterface) { - $this->connection->setProfiler($profiler); - } - if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) { - $this->statementPrototype->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Register connection - * - * @param Connection $connection - * @return Pgsql - */ - public function registerConnection(Connection $connection) - { - $this->connection = $connection; - $this->connection->setDriver($this); - return $this; - } - - /** - * Register statement prototype - * - * @param Statement $statement - * @return Pgsql - */ - public function registerStatementPrototype(Statement $statement) - { - $this->statementPrototype = $statement; - $this->statementPrototype->setDriver($this); // needs access to driver to createResult() - return $this; - } - - /** - * Register result prototype - * - * @param Result $result - * @return Pgsql - */ - public function registerResultPrototype(Result $result) - { - $this->resultPrototype = $result; - return $this; - } - - /** - * Get database platform name - * - * @param string $nameFormat - * @return string - */ - public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE) - { - if ($nameFormat == self::NAME_FORMAT_CAMELCASE) { - return 'Postgresql'; - } - - return 'PostgreSQL'; - } - - /** - * Check environment - * - * @throws Exception\RuntimeException - * @return bool - */ - public function checkEnvironment() - { - if (!extension_loaded('pgsql')) { - throw new Exception\RuntimeException('The PostgreSQL (pgsql) extension is required for this adapter but the extension is not loaded'); - } - } - - /** - * Get connection - * - * @return Connection - */ - public function getConnection() - { - return $this->connection; - } - - /** - * Create statement - * - * @param string|null $sqlOrResource - * @return Statement - */ - public function createStatement($sqlOrResource = null) - { - $statement = clone $this->statementPrototype; - - if (is_string($sqlOrResource)) { - $statement->setSql($sqlOrResource); - } - - if (!$this->connection->isConnected()) { - $this->connection->connect(); - } - - $statement->initialize($this->connection->getResource()); - return $statement; - } - - /** - * Create result - * - * @param resource $resource - * @return Result - */ - public function createResult($resource) - { - $result = clone $this->resultPrototype; - $result->initialize($resource, $this->connection->getLastGeneratedValue()); - return $result; - } - - /** - * Get prepare Type - * - * @return array - */ - public function getPrepareType() - { - return self::PARAMETERIZATION_POSITIONAL; - } - - /** - * Format parameter name - * - * @param string $name - * @param mixed $type - * @return string - */ - public function formatParameterName($name, $type = null) - { - return '$#'; - } - - /** - * Get last generated value - * - * @param string $name - * @return mixed - */ - public function getLastGeneratedValue($name = null) - { - return $this->connection->getLastGeneratedValue($name); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pgsql/Result.php b/library/Zend/Db/Adapter/Driver/Pgsql/Result.php deleted file mode 100755 index 6c2410dae..000000000 --- a/library/Zend/Db/Adapter/Driver/Pgsql/Result.php +++ /dev/null @@ -1,192 +0,0 @@ -resource = $resource; - $this->count = pg_num_rows($this->resource); - $this->generatedValue = $generatedValue; - } - - /** - * Current - * - * @return array|bool|mixed - */ - public function current() - { - if ($this->count === 0) { - return false; - } - return pg_fetch_assoc($this->resource, $this->position); - } - - /** - * Next - * - * @return void - */ - public function next() - { - $this->position++; - } - - /** - * Key - * - * @return int|mixed - */ - public function key() - { - return $this->position; - } - - /** - * Valid - * - * @return bool - */ - public function valid() - { - return ($this->position < $this->count); - } - - /** - * Rewind - * - * @return void - */ - public function rewind() - { - $this->position = 0; - } - - /** - * Buffer - * - * @return null - */ - public function buffer() - { - return null; - } - - /** - * Is buffered - * - * @return false - */ - public function isBuffered() - { - return false; - } - - /** - * Is query result - * - * @return bool - */ - public function isQueryResult() - { - return (pg_num_fields($this->resource) > 0); - } - - /** - * Get affected rows - * - * @return int - */ - public function getAffectedRows() - { - return pg_affected_rows($this->resource); - } - - /** - * Get generated value - * - * @return mixed|null - */ - public function getGeneratedValue() - { - return $this->generatedValue; - } - - /** - * Get resource - */ - public function getResource() - { - // TODO: Implement getResource() method. - } - - /** - * Count - * - * (PHP 5 >= 5.1.0)
        - * Count elements of an object - * @link http://php.net/manual/en/countable.count.php - * @return int The custom count as an integer. - *

        - *

        - * The return value is cast to an integer. - */ - public function count() - { - return $this->count; - } - - /** - * Get field count - * - * @return int - */ - public function getFieldCount() - { - return pg_num_fields($this->resource); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Pgsql/Statement.php b/library/Zend/Db/Adapter/Driver/Pgsql/Statement.php deleted file mode 100755 index c105a6647..000000000 --- a/library/Zend/Db/Adapter/Driver/Pgsql/Statement.php +++ /dev/null @@ -1,241 +0,0 @@ -driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Statement - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Initialize - * - * @param resource $pgsql - * @return void - * @throws Exception\RuntimeException for invalid or missing postgresql connection - */ - public function initialize($pgsql) - { - if (!is_resource($pgsql) || get_resource_type($pgsql) !== 'pgsql link') { - throw new Exception\RuntimeException(sprintf( - '%s: Invalid or missing postgresql connection; received "%s"', - __METHOD__, - get_resource_type($pgsql) - )); - } - $this->pgsql = $pgsql; - } - - /** - * Get resource - * - * @return resource - */ - public function getResource() - { - // TODO: Implement getResource() method. - } - - /** - * Set sql - * - * @param string $sql - * @return Statement - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * Get sql - * - * @return string - */ - public function getSql() - { - return $this->sql; - } - - /** - * Set parameter container - * - * @param ParameterContainer $parameterContainer - * @return Statement - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * Get parameter container - * - * @return ParameterContainer - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } - - /** - * Prepare - * - * @param string $sql - */ - public function prepare($sql = null) - { - $sql = ($sql) ?: $this->sql; - - $pCount = 1; - $sql = preg_replace_callback( - '#\$\##', function ($foo) use (&$pCount) { - return '$' . $pCount++; - }, - $sql - ); - - $this->sql = $sql; - $this->statementName = 'statement' . ++static::$statementIndex; - $this->resource = pg_prepare($this->pgsql, $this->statementName, $sql); - } - - /** - * Is prepared - * - * @return bool - */ - public function isPrepared() - { - return isset($this->resource); - } - - /** - * Execute - * - * @param ParameterContainer|null $parameters - * @throws Exception\InvalidQueryException - * @return Result - */ - public function execute($parameters = null) - { - if (!$this->isPrepared()) { - $this->prepare(); - } - - /** START Standard ParameterContainer Merging Block */ - if (!$this->parameterContainer instanceof ParameterContainer) { - if ($parameters instanceof ParameterContainer) { - $this->parameterContainer = $parameters; - $parameters = null; - } else { - $this->parameterContainer = new ParameterContainer(); - } - } - - if (is_array($parameters)) { - $this->parameterContainer->setFromArray($parameters); - } - - if ($this->parameterContainer->count() > 0) { - $parameters = $this->parameterContainer->getPositionalArray(); - } - /** END Standard ParameterContainer Merging Block */ - - if ($this->profiler) { - $this->profiler->profilerStart($this); - } - - $resultResource = pg_execute($this->pgsql, $this->statementName, (array) $parameters); - - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - - if ($resultResource === false) { - throw new Exception\InvalidQueryException(pg_last_error()); - } - - $result = $this->driver->createResult($resultResource); - return $result; - } -} diff --git a/library/Zend/Db/Adapter/Driver/ResultInterface.php b/library/Zend/Db/Adapter/Driver/ResultInterface.php deleted file mode 100755 index cb1f40784..000000000 --- a/library/Zend/Db/Adapter/Driver/ResultInterface.php +++ /dev/null @@ -1,67 +0,0 @@ -setConnectionParameters($connectionInfo); - } elseif (is_resource($connectionInfo)) { - $this->setResource($connectionInfo); - } else { - throw new Exception\InvalidArgumentException('$connection must be an array of parameters or a resource'); - } - } - - /** - * Set driver - * - * @param Sqlsrv $driver - * @return Connection - */ - public function setDriver(Sqlsrv $driver) - { - $this->driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Connection - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Set connection parameters - * - * @param array $connectionParameters - * @return Connection - */ - public function setConnectionParameters(array $connectionParameters) - { - $this->connectionParameters = $connectionParameters; - return $this; - } - - /** - * Get connection parameters - * - * @return array - */ - public function getConnectionParameters() - { - return $this->connectionParameters; - } - - /** - * Get current schema - * - * @return string - */ - public function getCurrentSchema() - { - if (!$this->isConnected()) { - $this->connect(); - } - - $result = sqlsrv_query($this->resource, 'SELECT SCHEMA_NAME()'); - $r = sqlsrv_fetch_array($result); - return $r[0]; - } - - /** - * Set resource - * - * @param resource $resource - * @throws Exception\InvalidArgumentException - * @return Connection - */ - public function setResource($resource) - { - if (get_resource_type($resource) !== 'SQL Server Connection') { - throw new Exception\InvalidArgumentException('Resource provided was not of type SQL Server Connection'); - } - $this->resource = $resource; - return $this; - } - - /** - * @return resource - */ - public function getResource() - { - if (!$this->isConnected()) { - $this->connect(); - } - return $this->resource; - } - - /** - * Connect - * - * @throws Exception\RuntimeException - * @return Connection - */ - public function connect() - { - if ($this->resource) { - return $this; - } - - $serverName = '.'; - $params = array( - 'ReturnDatesAsStrings' => true - ); - foreach ($this->connectionParameters as $key => $value) { - switch (strtolower($key)) { - case 'hostname': - case 'servername': - $serverName = (string) $value; - break; - case 'username': - case 'uid': - $params['UID'] = (string) $value; - break; - case 'password': - case 'pwd': - $params['PWD'] = (string) $value; - break; - case 'database': - case 'dbname': - $params['Database'] = (string) $value; - break; - case 'charset': - $params['CharacterSet'] = (string) $value; - break; - case 'driver_options': - case 'options': - $params = array_merge($params, (array) $value); - break; - - } - } - - $this->resource = sqlsrv_connect($serverName, $params); - - if (!$this->resource) { - throw new Exception\RuntimeException( - 'Connect Error', - null, - new ErrorException(sqlsrv_errors()) - ); - } - - return $this; - } - - /** - * Is connected - * @return bool - */ - public function isConnected() - { - return (is_resource($this->resource)); - } - - /** - * Disconnect - */ - public function disconnect() - { - sqlsrv_close($this->resource); - $this->resource = null; - } - - /** - * Begin transaction - */ - public function beginTransaction() - { - if (!$this->resource) { - $this->connect(); - } - if (sqlsrv_begin_transaction($this->resource) === false) { - throw new Exception\RuntimeException( - 'Begin transaction failed', - null, - new ErrorException(sqlsrv_errors()) - ); - } - - $this->inTransaction = true; - } - - /** - * In transaction - * - * @return bool - */ - public function inTransaction() - { - return $this->inTransaction; - } - - /** - * Commit - */ - public function commit() - { - // http://msdn.microsoft.com/en-us/library/cc296194.aspx - - if (!$this->resource) { - $this->connect(); - } - - $this->inTransaction = false; - - return sqlsrv_commit($this->resource); - } - - /** - * Rollback - */ - public function rollback() - { - // http://msdn.microsoft.com/en-us/library/cc296176.aspx - - if (!$this->resource) { - throw new Exception\RuntimeException('Must be connected before you can rollback.'); - } - - return sqlsrv_rollback($this->resource); - } - - /** - * Execute - * - * @param string $sql - * @throws Exception\RuntimeException - * @return mixed - */ - public function execute($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - if (!$this->driver instanceof Sqlsrv) { - throw new Exception\RuntimeException('Connection is missing an instance of Sqlsrv'); - } - - if ($this->profiler) { - $this->profiler->profilerStart($sql); - } - - $returnValue = sqlsrv_query($this->resource, $sql); - - if ($this->profiler) { - $this->profiler->profilerFinish($sql); - } - - // if the returnValue is something other than a Sqlsrv_result, bypass wrapping it - if ($returnValue === false) { - $errors = sqlsrv_errors(); - // ignore general warnings - if ($errors[0]['SQLSTATE'] != '01000') { - throw new Exception\RuntimeException( - 'An exception occurred while trying to execute the provided $sql', - null, - new ErrorException($errors) - ); - } - } - - $result = $this->driver->createResult($returnValue); - return $result; - } - - /** - * Prepare - * - * @param string $sql - * @return string - */ - public function prepare($sql) - { - if (!$this->isConnected()) { - $this->connect(); - } - - $statement = $this->driver->createStatement($sql); - return $statement; - } - - /** - * Get last generated id - * - * @param string $name - * @return mixed - */ - public function getLastGeneratedValue($name = null) - { - if (!$this->resource) { - $this->connect(); - } - $sql = 'SELECT @@IDENTITY as Current_Identity'; - $result = sqlsrv_query($this->resource, $sql); - $row = sqlsrv_fetch_array($result); - return $row['Current_Identity']; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Sqlsrv/Exception/ErrorException.php b/library/Zend/Db/Adapter/Driver/Sqlsrv/Exception/ErrorException.php deleted file mode 100755 index 9976eee63..000000000 --- a/library/Zend/Db/Adapter/Driver/Sqlsrv/Exception/ErrorException.php +++ /dev/null @@ -1,32 +0,0 @@ -errors = ($errors === false) ? sqlsrv_errors() : $errors; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Sqlsrv/Exception/ExceptionInterface.php b/library/Zend/Db/Adapter/Driver/Sqlsrv/Exception/ExceptionInterface.php deleted file mode 100755 index a7168e8d6..000000000 --- a/library/Zend/Db/Adapter/Driver/Sqlsrv/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -resource = $resource; - $this->generatedValue = $generatedValue; - return $this; - } - - /** - * @return null - */ - public function buffer() - { - return null; - } - - /** - * @return bool - */ - public function isBuffered() - { - return false; - } - - /** - * Get resource - * - * @return resource - */ - public function getResource() - { - return $this->resource; - } - - /** - * Current - * - * @return mixed - */ - public function current() - { - if ($this->currentComplete) { - return $this->currentData; - } - - $this->load(); - return $this->currentData; - } - - /** - * Next - * - * @return bool - */ - public function next() - { - $this->load(); - return true; - } - - /** - * Load - * - * @param int $row - * @return mixed - */ - protected function load($row = SQLSRV_SCROLL_NEXT) - { - $this->currentData = sqlsrv_fetch_array($this->resource, SQLSRV_FETCH_ASSOC, $row); - $this->currentComplete = true; - $this->position++; - return $this->currentData; - } - - /** - * Key - * - * @return mixed - */ - public function key() - { - return $this->position; - } - - /** - * Rewind - * - * @return bool - */ - public function rewind() - { - $this->position = 0; - $this->load(SQLSRV_SCROLL_FIRST); - return true; - } - - /** - * Valid - * - * @return bool - */ - public function valid() - { - if ($this->currentComplete && $this->currentData) { - return true; - } - - return $this->load(); - } - - /** - * Count - * - * @return int - */ - public function count() - { - return sqlsrv_num_rows($this->resource); - } - - /** - * @return bool|int - */ - public function getFieldCount() - { - return sqlsrv_num_fields($this->resource); - } - - /** - * Is query result - * - * @return bool - */ - public function isQueryResult() - { - if (is_bool($this->resource)) { - return false; - } - return (sqlsrv_num_fields($this->resource) > 0); - } - - /** - * Get affected rows - * - * @return int - */ - public function getAffectedRows() - { - return sqlsrv_rows_affected($this->resource); - } - - /** - * @return mixed|null - */ - public function getGeneratedValue() - { - return $this->generatedValue; - } -} diff --git a/library/Zend/Db/Adapter/Driver/Sqlsrv/Sqlsrv.php b/library/Zend/Db/Adapter/Driver/Sqlsrv/Sqlsrv.php deleted file mode 100755 index 0cb8b2435..000000000 --- a/library/Zend/Db/Adapter/Driver/Sqlsrv/Sqlsrv.php +++ /dev/null @@ -1,211 +0,0 @@ -registerConnection($connection); - $this->registerStatementPrototype(($statementPrototype) ?: new Statement()); - $this->registerResultPrototype(($resultPrototype) ?: new Result()); - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Sqlsrv - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - if ($this->connection instanceof Profiler\ProfilerAwareInterface) { - $this->connection->setProfiler($profiler); - } - if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) { - $this->statementPrototype->setProfiler($profiler); - } - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * Register connection - * - * @param Connection $connection - * @return Sqlsrv - */ - public function registerConnection(Connection $connection) - { - $this->connection = $connection; - $this->connection->setDriver($this); - return $this; - } - - /** - * Register statement prototype - * - * @param Statement $statementPrototype - * @return Sqlsrv - */ - public function registerStatementPrototype(Statement $statementPrototype) - { - $this->statementPrototype = $statementPrototype; - $this->statementPrototype->setDriver($this); - return $this; - } - - /** - * Register result prototype - * - * @param Result $resultPrototype - * @return Sqlsrv - */ - public function registerResultPrototype(Result $resultPrototype) - { - $this->resultPrototype = $resultPrototype; - return $this; - } - - /** - * Get database paltform name - * - * @param string $nameFormat - * @return string - */ - public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE) - { - if ($nameFormat == self::NAME_FORMAT_CAMELCASE) { - return 'SqlServer'; - } - - return 'SQLServer'; - } - - /** - * Check environment - * - * @throws Exception\RuntimeException - * @return void - */ - public function checkEnvironment() - { - if (!extension_loaded('sqlsrv')) { - throw new Exception\RuntimeException('The Sqlsrv extension is required for this adapter but the extension is not loaded'); - } - } - - /** - * @return Connection - */ - public function getConnection() - { - return $this->connection; - } - - /** - * @param string|resource $sqlOrResource - * @return Statement - */ - public function createStatement($sqlOrResource = null) - { - $statement = clone $this->statementPrototype; - if (is_resource($sqlOrResource)) { - $statement->initialize($sqlOrResource); - } else { - if (!$this->connection->isConnected()) { - $this->connection->connect(); - } - $statement->initialize($this->connection->getResource()); - if (is_string($sqlOrResource)) { - $statement->setSql($sqlOrResource); - } elseif ($sqlOrResource != null) { - throw new Exception\InvalidArgumentException('createStatement() only accepts an SQL string or a Sqlsrv resource'); - } - } - return $statement; - } - - /** - * @param resource $resource - * @return Result - */ - public function createResult($resource) - { - $result = clone $this->resultPrototype; - $result->initialize($resource, $this->connection->getLastGeneratedValue()); - return $result; - } - - /** - * @return array - */ - public function getPrepareType() - { - return self::PARAMETERIZATION_POSITIONAL; - } - - /** - * @param string $name - * @param mixed $type - * @return string - */ - public function formatParameterName($name, $type = null) - { - return '?'; - } - - /** - * @return mixed - */ - public function getLastGeneratedValue() - { - return $this->getConnection()->getLastGeneratedValue(); - } -} diff --git a/library/Zend/Db/Adapter/Driver/Sqlsrv/Statement.php b/library/Zend/Db/Adapter/Driver/Sqlsrv/Statement.php deleted file mode 100755 index 4aefa9ff9..000000000 --- a/library/Zend/Db/Adapter/Driver/Sqlsrv/Statement.php +++ /dev/null @@ -1,313 +0,0 @@ -driver = $driver; - return $this; - } - - /** - * @param Profiler\ProfilerInterface $profiler - * @return Statement - */ - public function setProfiler(Profiler\ProfilerInterface $profiler) - { - $this->profiler = $profiler; - return $this; - } - - /** - * @return null|Profiler\ProfilerInterface - */ - public function getProfiler() - { - return $this->profiler; - } - - /** - * - * One of two resource types will be provided here: - * a) "SQL Server Connection" when a prepared statement needs to still be produced - * b) "SQL Server Statement" when a prepared statement has been already produced - * (there will need to already be a bound param set if it applies to this query) - * - * @param resource $resource - * @throws Exception\InvalidArgumentException - * @return Statement - */ - public function initialize($resource) - { - $resourceType = get_resource_type($resource); - - if ($resourceType == 'SQL Server Connection') { - $this->sqlsrv = $resource; - } elseif ($resourceType == 'SQL Server Statement') { - $this->resource = $resource; - $this->isPrepared = true; - } else { - throw new Exception\InvalidArgumentException('Invalid resource provided to ' . __CLASS__); - } - - return $this; - } - - /** - * Set parameter container - * - * @param ParameterContainer $parameterContainer - * @return Statement - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * @return ParameterContainer - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } - - /** - * @param $resource - * @return Statement - */ - public function setResource($resource) - { - $this->resource = $resource; - return $this; - } - - /** - * Get resource - * - * @return resource - */ - public function getResource() - { - return $this->resource; - } - - /** - * @param string $sql - * @return Statement - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * Get sql - * - * @return string - */ - public function getSql() - { - return $this->sql; - } - - /** - * @param string $sql - * @param array $options - * @throws Exception\RuntimeException - * @return Statement - */ - public function prepare($sql = null, array $options = array()) - { - if ($this->isPrepared) { - throw new Exception\RuntimeException('Already prepared'); - } - $sql = ($sql) ?: $this->sql; - $options = ($options) ?: $this->prepareOptions; - - $pRef = &$this->parameterReferences; - for ($position = 0, $count = substr_count($sql, '?'); $position < $count; $position++) { - if (!isset($this->prepareParams[$position])) { - $pRef[$position] = array('', SQLSRV_PARAM_IN, null, null); - } else { - $pRef[$position] = &$this->prepareParams[$position]; - } - } - - $this->resource = sqlsrv_prepare($this->sqlsrv, $sql, $pRef, $options); - - $this->isPrepared = true; - - return $this; - } - - /** - * @return bool - */ - public function isPrepared() - { - return $this->isPrepared; - } - - /** - * Execute - * - * @param array|ParameterContainer $parameters - * @throws Exception\RuntimeException - * @return Result - */ - public function execute($parameters = null) - { - /** END Standard ParameterContainer Merging Block */ - if (!$this->isPrepared) { - $this->prepare(); - } - - /** START Standard ParameterContainer Merging Block */ - if (!$this->parameterContainer instanceof ParameterContainer) { - if ($parameters instanceof ParameterContainer) { - $this->parameterContainer = $parameters; - $parameters = null; - } else { - $this->parameterContainer = new ParameterContainer(); - } - } - - if (is_array($parameters)) { - $this->parameterContainer->setFromArray($parameters); - } - - if ($this->parameterContainer->count() > 0) { - $this->bindParametersFromContainer(); - } - - if ($this->profiler) { - $this->profiler->profilerStart($this); - } - - $resultValue = sqlsrv_execute($this->resource); - - if ($this->profiler) { - $this->profiler->profilerFinish(); - } - - if ($resultValue === false) { - $errors = sqlsrv_errors(); - // ignore general warnings - if ($errors[0]['SQLSTATE'] != '01000') { - throw new Exception\RuntimeException($errors[0]['message']); - } - } - - $result = $this->driver->createResult($this->resource); - return $result; - } - - /** - * Bind parameters from container - * - */ - protected function bindParametersFromContainer() - { - $values = $this->parameterContainer->getPositionalArray(); - $position = 0; - foreach ($values as $value) { - $this->parameterReferences[$position++][0] = $value; - } - } - - /** - * @param array $prepareParams - */ - public function setPrepareParams(array $prepareParams) - { - $this->prepareParams = $prepareParams; - } - - /** - * @param array $prepareOptions - */ - public function setPrepareOptions(array $prepareOptions) - { - $this->prepareOptions = $prepareOptions; - } -} diff --git a/library/Zend/Db/Adapter/Driver/StatementInterface.php b/library/Zend/Db/Adapter/Driver/StatementInterface.php deleted file mode 100755 index a1ba56709..000000000 --- a/library/Zend/Db/Adapter/Driver/StatementInterface.php +++ /dev/null @@ -1,44 +0,0 @@ -parameters = $parameters; - } -} diff --git a/library/Zend/Db/Adapter/Exception/InvalidQueryException.php b/library/Zend/Db/Adapter/Exception/InvalidQueryException.php deleted file mode 100755 index 1372237fe..000000000 --- a/library/Zend/Db/Adapter/Exception/InvalidQueryException.php +++ /dev/null @@ -1,14 +0,0 @@ -setFromArray($data); - } - } - - /** - * Offset exists - * - * @param string $name - * @return bool - */ - public function offsetExists($name) - { - return (isset($this->data[$name])); - } - - /** - * Offset get - * - * @param string $name - * @return mixed - */ - public function offsetGet($name) - { - return (isset($this->data[$name])) ? $this->data[$name] : null; - } - - /** - * @param $name - * @param $from - */ - public function offsetSetReference($name, $from) - { - $this->data[$name] =& $this->data[$from]; - } - - /** - * Offset set - * - * @param string|int $name - * @param mixed $value - * @param mixed $errata - */ - public function offsetSet($name, $value, $errata = null) - { - $position = false; - - // if integer, get name for this position - if (is_int($name)) { - if (isset($this->positions[$name])) { - $position = $name; - $name = $this->positions[$name]; - } else { - $name = (string) $name; - } - } elseif (is_string($name)) { - // is a string: - $position = array_key_exists($name, $this->data); - } elseif ($name === null) { - $name = (string) count($this->data); - } else { - throw new Exception\InvalidArgumentException('Keys must be string, integer or null'); - } - - if ($position === false) { - $this->positions[] = $name; - } - - $this->data[$name] = $value; - - if ($errata) { - $this->offsetSetErrata($name, $errata); - } - } - - /** - * Offset unset - * - * @param string $name - * @return ParameterContainer - */ - public function offsetUnset($name) - { - if (is_int($name) && isset($this->positions[$name])) { - $name = $this->positions[$name]; - } - unset($this->data[$name]); - return $this; - } - - /** - * Set from array - * - * @param array $data - * @return ParameterContainer - */ - public function setFromArray(Array $data) - { - foreach ($data as $n => $v) { - $this->offsetSet($n, $v); - } - return $this; - } - - /** - * Offset set errata - * - * @param string|int $name - * @param mixed $errata - */ - public function offsetSetErrata($name, $errata) - { - if (is_int($name)) { - $name = $this->positions[$name]; - } - $this->errata[$name] = $errata; - } - - /** - * Offset get errata - * - * @param string|int $name - * @throws Exception\InvalidArgumentException - * @return mixed - */ - public function offsetGetErrata($name) - { - if (is_int($name)) { - $name = $this->positions[$name]; - } - if (!array_key_exists($name, $this->data)) { - throw new Exception\InvalidArgumentException('Data does not exist for this name/position'); - } - return $this->errata[$name]; - } - - /** - * Offset has errata - * - * @param string|int $name - * @return bool - */ - public function offsetHasErrata($name) - { - if (is_int($name)) { - $name = $this->positions[$name]; - } - return (isset($this->errata[$name])); - } - - /** - * Offset unset errata - * - * @param string|int $name - * @throws Exception\InvalidArgumentException - */ - public function offsetUnsetErrata($name) - { - if (is_int($name)) { - $name = $this->positions[$name]; - } - if (!array_key_exists($name, $this->errata)) { - throw new Exception\InvalidArgumentException('Data does not exist for this name/position'); - } - $this->errata[$name] = null; - } - - /** - * Get errata iterator - * - * @return \ArrayIterator - */ - public function getErrataIterator() - { - return new \ArrayIterator($this->errata); - } - - /** - * getNamedArray - * - * @return array - */ - public function getNamedArray() - { - return $this->data; - } - - /** - * getNamedArray - * - * @return array - */ - public function getPositionalArray() - { - return array_values($this->data); - } - - /** - * count - * - * @return int - */ - public function count() - { - return count($this->data); - } - - /** - * Current - * - * @return mixed - */ - public function current() - { - return current($this->data); - } - - /** - * Next - * - * @return mixed - */ - public function next() - { - return next($this->data); - } - - /** - * Key - * - * @return mixed - */ - public function key() - { - return key($this->data); - } - - /** - * Valid - * - * @return bool - */ - public function valid() - { - return (current($this->data) !== false); - } - - /** - * Rewind - */ - public function rewind() - { - reset($this->data); - } - - /** - * @param array|ParameterContainer $parameters - * @throws Exception\InvalidArgumentException - * @return ParameterContainer - */ - public function merge($parameters) - { - if (!is_array($parameters) && !$parameters instanceof ParameterContainer) { - throw new Exception\InvalidArgumentException('$parameters must be an array or an instance of ParameterContainer'); - } - - if (count($parameters) == 0) { - return $this; - } - - if ($parameters instanceof ParameterContainer) { - $parameters = $parameters->getNamedArray(); - } - - foreach ($parameters as $key => $value) { - if (is_int($key)) { - $key = null; - } - $this->offsetSet($key, $value); - } - return $this; - } -} diff --git a/library/Zend/Db/Adapter/Platform/IbmDb2.php b/library/Zend/Db/Adapter/Platform/IbmDb2.php deleted file mode 100755 index 693b647e8..000000000 --- a/library/Zend/Db/Adapter/Platform/IbmDb2.php +++ /dev/null @@ -1,207 +0,0 @@ -quoteIdentifiers = false; - } - - if (isset($options['identifier_separator'])) { - $this->identifierSeparator = $options['identifier_separator']; - } - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return 'IBM DB2'; - } - - /** - * Get quote indentifier symbol - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return '"'; - } - - /** - * Quote identifier - * - * @param string $identifier - * @return string - */ - public function quoteIdentifier($identifier) - { - if ($this->quoteIdentifiers === false) { - return $identifier; - } - return '"' . str_replace('"', '\\' . '"', $identifier) . '"'; - } - - /** - * Quote identifier chain - * - * @param string|string[] $identifierChain - * @return string - */ - public function quoteIdentifierChain($identifierChain) - { - if ($this->quoteIdentifiers === false) { - return (is_array($identifierChain)) ? implode($this->identifierSeparator, $identifierChain) : $identifierChain; - } - $identifierChain = str_replace('"', '\\"', $identifierChain); - if (is_array($identifierChain)) { - $identifierChain = implode('"' . $this->identifierSeparator . '"', $identifierChain); - } - return '"' . $identifierChain . '"'; - } - - /** - * Get quote value symbol - * - * @return string - */ - public function getQuoteValueSymbol() - { - return '\''; - } - - /** - * Quote value - * - * @param string $value - * @return string - */ - public function quoteValue($value) - { - if (function_exists('db2_escape_string')) { - return '\'' . db2_escape_string($value) . '\''; - } - trigger_error( - 'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support ' - . 'can introduce security vulnerabilities in a production environment.' - ); - return '\'' . str_replace("'", "''", $value) . '\''; - } - - /** - * Quote Trusted Value - * - * The ability to quote values without notices - * - * @param $value - * @return mixed - */ - public function quoteTrustedValue($value) - { - if (function_exists('db2_escape_string')) { - return '\'' . db2_escape_string($value) . '\''; - } - return '\'' . str_replace("'", "''", $value) . '\''; - } - - /** - * Quote value list - * - * @param string|string[] $valueList - * @return string - */ - public function quoteValueList($valueList) - { - if (!is_array($valueList)) { - return $this->quoteValue($valueList); - } - - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return $this->identifierSeparator; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - if ($this->quoteIdentifiers === false) { - return $identifier; - } - $parts = preg_split('#([\.\s\W])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '"' . str_replace('"', '\\' . '"', $part) . '"'; - } - } - - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Platform/Mysql.php b/library/Zend/Db/Adapter/Platform/Mysql.php deleted file mode 100755 index 6e02f083a..000000000 --- a/library/Zend/Db/Adapter/Platform/Mysql.php +++ /dev/null @@ -1,214 +0,0 @@ -setDriver($driver); - } - } - - /** - * @param \Zend\Db\Adapter\Driver\Mysqli\Mysqli|\Zend\Db\Adapter\Driver\Pdo\Pdo||\mysqli|\PDO $driver - * @throws \Zend\Db\Adapter\Exception\InvalidArgumentException - * @return $this - */ - public function setDriver($driver) - { - // handle Zend\Db drivers - if ($driver instanceof Mysqli\Mysqli - || ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() == 'Mysql') - || ($driver instanceof \mysqli) - || ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'mysql') - ) { - $this->resource = $driver; - return $this; - } - - throw new Exception\InvalidArgumentException('$driver must be a Mysqli or Mysql PDO Zend\Db\Adapter\Driver, Mysqli instance or MySQL PDO instance'); - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return 'MySQL'; - } - - /** - * Get quote identifier symbol - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return '`'; - } - - /** - * Quote identifier - * - * @param string $identifier - * @return string - */ - public function quoteIdentifier($identifier) - { - return '`' . str_replace('`', '``', $identifier) . '`'; - } - - /** - * Quote identifier chain - * - * @param string|string[] $identifierChain - * @return string - */ - public function quoteIdentifierChain($identifierChain) - { - $identifierChain = str_replace('`', '``', $identifierChain); - if (is_array($identifierChain)) { - $identifierChain = implode('`.`', $identifierChain); - } - return '`' . $identifierChain . '`'; - } - - /** - * Get quote value symbol - * - * @return string - */ - public function getQuoteValueSymbol() - { - return '\''; - } - - /** - * Quote value - * - * @param string $value - * @return string - */ - public function quoteValue($value) - { - if ($this->resource instanceof DriverInterface) { - $this->resource = $this->resource->getConnection()->getResource(); - } - if ($this->resource instanceof \mysqli) { - return '\'' . $this->resource->real_escape_string($value) . '\''; - } - if ($this->resource instanceof \PDO) { - return $this->resource->quote($value); - } - trigger_error( - 'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support ' - . 'can introduce security vulnerabilities in a production environment.' - ); - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote Trusted Value - * - * The ability to quote values without notices - * - * @param $value - * @return mixed - */ - public function quoteTrustedValue($value) - { - if ($this->resource instanceof DriverInterface) { - $this->resource = $this->resource->getConnection()->getResource(); - } - if ($this->resource instanceof \mysqli) { - return '\'' . $this->resource->real_escape_string($value) . '\''; - } - if ($this->resource instanceof \PDO) { - return $this->resource->quote($value); - } - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote value list - * - * @param string|string[] $valueList - * @return string - */ - public function quoteValueList($valueList) - { - if (!is_array($valueList)) { - return $this->quoteValue($valueList); - } - - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return '.'; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - // regex taken from @link http://dev.mysql.com/doc/refman/5.0/en/identifiers.html - $parts = preg_split('#([^0-9,a-z,A-Z$_])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '`' . str_replace('`', '``', $part) . '`'; - } - } - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Platform/Oracle.php b/library/Zend/Db/Adapter/Platform/Oracle.php deleted file mode 100755 index 61f700a49..000000000 --- a/library/Zend/Db/Adapter/Platform/Oracle.php +++ /dev/null @@ -1,187 +0,0 @@ -quoteIdentifiers = false; - } - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return 'Oracle'; - } - - /** - * Get quote identifier symbol - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return '"'; - } - - /** - * Quote identifier - * - * @param string $identifier - * @return string - */ - public function quoteIdentifier($identifier) - { - if ($this->quoteIdentifiers === false) { - return $identifier; - } - return '"' . str_replace('"', '\\' . '"', $identifier) . '"'; - } - - /** - * Quote identifier chain - * - * @param string|string[] $identifierChain - * @return string - */ - public function quoteIdentifierChain($identifierChain) - { - if ($this->quoteIdentifiers === false) { - return (is_array($identifierChain)) ? implode('.', $identifierChain) : $identifierChain; - } - $identifierChain = str_replace('"', '\\"', $identifierChain); - if (is_array($identifierChain)) { - $identifierChain = implode('"."', $identifierChain); - } - return '"' . $identifierChain . '"'; - } - - /** - * Get quote value symbol - * - * @return string - */ - public function getQuoteValueSymbol() - { - return '\''; - } - - /** - * Quote value - * - * @param string $value - * @return string - */ - public function quoteValue($value) - { - trigger_error( - 'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support ' - . 'can introduce security vulnerabilities in a production environment.' - ); - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote Trusted Value - * - * The ability to quote values without notices - * - * @param $value - * @return mixed - */ - public function quoteTrustedValue($value) - { - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote value list - * - * @param string|string[] $valueList - * @return string - */ - public function quoteValueList($valueList) - { - if (!is_array($valueList)) { - return $this->quoteValue($valueList); - } - - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return '.'; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - if ($this->quoteIdentifiers === false) { - return $identifier; - } - $parts = preg_split('#([\.\s\W])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '"' . str_replace('"', '\\' . '"', $part) . '"'; - } - } - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Platform/PlatformInterface.php b/library/Zend/Db/Adapter/Platform/PlatformInterface.php deleted file mode 100755 index d8ec05b2b..000000000 --- a/library/Zend/Db/Adapter/Platform/PlatformInterface.php +++ /dev/null @@ -1,94 +0,0 @@ -setDriver($driver); - } - } - - /** - * @param \Zend\Db\Adapter\Driver\Pgsql\Pgsql|\Zend\Db\Adapter\Driver\Pdo\Pdo|resource|\PDO $driver - * @throws \Zend\Db\Adapter\Exception\InvalidArgumentException - * @return $this - */ - public function setDriver($driver) - { - if ($driver instanceof Pgsql\Pgsql - || ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() == 'Postgresql') - || (is_resource($driver) && (in_array(get_resource_type($driver), array('pgsql link', 'pgsql link persistent')))) - || ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'pgsql') - ) { - $this->resource = $driver; - return $this; - } - - throw new Exception\InvalidArgumentException('$driver must be a Pgsql or Postgresql PDO Zend\Db\Adapter\Driver, pgsql link resource or Postgresql PDO instance'); - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return 'PostgreSQL'; - } - - /** - * Get quote indentifier symbol - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return '"'; - } - - /** - * Quote identifier - * - * @param string $identifier - * @return string - */ - public function quoteIdentifier($identifier) - { - return '"' . str_replace('"', '\\' . '"', $identifier) . '"'; - } - - /** - * Quote identifier chain - * - * @param string|string[] $identifierChain - * @return string - */ - public function quoteIdentifierChain($identifierChain) - { - $identifierChain = str_replace('"', '\\"', $identifierChain); - if (is_array($identifierChain)) { - $identifierChain = implode('"."', $identifierChain); - } - return '"' . $identifierChain . '"'; - } - - /** - * Get quote value symbol - * - * @return string - */ - public function getQuoteValueSymbol() - { - return '\''; - } - - /** - * Quote value - * - * @param string $value - * @return string - */ - public function quoteValue($value) - { - if ($this->resource instanceof DriverInterface) { - $this->resource = $this->resource->getConnection()->getResource(); - } - if (is_resource($this->resource)) { - return '\'' . pg_escape_string($this->resource, $value) . '\''; - } - if ($this->resource instanceof \PDO) { - return $this->resource->quote($value); - } - trigger_error( - 'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support ' - . 'can introduce security vulnerabilities in a production environment.' - ); - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote Trusted Value - * - * The ability to quote values without notices - * - * @param $value - * @return mixed - */ - public function quoteTrustedValue($value) - { - if ($this->resource instanceof DriverInterface) { - $this->resource = $this->resource->getConnection()->getResource(); - } - if (is_resource($this->resource)) { - return '\'' . pg_escape_string($this->resource, $value) . '\''; - } - if ($this->resource instanceof \PDO) { - return $this->resource->quote($value); - } - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote value list - * - * @param string|string[] $valueList - * @return string - */ - public function quoteValueList($valueList) - { - if (!is_array($valueList)) { - return $this->quoteValue($valueList); - } - - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return '.'; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - $parts = preg_split('#([\.\s\W])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '"' . str_replace('"', '\\' . '"', $part) . '"'; - } - } - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Platform/Sql92.php b/library/Zend/Db/Adapter/Platform/Sql92.php deleted file mode 100755 index bbeda46d7..000000000 --- a/library/Zend/Db/Adapter/Platform/Sql92.php +++ /dev/null @@ -1,161 +0,0 @@ -quoteValue($valueList); - } - - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return '.'; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - $parts = preg_split('#([\.\s\W])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '"' . str_replace('"', '\\' . '"', $part) . '"'; - } - } - - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Platform/SqlServer.php b/library/Zend/Db/Adapter/Platform/SqlServer.php deleted file mode 100755 index 74a9acb9c..000000000 --- a/library/Zend/Db/Adapter/Platform/SqlServer.php +++ /dev/null @@ -1,203 +0,0 @@ -setDriver($driver); - } - } - - /** - * @param \Zend\Db\Adapter\Driver\Sqlsrv\Sqlsrv|\Zend\Db\Adapter\Driver\Pdo\Pdo||resource|\PDO $driver - * @throws \Zend\Db\Adapter\Exception\InvalidArgumentException - * @return $this - */ - public function setDriver($driver) - { - // handle Zend\Db drivers - if (($driver instanceof Pdo\Pdo && in_array($driver->getDatabasePlatformName(), array('SqlServer', 'Dblib'))) - || (($driver instanceof \PDO && in_array($driver->getAttribute(\PDO::ATTR_DRIVER_NAME), array('sqlsrv', 'dblib')))) - ) { - $this->resource = $driver; - return $this; - } - - throw new Exception\InvalidArgumentException('$driver must be a Sqlsrv PDO Zend\Db\Adapter\Driver or Sqlsrv PDO instance'); - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return 'SQLServer'; - } - - /** - * Get quote identifier symbol - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return array('[', ']'); - } - - /** - * Quote identifier - * - * @param string $identifier - * @return string - */ - public function quoteIdentifier($identifier) - { - return '[' . $identifier . ']'; - } - - /** - * Quote identifier chain - * - * @param string|string[] $identifierChain - * @return string - */ - public function quoteIdentifierChain($identifierChain) - { - if (is_array($identifierChain)) { - $identifierChain = implode('].[', $identifierChain); - } - return '[' . $identifierChain . ']'; - } - - /** - * Get quote value symbol - * - * @return string - */ - public function getQuoteValueSymbol() - { - return '\''; - } - - /** - * Quote value - * - * @param string $value - * @return string - */ - public function quoteValue($value) - { - if ($this->resource instanceof DriverInterface) { - $this->resource = $this->resource->getConnection()->getResource(); - } - if ($this->resource instanceof \PDO) { - return $this->resource->quote($value); - } - trigger_error( - 'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support ' - . 'can introduce security vulnerabilities in a production environment.' - ); - $value = addcslashes($value, "\000\032"); - return '\'' . str_replace('\'', '\'\'', $value) . '\''; - } - - /** - * Quote Trusted Value - * - * The ability to quote values without notices - * - * @param $value - * @return mixed - */ - public function quoteTrustedValue($value) - { - if ($this->resource instanceof DriverInterface) { - $this->resource = $this->resource->getConnection()->getResource(); - } - if ($this->resource instanceof \PDO) { - return $this->resource->quote($value); - } - return '\'' . str_replace('\'', '\'\'', $value) . '\''; - } - - /** - * Quote value list - * - * @param string|string[] $valueList - * @return string - */ - public function quoteValueList($valueList) - { - if (!is_array($valueList)) { - return $this->quoteValue($valueList); - } - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return '.'; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - $parts = preg_split('#([\.\s\W])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '[' . $part . ']'; - } - } - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Platform/Sqlite.php b/library/Zend/Db/Adapter/Platform/Sqlite.php deleted file mode 100755 index 340c247e3..000000000 --- a/library/Zend/Db/Adapter/Platform/Sqlite.php +++ /dev/null @@ -1,210 +0,0 @@ -setDriver($driver); - } - } - - /** - * @param \Zend\Db\Adapter\Driver\Pdo\Pdo||\PDO $driver - * @throws \Zend\Db\Adapter\Exception\InvalidArgumentException - * @return $this - */ - public function setDriver($driver) - { - if (($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'sqlite') - || ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() == 'Sqlite') - ) { - $this->resource = $driver; - return $this; - } - - throw new Exception\InvalidArgumentException('$driver must be a Sqlite PDO Zend\Db\Adapter\Driver, Sqlite PDO instance'); - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return 'SQLite'; - } - - /** - * Get quote identifier symbol - * - * @return string - */ - public function getQuoteIdentifierSymbol() - { - return '"'; - } - - /** - * Quote identifier - * - * @param string $identifier - * @return string - */ - public function quoteIdentifier($identifier) - { - return '"' . str_replace('"', '\\' . '"', $identifier) . '"'; - } - - /** - * Quote identifier chain - * - * @param string|string[] $identifierChain - * @return string - */ - public function quoteIdentifierChain($identifierChain) - { - $identifierChain = str_replace('"', '\\"', $identifierChain); - if (is_array($identifierChain)) { - $identifierChain = implode('"."', $identifierChain); - } - return '"' . $identifierChain . '"'; - } - - /** - * Get quote value symbol - * - * @return string - */ - public function getQuoteValueSymbol() - { - return '\''; - } - - /** - * Quote value - * - * @param string $value - * @return string - */ - public function quoteValue($value) - { - $resource = $this->resource; - - if ($resource instanceof DriverInterface) { - $resource = $resource->getConnection()->getResource(); - } - - if ($resource instanceof \PDO) { - return $resource->quote($value); - } - - trigger_error( - 'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support ' - . 'can introduce security vulnerabilities in a production environment.' - ); - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote Trusted Value - * - * The ability to quote values without notices - * - * @param $value - * @return mixed - */ - public function quoteTrustedValue($value) - { - $resource = $this->resource; - - if ($resource instanceof DriverInterface) { - $resource = $resource->getConnection()->getResource(); - } - - if ($resource instanceof \PDO) { - return $resource->quote($value); - } - - return '\'' . addcslashes($value, "\x00\n\r\\'\"\x1a") . '\''; - } - - /** - * Quote value list - * - * @param string|string[] $valueList - * @return string - */ - public function quoteValueList($valueList) - { - if (!is_array($valueList)) { - return $this->quoteValue($valueList); - } - $value = reset($valueList); - do { - $valueList[key($valueList)] = $this->quoteValue($value); - } while ($value = next($valueList)); - return implode(', ', $valueList); - } - - /** - * Get identifier separator - * - * @return string - */ - public function getIdentifierSeparator() - { - return '.'; - } - - /** - * Quote identifier in fragment - * - * @param string $identifier - * @param array $safeWords - * @return string - */ - public function quoteIdentifierInFragment($identifier, array $safeWords = array()) - { - $parts = preg_split('#([\.\s\W])#', $identifier, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - if ($safeWords) { - $safeWords = array_flip($safeWords); - $safeWords = array_change_key_case($safeWords, CASE_LOWER); - } - foreach ($parts as $i => $part) { - if ($safeWords && isset($safeWords[strtolower($part)])) { - continue; - } - switch ($part) { - case ' ': - case '.': - case '*': - case 'AS': - case 'As': - case 'aS': - case 'as': - break; - default: - $parts[$i] = '"' . str_replace('"', '\\' . '"', $part) . '"'; - } - } - return implode('', $parts); - } -} diff --git a/library/Zend/Db/Adapter/Profiler/Profiler.php b/library/Zend/Db/Adapter/Profiler/Profiler.php deleted file mode 100755 index 5115e3f3f..000000000 --- a/library/Zend/Db/Adapter/Profiler/Profiler.php +++ /dev/null @@ -1,85 +0,0 @@ - '', - 'parameters' => null, - 'start' => microtime(true), - 'end' => null, - 'elapse' => null - ); - if ($target instanceof StatementContainerInterface) { - $profileInformation['sql'] = $target->getSql(); - $profileInformation['parameters'] = clone $target->getParameterContainer(); - } elseif (is_string($target)) { - $profileInformation['sql'] = $target; - } else { - throw new Exception\InvalidArgumentException(__FUNCTION__ . ' takes either a StatementContainer or a string'); - } - - $this->profiles[$this->currentIndex] = $profileInformation; - - return $this; - } - - /** - * @return Profiler - */ - public function profilerFinish() - { - if (!isset($this->profiles[$this->currentIndex])) { - throw new Exception\RuntimeException('A profile must be started before ' . __FUNCTION__ . ' can be called.'); - } - $current = &$this->profiles[$this->currentIndex]; - $current['end'] = microtime(true); - $current['elapse'] = $current['end'] - $current['start']; - $this->currentIndex++; - return $this; - } - - /** - * @return array|null - */ - public function getLastProfile() - { - return end($this->profiles); - } - - /** - * @return array - */ - public function getProfiles() - { - return $this->profiles; - } -} diff --git a/library/Zend/Db/Adapter/Profiler/ProfilerAwareInterface.php b/library/Zend/Db/Adapter/Profiler/ProfilerAwareInterface.php deleted file mode 100755 index a0b631d94..000000000 --- a/library/Zend/Db/Adapter/Profiler/ProfilerAwareInterface.php +++ /dev/null @@ -1,15 +0,0 @@ -setSql($sql); - } - $this->parameterContainer = ($parameterContainer) ?: new ParameterContainer; - } - - /** - * @param $sql - * @return StatementContainer - */ - public function setSql($sql) - { - $this->sql = $sql; - return $this; - } - - /** - * @return string - */ - public function getSql() - { - return $this->sql; - } - - /** - * @param ParameterContainer $parameterContainer - * @return StatementContainer - */ - public function setParameterContainer(ParameterContainer $parameterContainer) - { - $this->parameterContainer = $parameterContainer; - return $this; - } - - /** - * @return null|ParameterContainer - */ - public function getParameterContainer() - { - return $this->parameterContainer; - } -} diff --git a/library/Zend/Db/Adapter/StatementContainerInterface.php b/library/Zend/Db/Adapter/StatementContainerInterface.php deleted file mode 100755 index 098d6a6fd..000000000 --- a/library/Zend/Db/Adapter/StatementContainerInterface.php +++ /dev/null @@ -1,43 +0,0 @@ -adapter = $adapter; - $this->source = $this->createSourceFromAdapter($adapter); - } - - /** - * Create source from adapter - * - * @param Adapter $adapter - * @return Source\AbstractSource - */ - protected function createSourceFromAdapter(Adapter $adapter) - { - switch ($adapter->getPlatform()->getName()) { - case 'MySQL': - return new Source\MysqlMetadata($adapter); - case 'SQLServer': - return new Source\SqlServerMetadata($adapter); - case 'SQLite': - return new Source\SqliteMetadata($adapter); - case 'PostgreSQL': - return new Source\PostgresqlMetadata($adapter); - case 'Oracle': - return new Source\OracleMetadata($adapter); - } - - throw new \Exception('cannot create source from adapter'); - } - - // @todo methods - - /** - * Get base tables and views - * - * @param string $schema - * @param bool $includeViews - * @return Object\TableObject[] - */ - public function getTables($schema = null, $includeViews = false) - { - return $this->source->getTables($schema, $includeViews); - } - - /** - * Get base tables and views - * - * @param string $schema - * @return Object\TableObject[] - */ - public function getViews($schema = null) - { - return $this->source->getViews($schema); - } - - /** - * Get triggers - * - * @param string $schema - * @return array - */ - public function getTriggers($schema = null) - { - return $this->source->getTriggers($schema); - } - - /** - * Get constraints - * - * @param string $table - * @param string $schema - * @return array - */ - public function getConstraints($table, $schema = null) - { - return $this->source->getConstraints($table, $schema); - } - - /** - * Get columns - * - * @param string $table - * @param string $schema - * @return array - */ - public function getColumns($table, $schema = null) - { - return $this->source->getColumns($table, $schema); - } - - /** - * Get constraint keys - * - * @param string $constraint - * @param string $table - * @param string $schema - * @return array - */ - public function getConstraintKeys($constraint, $table, $schema = null) - { - return $this->source->getConstraintKeys($constraint, $table, $schema); - } - - /** - * Get constraints - * - * @param string $constraintName - * @param string $table - * @param string $schema - * @return Object\ConstraintObject - */ - public function getConstraint($constraintName, $table, $schema = null) - { - return $this->source->getConstraint($constraintName, $table, $schema); - } - - /** - * Get schemas - */ - public function getSchemas() - { - return $this->source->getSchemas(); - } - - /** - * Get table names - * - * @param string $schema - * @param bool $includeViews - * @return array - */ - public function getTableNames($schema = null, $includeViews = false) - { - return $this->source->getTableNames($schema, $includeViews); - } - - /** - * Get table - * - * @param string $tableName - * @param string $schema - * @return Object\TableObject - */ - public function getTable($tableName, $schema = null) - { - return $this->source->getTable($tableName, $schema); - } - - /** - * Get views names - * - * @param string $schema - * @return \Zend\Db\Metadata\Object\TableObject - */ - public function getViewNames($schema = null) - { - return $this->source->getViewNames($schema); - } - - /** - * Get view - * - * @param string $viewName - * @param string $schema - * @return \Zend\Db\Metadata\Object\TableObject - */ - public function getView($viewName, $schema = null) - { - return $this->source->getView($viewName, $schema); - } - - /** - * Get trigger names - * - * @param string $schema - * @return array - */ - public function getTriggerNames($schema = null) - { - return $this->source->getTriggerNames($schema); - } - - /** - * Get trigger - * - * @param string $triggerName - * @param string $schema - * @return \Zend\Db\Metadata\Object\TriggerObject - */ - public function getTrigger($triggerName, $schema = null) - { - return $this->source->getTrigger($triggerName, $schema); - } - - /** - * Get column names - * - * @param string $table - * @param string $schema - * @return array - */ - public function getColumnNames($table, $schema = null) - { - return $this->source->getColumnNames($table, $schema); - } - - /** - * Get column - * - * @param string $columnName - * @param string $table - * @param string $schema - * @return \Zend\Db\Metadata\Object\ColumnObject - */ - public function getColumn($columnName, $table, $schema = null) - { - return $this->source->getColumn($columnName, $table, $schema); - } -} diff --git a/library/Zend/Db/Metadata/MetadataInterface.php b/library/Zend/Db/Metadata/MetadataInterface.php deleted file mode 100755 index f0f58eb30..000000000 --- a/library/Zend/Db/Metadata/MetadataInterface.php +++ /dev/null @@ -1,35 +0,0 @@ -setName($name); - } - } - - /** - * Set columns - * - * @param array $columns - */ - public function setColumns(array $columns) - { - $this->columns = $columns; - } - - /** - * Get columns - * - * @return array - */ - public function getColumns() - { - return $this->columns; - } - - /** - * Set constraints - * - * @param array $constraints - */ - public function setConstraints($constraints) - { - $this->constraints = $constraints; - } - - /** - * Get constraints - * - * @return array - */ - public function getConstraints() - { - return $this->constraints; - } - - /** - * Set name - * - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return $this->name; - } -} diff --git a/library/Zend/Db/Metadata/Object/ColumnObject.php b/library/Zend/Db/Metadata/Object/ColumnObject.php deleted file mode 100755 index e76a91a99..000000000 --- a/library/Zend/Db/Metadata/Object/ColumnObject.php +++ /dev/null @@ -1,388 +0,0 @@ -setName($name); - $this->setTableName($tableName); - $this->setSchemaName($schemaName); - } - - /** - * Set name - * - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Get table name - * - * @return string - */ - public function getTableName() - { - return $this->tableName; - } - - /** - * Set table name - * - * @param string $tableName - * @return ColumnObject - */ - public function setTableName($tableName) - { - $this->tableName = $tableName; - return $this; - } - - /** - * Set schema name - * - * @param string $schemaName - */ - public function setSchemaName($schemaName) - { - $this->schemaName = $schemaName; - } - - /** - * Get schema name - * - * @return string - */ - public function getSchemaName() - { - return $this->schemaName; - } - - /** - * @return int $ordinalPosition - */ - public function getOrdinalPosition() - { - return $this->ordinalPosition; - } - - /** - * @param int $ordinalPosition to set - * @return ColumnObject - */ - public function setOrdinalPosition($ordinalPosition) - { - $this->ordinalPosition = $ordinalPosition; - return $this; - } - - /** - * @return null|string the $columnDefault - */ - public function getColumnDefault() - { - return $this->columnDefault; - } - - /** - * @param mixed $columnDefault to set - * @return ColumnObject - */ - public function setColumnDefault($columnDefault) - { - $this->columnDefault = $columnDefault; - return $this; - } - - /** - * @return bool $isNullable - */ - public function getIsNullable() - { - return $this->isNullable; - } - - /** - * @param bool $isNullable to set - * @return ColumnObject - */ - public function setIsNullable($isNullable) - { - $this->isNullable = $isNullable; - return $this; - } - - /** - * @return bool $isNullable - */ - public function isNullable() - { - return $this->isNullable; - } - - /** - * @return null|string the $dataType - */ - public function getDataType() - { - return $this->dataType; - } - - /** - * @param string $dataType the $dataType to set - * @return ColumnObject - */ - public function setDataType($dataType) - { - $this->dataType = $dataType; - return $this; - } - - /** - * @return int|null the $characterMaximumLength - */ - public function getCharacterMaximumLength() - { - return $this->characterMaximumLength; - } - - /** - * @param int $characterMaximumLength the $characterMaximumLength to set - * @return ColumnObject - */ - public function setCharacterMaximumLength($characterMaximumLength) - { - $this->characterMaximumLength = $characterMaximumLength; - return $this; - } - - /** - * @return int|null the $characterOctetLength - */ - public function getCharacterOctetLength() - { - return $this->characterOctetLength; - } - - /** - * @param int $characterOctetLength the $characterOctetLength to set - * @return ColumnObject - */ - public function setCharacterOctetLength($characterOctetLength) - { - $this->characterOctetLength = $characterOctetLength; - return $this; - } - - /** - * @return int the $numericPrecision - */ - public function getNumericPrecision() - { - return $this->numericPrecision; - } - - /** - * @param int $numericPrecision the $numericPrevision to set - * @return ColumnObject - */ - public function setNumericPrecision($numericPrecision) - { - $this->numericPrecision = $numericPrecision; - return $this; - } - - /** - * @return int the $numericScale - */ - public function getNumericScale() - { - return $this->numericScale; - } - - /** - * @param int $numericScale the $numericScale to set - * @return ColumnObject - */ - public function setNumericScale($numericScale) - { - $this->numericScale = $numericScale; - return $this; - } - - /** - * @return bool - */ - public function getNumericUnsigned() - { - return $this->numericUnsigned; - } - - /** - * @param bool $numericUnsigned - * @return ColumnObject - */ - public function setNumericUnsigned($numericUnsigned) - { - $this->numericUnsigned = $numericUnsigned; - return $this; - } - - /** - * @return bool - */ - public function isNumericUnsigned() - { - return $this->numericUnsigned; - } - - /** - * @return array the $errata - */ - public function getErratas() - { - return $this->errata; - } - - /** - * @param array $erratas - * @return ColumnObject - */ - public function setErratas(array $erratas) - { - foreach ($erratas as $name => $value) { - $this->setErrata($name, $value); - } - return $this; - } - - /** - * @param string $errataName - * @return mixed - */ - public function getErrata($errataName) - { - if (array_key_exists($errataName, $this->errata)) { - return $this->errata[$errataName]; - } - return null; - } - - /** - * @param string $errataName - * @param mixed $errataValue - * @return ColumnObject - */ - public function setErrata($errataName, $errataValue) - { - $this->errata[$errataName] = $errataValue; - return $this; - } -} diff --git a/library/Zend/Db/Metadata/Object/ConstraintKeyObject.php b/library/Zend/Db/Metadata/Object/ConstraintKeyObject.php deleted file mode 100755 index 568368805..000000000 --- a/library/Zend/Db/Metadata/Object/ConstraintKeyObject.php +++ /dev/null @@ -1,249 +0,0 @@ -setColumnName($column); - } - - /** - * Get column name - * - * @return string - */ - public function getColumnName() - { - return $this->columnName; - } - - /** - * Set column name - * - * @param string $columnName - * @return ConstraintKeyObject - */ - public function setColumnName($columnName) - { - $this->columnName = $columnName; - return $this; - } - - /** - * Get ordinal position - * - * @return int - */ - public function getOrdinalPosition() - { - return $this->ordinalPosition; - } - - /** - * Set ordinal position - * - * @param int $ordinalPosition - * @return ConstraintKeyObject - */ - public function setOrdinalPosition($ordinalPosition) - { - $this->ordinalPosition = $ordinalPosition; - return $this; - } - - /** - * Get position in unique constraint - * - * @return bool - */ - public function getPositionInUniqueConstraint() - { - return $this->positionInUniqueConstraint; - } - - /** - * Set position in unique constraint - * - * @param bool $positionInUniqueConstraint - * @return ConstraintKeyObject - */ - public function setPositionInUniqueConstraint($positionInUniqueConstraint) - { - $this->positionInUniqueConstraint = $positionInUniqueConstraint; - return $this; - } - - /** - * Get referencred table schema - * - * @return string - */ - public function getReferencedTableSchema() - { - return $this->referencedTableSchema; - } - - /** - * Set referenced table schema - * - * @param string $referencedTableSchema - * @return ConstraintKeyObject - */ - public function setReferencedTableSchema($referencedTableSchema) - { - $this->referencedTableSchema = $referencedTableSchema; - return $this; - } - - /** - * Get referenced table name - * - * @return string - */ - public function getReferencedTableName() - { - return $this->referencedTableName; - } - - /** - * Set Referenced table name - * - * @param string $referencedTableName - * @return ConstraintKeyObject - */ - public function setReferencedTableName($referencedTableName) - { - $this->referencedTableName = $referencedTableName; - return $this; - } - - /** - * Get referenced column name - * - * @return string - */ - public function getReferencedColumnName() - { - return $this->referencedColumnName; - } - - /** - * Set referenced column name - * - * @param string $referencedColumnName - * @return ConstraintKeyObject - */ - public function setReferencedColumnName($referencedColumnName) - { - $this->referencedColumnName = $referencedColumnName; - return $this; - } - - /** - * set foreign key update rule - * - * @param string $foreignKeyUpdateRule - */ - public function setForeignKeyUpdateRule($foreignKeyUpdateRule) - { - $this->foreignKeyUpdateRule = $foreignKeyUpdateRule; - } - - /** - * Get foreign key update rule - * - * @return string - */ - public function getForeignKeyUpdateRule() - { - return $this->foreignKeyUpdateRule; - } - - /** - * Set foreign key delete rule - * - * @param string $foreignKeyDeleteRule - */ - public function setForeignKeyDeleteRule($foreignKeyDeleteRule) - { - $this->foreignKeyDeleteRule = $foreignKeyDeleteRule; - } - - /** - * get foreign key delete rule - * - * @return string - */ - public function getForeignKeyDeleteRule() - { - return $this->foreignKeyDeleteRule; - } -} diff --git a/library/Zend/Db/Metadata/Object/ConstraintObject.php b/library/Zend/Db/Metadata/Object/ConstraintObject.php deleted file mode 100755 index 089c5ea1f..000000000 --- a/library/Zend/Db/Metadata/Object/ConstraintObject.php +++ /dev/null @@ -1,411 +0,0 @@ -setName($name); - $this->setTableName($tableName); - $this->setSchemaName($schemaName); - } - - /** - * Set name - * - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Set schema name - * - * @param string $schemaName - */ - public function setSchemaName($schemaName) - { - $this->schemaName = $schemaName; - } - - /** - * Get schema name - * - * @return string - */ - public function getSchemaName() - { - return $this->schemaName; - } - - /** - * Get table name - * - * @return string - */ - public function getTableName() - { - return $this->tableName; - } - - /** - * Set table name - * - * @param string $tableName - * @return ConstraintObject - */ - public function setTableName($tableName) - { - $this->tableName = $tableName; - return $this; - } - - /** - * Set type - * - * @param string $type - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * Get type - * - * @return string - */ - public function getType() - { - return $this->type; - } - - public function hasColumns() - { - return (!empty($this->columns)); - } - - /** - * Get Columns. - * - * @return string[] - */ - public function getColumns() - { - return $this->columns; - } - - /** - * Set Columns. - * - * @param string[] $columns - * @return ConstraintObject - */ - public function setColumns(array $columns) - { - $this->columns = $columns; - return $this; - } - - /** - * Get Referenced Table Schema. - * - * @return string - */ - public function getReferencedTableSchema() - { - return $this->referencedTableSchema; - } - - /** - * Set Referenced Table Schema. - * - * @param string $referencedTableSchema - * @return ConstraintObject - */ - public function setReferencedTableSchema($referencedTableSchema) - { - $this->referencedTableSchema = $referencedTableSchema; - return $this; - } - - /** - * Get Referenced Table Name. - * - * @return string - */ - public function getReferencedTableName() - { - return $this->referencedTableName; - } - - /** - * Set Referenced Table Name. - * - * @param string $referencedTableName - * @return ConstraintObject - */ - public function setReferencedTableName($referencedTableName) - { - $this->referencedTableName = $referencedTableName; - return $this; - } - - /** - * Get Referenced Columns. - * - * @return string[] - */ - public function getReferencedColumns() - { - return $this->referencedColumns; - } - - /** - * Set Referenced Columns. - * - * @param string[] $referencedColumns - * @return ConstraintObject - */ - public function setReferencedColumns(array $referencedColumns) - { - $this->referencedColumns = $referencedColumns; - return $this; - } - - /** - * Get Match Option. - * - * @return string - */ - public function getMatchOption() - { - return $this->matchOption; - } - - /** - * Set Match Option. - * - * @param string $matchOption - * @return ConstraintObject - */ - public function setMatchOption($matchOption) - { - $this->matchOption = $matchOption; - return $this; - } - - /** - * Get Update Rule. - * - * @return string - */ - public function getUpdateRule() - { - return $this->updateRule; - } - - /** - * Set Update Rule. - * - * @param string $updateRule - * @return ConstraintObject - */ - public function setUpdateRule($updateRule) - { - $this->updateRule = $updateRule; - return $this; - } - - /** - * Get Delete Rule. - * - * @return string - */ - public function getDeleteRule() - { - return $this->deleteRule; - } - - /** - * Set Delete Rule. - * - * @param string $deleteRule - * @return ConstraintObject - */ - public function setDeleteRule($deleteRule) - { - $this->deleteRule = $deleteRule; - return $this; - } - - /** - * Get Check Clause. - * - * @return string - */ - public function getCheckClause() - { - return $this->checkClause; - } - - /** - * Set Check Clause. - * - * @param string $checkClause - * @return ConstraintObject - */ - public function setCheckClause($checkClause) - { - $this->checkClause = $checkClause; - return $this; - } - - /** - * Is primary key - * - * @return bool - */ - public function isPrimaryKey() - { - return ('PRIMARY KEY' == $this->type); - } - - /** - * Is unique key - * - * @return bool - */ - public function isUnique() - { - return ('UNIQUE' == $this->type); - } - - /** - * Is foreign key - * - * @return bool - */ - public function isForeignKey() - { - return ('FOREIGN KEY' == $this->type); - } - - /** - * Is foreign key - * - * @return bool - */ - public function isCheck() - { - return ('CHECK' == $this->type); - } -} diff --git a/library/Zend/Db/Metadata/Object/TableObject.php b/library/Zend/Db/Metadata/Object/TableObject.php deleted file mode 100755 index 8735fbfc8..000000000 --- a/library/Zend/Db/Metadata/Object/TableObject.php +++ /dev/null @@ -1,14 +0,0 @@ -name; - } - - /** - * Set Name. - * - * @param string $name - * @return TriggerObject - */ - public function setName($name) - { - $this->name = $name; - return $this; - } - - /** - * Get Event Manipulation. - * - * @return string - */ - public function getEventManipulation() - { - return $this->eventManipulation; - } - - /** - * Set Event Manipulation. - * - * @param string $eventManipulation - * @return TriggerObject - */ - public function setEventManipulation($eventManipulation) - { - $this->eventManipulation = $eventManipulation; - return $this; - } - - /** - * Get Event Object Catalog. - * - * @return string - */ - public function getEventObjectCatalog() - { - return $this->eventObjectCatalog; - } - - /** - * Set Event Object Catalog. - * - * @param string $eventObjectCatalog - * @return TriggerObject - */ - public function setEventObjectCatalog($eventObjectCatalog) - { - $this->eventObjectCatalog = $eventObjectCatalog; - return $this; - } - - /** - * Get Event Object Schema. - * - * @return string - */ - public function getEventObjectSchema() - { - return $this->eventObjectSchema; - } - - /** - * Set Event Object Schema. - * - * @param string $eventObjectSchema - * @return TriggerObject - */ - public function setEventObjectSchema($eventObjectSchema) - { - $this->eventObjectSchema = $eventObjectSchema; - return $this; - } - - /** - * Get Event Object Table. - * - * @return string - */ - public function getEventObjectTable() - { - return $this->eventObjectTable; - } - - /** - * Set Event Object Table. - * - * @param string $eventObjectTable - * @return TriggerObject - */ - public function setEventObjectTable($eventObjectTable) - { - $this->eventObjectTable = $eventObjectTable; - return $this; - } - - /** - * Get Action Order. - * - * @return string - */ - public function getActionOrder() - { - return $this->actionOrder; - } - - /** - * Set Action Order. - * - * @param string $actionOrder - * @return TriggerObject - */ - public function setActionOrder($actionOrder) - { - $this->actionOrder = $actionOrder; - return $this; - } - - /** - * Get Action Condition. - * - * @return string - */ - public function getActionCondition() - { - return $this->actionCondition; - } - - /** - * Set Action Condition. - * - * @param string $actionCondition - * @return TriggerObject - */ - public function setActionCondition($actionCondition) - { - $this->actionCondition = $actionCondition; - return $this; - } - - /** - * Get Action Statement. - * - * @return string - */ - public function getActionStatement() - { - return $this->actionStatement; - } - - /** - * Set Action Statement. - * - * @param string $actionStatement - * @return TriggerObject - */ - public function setActionStatement($actionStatement) - { - $this->actionStatement = $actionStatement; - return $this; - } - - /** - * Get Action Orientation. - * - * @return string - */ - public function getActionOrientation() - { - return $this->actionOrientation; - } - - /** - * Set Action Orientation. - * - * @param string $actionOrientation - * @return TriggerObject - */ - public function setActionOrientation($actionOrientation) - { - $this->actionOrientation = $actionOrientation; - return $this; - } - - /** - * Get Action Timing. - * - * @return string - */ - public function getActionTiming() - { - return $this->actionTiming; - } - - /** - * Set Action Timing. - * - * @param string $actionTiming - * @return TriggerObject - */ - public function setActionTiming($actionTiming) - { - $this->actionTiming = $actionTiming; - return $this; - } - - /** - * Get Action Reference Old Table. - * - * @return string - */ - public function getActionReferenceOldTable() - { - return $this->actionReferenceOldTable; - } - - /** - * Set Action Reference Old Table. - * - * @param string $actionReferenceOldTable - * @return TriggerObject - */ - public function setActionReferenceOldTable($actionReferenceOldTable) - { - $this->actionReferenceOldTable = $actionReferenceOldTable; - return $this; - } - - /** - * Get Action Reference New Table. - * - * @return string - */ - public function getActionReferenceNewTable() - { - return $this->actionReferenceNewTable; - } - - /** - * Set Action Reference New Table. - * - * @param string $actionReferenceNewTable - * @return TriggerObject - */ - public function setActionReferenceNewTable($actionReferenceNewTable) - { - $this->actionReferenceNewTable = $actionReferenceNewTable; - return $this; - } - - /** - * Get Action Reference Old Row. - * - * @return string - */ - public function getActionReferenceOldRow() - { - return $this->actionReferenceOldRow; - } - - /** - * Set Action Reference Old Row. - * - * @param string $actionReferenceOldRow - * @return TriggerObject - */ - public function setActionReferenceOldRow($actionReferenceOldRow) - { - $this->actionReferenceOldRow = $actionReferenceOldRow; - return $this; - } - - /** - * Get Action Reference New Row. - * - * @return string - */ - public function getActionReferenceNewRow() - { - return $this->actionReferenceNewRow; - } - - /** - * Set Action Reference New Row. - * - * @param string $actionReferenceNewRow - * @return TriggerObject - */ - public function setActionReferenceNewRow($actionReferenceNewRow) - { - $this->actionReferenceNewRow = $actionReferenceNewRow; - return $this; - } - - /** - * Get Created. - * - * @return \DateTime - */ - public function getCreated() - { - return $this->created; - } - - /** - * Set Created. - * - * @param \DateTime $created - * @return TriggerObject - */ - public function setCreated($created) - { - $this->created = $created; - return $this; - } -} diff --git a/library/Zend/Db/Metadata/Object/ViewObject.php b/library/Zend/Db/Metadata/Object/ViewObject.php deleted file mode 100755 index 5130e9ecc..000000000 --- a/library/Zend/Db/Metadata/Object/ViewObject.php +++ /dev/null @@ -1,76 +0,0 @@ -viewDefinition; - } - - /** - * @param string $viewDefinition to set - * @return ViewObject - */ - public function setViewDefinition($viewDefinition) - { - $this->viewDefinition = $viewDefinition; - return $this; - } - - /** - * @return string $checkOption - */ - public function getCheckOption() - { - return $this->checkOption; - } - - /** - * @param string $checkOption to set - * @return ViewObject - */ - public function setCheckOption($checkOption) - { - $this->checkOption = $checkOption; - return $this; - } - - /** - * @return bool $isUpdatable - */ - public function getIsUpdatable() - { - return $this->isUpdatable; - } - - /** - * @param bool $isUpdatable to set - * @return ViewObject - */ - public function setIsUpdatable($isUpdatable) - { - $this->isUpdatable = $isUpdatable; - return $this; - } - - public function isUpdatable() - { - return $this->isUpdatable; - } -} diff --git a/library/Zend/Db/Metadata/Source/AbstractSource.php b/library/Zend/Db/Metadata/Source/AbstractSource.php deleted file mode 100755 index 63d63a928..000000000 --- a/library/Zend/Db/Metadata/Source/AbstractSource.php +++ /dev/null @@ -1,601 +0,0 @@ -adapter = $adapter; - $this->defaultSchema = ($adapter->getCurrentSchema()) ?: self::DEFAULT_SCHEMA; - } - - /** - * Get schemas - * - */ - public function getSchemas() - { - $this->loadSchemaData(); - - return $this->data['schemas']; - } - - /** - * Get table names - * - * @param string $schema - * @param bool $includeViews - * @return string[] - */ - public function getTableNames($schema = null, $includeViews = false) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadTableNameData($schema); - - if ($includeViews) { - return array_keys($this->data['table_names'][$schema]); - } - - $tableNames = array(); - foreach ($this->data['table_names'][$schema] as $tableName => $data) { - if ('BASE TABLE' == $data['table_type']) { - $tableNames[] = $tableName; - } - } - return $tableNames; - } - - /** - * Get tables - * - * @param string $schema - * @param bool $includeViews - * @return Object\TableObject[] - */ - public function getTables($schema = null, $includeViews = false) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $tables = array(); - foreach ($this->getTableNames($schema, $includeViews) as $tableName) { - $tables[] = $this->getTable($tableName, $schema); - } - return $tables; - } - - /** - * Get table - * - * @param string $tableName - * @param string $schema - * @return Object\TableObject - */ - public function getTable($tableName, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadTableNameData($schema); - - if (!isset($this->data['table_names'][$schema][$tableName])) { - throw new \Exception('Table "' . $tableName . '" does not exist'); - } - - $data = $this->data['table_names'][$schema][$tableName]; - switch ($data['table_type']) { - case 'BASE TABLE': - $table = new Object\TableObject($tableName); - break; - case 'VIEW': - $table = new Object\ViewObject($tableName); - $table->setViewDefinition($data['view_definition']); - $table->setCheckOption($data['check_option']); - $table->setIsUpdatable($data['is_updatable']); - break; - default: - throw new \Exception('Table "' . $tableName . '" is of an unsupported type "' . $data['table_type'] . '"'); - } - $table->setColumns($this->getColumns($tableName, $schema)); - $table->setConstraints($this->getConstraints($tableName, $schema)); - return $table; - } - - /** - * Get view names - * - * @param string $schema - * @return array - */ - public function getViewNames($schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadTableNameData($schema); - - $viewNames = array(); - foreach ($this->data['table_names'][$schema] as $tableName => $data) { - if ('VIEW' == $data['table_type']) { - $viewNames[] = $tableName; - } - } - return $viewNames; - } - - /** - * Get views - * - * @param string $schema - * @return array - */ - public function getViews($schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $views = array(); - foreach ($this->getViewNames($schema) as $tableName) { - $views[] = $this->getTable($tableName, $schema); - } - return $views; - } - - /** - * Get view - * - * @param string $viewName - * @param string $schema - * @return \Zend\Db\Metadata\Object\TableObject - */ - public function getView($viewName, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadTableNameData($schema); - - $tableNames = $this->data['table_names'][$schema]; - if (isset($tableNames[$viewName]) && 'VIEW' == $tableNames[$viewName]['table_type']) { - return $this->getTable($viewName, $schema); - } - throw new \Exception('View "' . $viewName . '" does not exist'); - } - - /** - * Gt column names - * - * @param string $table - * @param string $schema - * @return array - */ - public function getColumnNames($table, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadColumnData($table, $schema); - - if (!isset($this->data['columns'][$schema][$table])) { - throw new \Exception('"' . $table . '" does not exist'); - } - - return array_keys($this->data['columns'][$schema][$table]); - } - - /** - * Get columns - * - * @param string $table - * @param string $schema - * @return array - */ - public function getColumns($table, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadColumnData($table, $schema); - - $columns = array(); - foreach ($this->getColumnNames($table, $schema) as $columnName) { - $columns[] = $this->getColumn($columnName, $table, $schema); - } - return $columns; - } - - /** - * Get column - * - * @param string $columnName - * @param string $table - * @param string $schema - * @return Object\ColumnObject - */ - public function getColumn($columnName, $table, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadColumnData($table, $schema); - - if (!isset($this->data['columns'][$schema][$table][$columnName])) { - throw new \Exception('A column by that name was not found.'); - } - - $info = $this->data['columns'][$schema][$table][$columnName]; - - $column = new Object\ColumnObject($columnName, $table, $schema); - $props = array( - 'ordinal_position', 'column_default', 'is_nullable', - 'data_type', 'character_maximum_length', 'character_octet_length', - 'numeric_precision', 'numeric_scale', 'numeric_unsigned', - 'erratas' - ); - foreach ($props as $prop) { - if (isset($info[$prop])) { - $column->{'set' . str_replace('_', '', $prop)}($info[$prop]); - } - } - - $column->setOrdinalPosition($info['ordinal_position']); - $column->setColumnDefault($info['column_default']); - $column->setIsNullable($info['is_nullable']); - $column->setDataType($info['data_type']); - $column->setCharacterMaximumLength($info['character_maximum_length']); - $column->setCharacterOctetLength($info['character_octet_length']); - $column->setNumericPrecision($info['numeric_precision']); - $column->setNumericScale($info['numeric_scale']); - $column->setNumericUnsigned($info['numeric_unsigned']); - $column->setErratas($info['erratas']); - - return $column; - } - - /** - * Get constraints - * - * @param string $table - * @param string $schema - * @return array - */ - public function getConstraints($table, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadConstraintData($table, $schema); - - $constraints = array(); - foreach (array_keys($this->data['constraints'][$schema][$table]) as $constraintName) { - $constraints[] = $this->getConstraint($constraintName, $table, $schema); - } - - return $constraints; - } - - /** - * Get constraint - * - * @param string $constraintName - * @param string $table - * @param string $schema - * @return Object\ConstraintObject - */ - public function getConstraint($constraintName, $table, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadConstraintData($table, $schema); - - if (!isset($this->data['constraints'][$schema][$table][$constraintName])) { - throw new \Exception('Cannot find a constraint by that name in this table'); - } - - $info = $this->data['constraints'][$schema][$table][$constraintName]; - $constraint = new Object\ConstraintObject($constraintName, $table, $schema); - - foreach (array( - 'constraint_type' => 'setType', - 'match_option' => 'setMatchOption', - 'update_rule' => 'setUpdateRule', - 'delete_rule' => 'setDeleteRule', - 'columns' => 'setColumns', - 'referenced_table_schema' => 'setReferencedTableSchema', - 'referenced_table_name' => 'setReferencedTableName', - 'referenced_columns' => 'setReferencedColumns', - 'check_clause' => 'setCheckClause', - ) as $key => $setMethod) { - if (isset($info[$key])) { - $constraint->{$setMethod}($info[$key]); - } - } - - return $constraint; - } - - /** - * Get constraint keys - * - * @param string $constraint - * @param string $table - * @param string $schema - * @return array - */ - public function getConstraintKeys($constraint, $table, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadConstraintReferences($table, $schema); - - // organize references first - $references = array(); - foreach ($this->data['constraint_references'][$schema] as $refKeyInfo) { - if ($refKeyInfo['constraint_name'] == $constraint) { - $references[$refKeyInfo['constraint_name']] = $refKeyInfo; - } - } - - $this->loadConstraintDataKeys($schema); - - $keys = array(); - foreach ($this->data['constraint_keys'][$schema] as $constraintKeyInfo) { - if ($constraintKeyInfo['table_name'] == $table && $constraintKeyInfo['constraint_name'] === $constraint) { - $keys[] = $key = new Object\ConstraintKeyObject($constraintKeyInfo['column_name']); - $key->setOrdinalPosition($constraintKeyInfo['ordinal_position']); - if (isset($references[$constraint])) { - //$key->setReferencedTableSchema($constraintKeyInfo['referenced_table_schema']); - $key->setForeignKeyUpdateRule($references[$constraint]['update_rule']); - $key->setForeignKeyDeleteRule($references[$constraint]['delete_rule']); - //$key->setReferencedTableSchema($references[$constraint]['referenced_table_schema']); - $key->setReferencedTableName($references[$constraint]['referenced_table_name']); - $key->setReferencedColumnName($references[$constraint]['referenced_column_name']); - } - } - } - - return $keys; - } - - /** - * Get trigger names - * - * @param string $schema - * @return array - */ - public function getTriggerNames($schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadTriggerData($schema); - - return array_keys($this->data['triggers'][$schema]); - } - - /** - * Get triggers - * - * @param string $schema - * @return array - */ - public function getTriggers($schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $triggers = array(); - foreach ($this->getTriggerNames($schema) as $triggerName) { - $triggers[] = $this->getTrigger($triggerName, $schema); - } - return $triggers; - } - - /** - * Get trigger - * - * @param string $triggerName - * @param string $schema - * @return Object\TriggerObject - */ - public function getTrigger($triggerName, $schema = null) - { - if ($schema === null) { - $schema = $this->defaultSchema; - } - - $this->loadTriggerData($schema); - - if (!isset($this->data['triggers'][$schema][$triggerName])) { - throw new \Exception('Trigger "' . $triggerName . '" does not exist'); - } - - $info = $this->data['triggers'][$schema][$triggerName]; - - $trigger = new Object\TriggerObject(); - - $trigger->setName($triggerName); - $trigger->setEventManipulation($info['event_manipulation']); - $trigger->setEventObjectCatalog($info['event_object_catalog']); - $trigger->setEventObjectSchema($info['event_object_schema']); - $trigger->setEventObjectTable($info['event_object_table']); - $trigger->setActionOrder($info['action_order']); - $trigger->setActionCondition($info['action_condition']); - $trigger->setActionStatement($info['action_statement']); - $trigger->setActionOrientation($info['action_orientation']); - $trigger->setActionTiming($info['action_timing']); - $trigger->setActionReferenceOldTable($info['action_reference_old_table']); - $trigger->setActionReferenceNewTable($info['action_reference_new_table']); - $trigger->setActionReferenceOldRow($info['action_reference_old_row']); - $trigger->setActionReferenceNewRow($info['action_reference_new_row']); - $trigger->setCreated($info['created']); - - return $trigger; - } - - /** - * Prepare data hierarchy - * - * @param string $type - * @param string $key ... - */ - protected function prepareDataHierarchy($type) - { - $data = &$this->data; - foreach (func_get_args() as $key) { - if (!isset($data[$key])) { - $data[$key] = array(); - } - $data = &$data[$key]; - } - } - - /** - * Load schema data - */ - protected function loadSchemaData() - { - } - - /** - * Load table name data - * - * @param string $schema - */ - protected function loadTableNameData($schema) - { - if (isset($this->data['table_names'][$schema])) { - return; - } - - $this->prepareDataHierarchy('table_names', $schema); - } - - /** - * Load column data - * - * @param string $table - * @param string $schema - */ - protected function loadColumnData($table, $schema) - { - if (isset($this->data['columns'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('columns', $schema, $table); - } - - /** - * Load constraint data - * - * @param string $table - * @param string $schema - */ - protected function loadConstraintData($table, $schema) - { - if (isset($this->data['constraints'][$schema])) { - return; - } - - $this->prepareDataHierarchy('constraints', $schema); - } - - /** - * Load constraint data keys - * - * @param string $schema - */ - protected function loadConstraintDataKeys($schema) - { - if (isset($this->data['constraint_keys'][$schema])) { - return; - } - - $this->prepareDataHierarchy('constraint_keys', $schema); - } - - /** - * Load constraint references - * - * @param string $table - * @param string $schema - */ - protected function loadConstraintReferences($table, $schema) - { - if (isset($this->data['constraint_references'][$schema])) { - return; - } - - $this->prepareDataHierarchy('constraint_references', $schema); - } - - /** - * Load trigger data - * - * @param string $schema - */ - protected function loadTriggerData($schema) - { - if (isset($this->data['triggers'][$schema])) { - return; - } - - $this->prepareDataHierarchy('triggers', $schema); - } -} diff --git a/library/Zend/Db/Metadata/Source/MysqlMetadata.php b/library/Zend/Db/Metadata/Source/MysqlMetadata.php deleted file mode 100755 index ac9642f9c..000000000 --- a/library/Zend/Db/Metadata/Source/MysqlMetadata.php +++ /dev/null @@ -1,493 +0,0 @@ -data['schemas'])) { - return; - } - $this->prepareDataHierarchy('schemas'); - - $p = $this->adapter->getPlatform(); - - $sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME') - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'SCHEMATA')) - . ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME') - . ' != \'INFORMATION_SCHEMA\''; - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $schemas = array(); - foreach ($results->toArray() as $row) { - $schemas[] = $row['SCHEMA_NAME']; - } - - $this->data['schemas'] = $schemas; - } - - protected function loadTableNameData($schema) - { - if (isset($this->data['table_names'][$schema])) { - return; - } - $this->prepareDataHierarchy('table_names', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('T', 'TABLE_NAME'), - array('T', 'TABLE_TYPE'), - array('V', 'VIEW_DEFINITION'), - array('V', 'CHECK_OPTION'), - array('V', 'IS_UPDATABLE'), - ); - - array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . 'T' - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'VIEWS')) . ' V' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('V', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('V', 'TABLE_NAME')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $tables = array(); - foreach ($results->toArray() as $row) { - $tables[$row['TABLE_NAME']] = array( - 'table_type' => $row['TABLE_TYPE'], - 'view_definition' => $row['VIEW_DEFINITION'], - 'check_option' => $row['CHECK_OPTION'], - 'is_updatable' => ('YES' == $row['IS_UPDATABLE']), - ); - } - - $this->data['table_names'][$schema] = $tables; - } - - protected function loadColumnData($table, $schema) - { - if (isset($this->data['columns'][$schema][$table])) { - return; - } - $this->prepareDataHierarchy('columns', $schema, $table); - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('C', 'ORDINAL_POSITION'), - array('C', 'COLUMN_DEFAULT'), - array('C', 'IS_NULLABLE'), - array('C', 'DATA_TYPE'), - array('C', 'CHARACTER_MAXIMUM_LENGTH'), - array('C', 'CHARACTER_OCTET_LENGTH'), - array('C', 'NUMERIC_PRECISION'), - array('C', 'NUMERIC_SCALE'), - array('C', 'COLUMN_NAME'), - array('C', 'COLUMN_TYPE'), - ); - - array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . 'T' - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'COLUMNS')) . 'C' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('C', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('C', 'TABLE_NAME')) - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')' - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteTrustedValue($table); - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $columns = array(); - foreach ($results->toArray() as $row) { - $erratas = array(); - $matches = array(); - if (preg_match('/^(?:enum|set)\((.+)\)$/i', $row['COLUMN_TYPE'], $matches)) { - $permittedValues = $matches[1]; - if (preg_match_all("/\\s*'((?:[^']++|'')*+)'\\s*(?:,|\$)/", $permittedValues, $matches, PREG_PATTERN_ORDER)) { - $permittedValues = str_replace("''", "'", $matches[1]); - } else { - $permittedValues = array($permittedValues); - } - $erratas['permitted_values'] = $permittedValues; - } - $columns[$row['COLUMN_NAME']] = array( - 'ordinal_position' => $row['ORDINAL_POSITION'], - 'column_default' => $row['COLUMN_DEFAULT'], - 'is_nullable' => ('YES' == $row['IS_NULLABLE']), - 'data_type' => $row['DATA_TYPE'], - 'character_maximum_length' => $row['CHARACTER_MAXIMUM_LENGTH'], - 'character_octet_length' => $row['CHARACTER_OCTET_LENGTH'], - 'numeric_precision' => $row['NUMERIC_PRECISION'], - 'numeric_scale' => $row['NUMERIC_SCALE'], - 'numeric_unsigned' => (false !== strpos($row['COLUMN_TYPE'], 'unsigned')), - 'erratas' => $erratas, - ); - } - - $this->data['columns'][$schema][$table] = $columns; - } - - protected function loadConstraintData($table, $schema) - { - if (isset($this->data['constraints'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('constraints', $schema, $table); - - $isColumns = array( - array('T', 'TABLE_NAME'), - array('TC', 'CONSTRAINT_NAME'), - array('TC', 'CONSTRAINT_TYPE'), - array('KCU', 'COLUMN_NAME'), - array('RC', 'MATCH_OPTION'), - array('RC', 'UPDATE_RULE'), - array('RC', 'DELETE_RULE'), - array('KCU', 'REFERENCED_TABLE_SCHEMA'), - array('KCU', 'REFERENCED_TABLE_NAME'), - array('KCU', 'REFERENCED_COLUMN_NAME'), - ); - - $p = $this->adapter->getPlatform(); - - array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifierChain($c); - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . ' T' - - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS')) . ' TC' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('TC', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('TC', 'TABLE_NAME')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE')) . ' KCU' - . ' ON ' . $p->quoteIdentifierChain(array('TC', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_NAME')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'CONSTRAINT_NAME')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS')) . ' RC' - . ' ON ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_NAME')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteTrustedValue($table) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_TYPE')) - . " WHEN 'PRIMARY KEY' THEN 1" - . " WHEN 'UNIQUE' THEN 2" - . " WHEN 'FOREIGN KEY' THEN 3" - . " ELSE 4 END" - - . ', ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ', ' . $p->quoteIdentifierChain(array('KCU', 'ORDINAL_POSITION')); - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $realName = null; - $constraints = array(); - foreach ($results->toArray() as $row) { - if ($row['CONSTRAINT_NAME'] !== $realName) { - $realName = $row['CONSTRAINT_NAME']; - $isFK = ('FOREIGN KEY' == $row['CONSTRAINT_TYPE']); - if ($isFK) { - $name = $realName; - } else { - $name = '_zf_' . $row['TABLE_NAME'] . '_' . $realName; - } - $constraints[$name] = array( - 'constraint_name' => $name, - 'constraint_type' => $row['CONSTRAINT_TYPE'], - 'table_name' => $row['TABLE_NAME'], - 'columns' => array(), - ); - if ($isFK) { - $constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA']; - $constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME']; - $constraints[$name]['referenced_columns'] = array(); - $constraints[$name]['match_option'] = $row['MATCH_OPTION']; - $constraints[$name]['update_rule'] = $row['UPDATE_RULE']; - $constraints[$name]['delete_rule'] = $row['DELETE_RULE']; - } - } - $constraints[$name]['columns'][] = $row['COLUMN_NAME']; - if ($isFK) { - $constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME']; - } - } - - $this->data['constraints'][$schema][$table] = $constraints; - } - - protected function loadConstraintDataNames($schema) - { - if (isset($this->data['constraint_names'][$schema])) { - return; - } - - $this->prepareDataHierarchy('constraint_names', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('TC', 'TABLE_NAME'), - array('TC', 'CONSTRAINT_NAME'), - array('TC', 'CONSTRAINT_TYPE'), - ); - - array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifierChain($c); - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . 'T' - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS')) . 'TC' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('TC', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('TC', 'TABLE_NAME')) - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $data = array(); - foreach ($results->toArray() as $row) { - $data[] = array_change_key_case($row, CASE_LOWER); - } - - $this->data['constraint_names'][$schema] = $data; - } - - protected function loadConstraintDataKeys($schema) - { - if (isset($this->data['constraint_keys'][$schema])) { - return; - } - - $this->prepareDataHierarchy('constraint_keys', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('T', 'TABLE_NAME'), - array('KCU', 'CONSTRAINT_NAME'), - array('KCU', 'COLUMN_NAME'), - array('KCU', 'ORDINAL_POSITION'), - ); - - array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifierChain($c); - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . 'T' - - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE')) . 'KCU' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_NAME')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $data = array(); - foreach ($results->toArray() as $row) { - $data[] = array_change_key_case($row, CASE_LOWER); - } - - $this->data['constraint_keys'][$schema] = $data; - } - - protected function loadConstraintReferences($table, $schema) - { - parent::loadConstraintReferences($table, $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('RC', 'TABLE_NAME'), - array('RC', 'CONSTRAINT_NAME'), - array('RC', 'UPDATE_RULE'), - array('RC', 'DELETE_RULE'), - array('KCU', 'REFERENCED_TABLE_SCHEMA'), - array('KCU', 'REFERENCED_TABLE_NAME'), - array('KCU', 'REFERENCED_COLUMN_NAME'), - ); - - array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifierChain($c); - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . 'FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . 'T' - - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS')) . 'RC' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('RC', 'TABLE_NAME')) - - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE')) . 'KCU' - . ' ON ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('RC', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_NAME')) - . ' AND ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'CONSTRAINT_NAME')) - - . 'WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $data = array(); - foreach ($results->toArray() as $row) { - $data[] = array_change_key_case($row, CASE_LOWER); - } - - $this->data['constraint_references'][$schema] = $data; - } - - protected function loadTriggerData($schema) - { - if (isset($this->data['triggers'][$schema])) { - return; - } - - $this->prepareDataHierarchy('triggers', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( -// 'TRIGGER_CATALOG', -// 'TRIGGER_SCHEMA', - 'TRIGGER_NAME', - 'EVENT_MANIPULATION', - 'EVENT_OBJECT_CATALOG', - 'EVENT_OBJECT_SCHEMA', - 'EVENT_OBJECT_TABLE', - 'ACTION_ORDER', - 'ACTION_CONDITION', - 'ACTION_STATEMENT', - 'ACTION_ORIENTATION', - 'ACTION_TIMING', - 'ACTION_REFERENCE_OLD_TABLE', - 'ACTION_REFERENCE_NEW_TABLE', - 'ACTION_REFERENCE_OLD_ROW', - 'ACTION_REFERENCE_NEW_ROW', - 'CREATED', - ); - - array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifier($c); - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TRIGGERS')) - . ' WHERE '; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= $p->quoteIdentifier('TRIGGER_SCHEMA') - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= $p->quoteIdentifier('TRIGGER_SCHEMA') - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $data = array(); - foreach ($results->toArray() as $row) { - $row = array_change_key_case($row, CASE_LOWER); - if (null !== $row['created']) { - $row['created'] = new \DateTime($row['created']); - } - $data[$row['trigger_name']] = $row; - } - - $this->data['triggers'][$schema] = $data; - } -} diff --git a/library/Zend/Db/Metadata/Source/OracleMetadata.php b/library/Zend/Db/Metadata/Source/OracleMetadata.php deleted file mode 100755 index 44deac13d..000000000 --- a/library/Zend/Db/Metadata/Source/OracleMetadata.php +++ /dev/null @@ -1,256 +0,0 @@ - 'CHECK', - 'P' => 'PRIMARY KEY', - 'R' => 'FOREIGN_KEY' - ); - - /** - * {@inheritdoc} - * @see \Zend\Db\Metadata\Source\AbstractSource::loadColumnData() - */ - protected function loadColumnData($table, $schema) - { - if (isset($this->data['columns'][$schema][$table])) { - return; - } - - $isColumns = array( - 'COLUMN_ID', - 'COLUMN_NAME', - 'DATA_DEFAULT', - 'NULLABLE', - 'DATA_TYPE', - 'DATA_LENGTH', - 'DATA_PRECISION', - 'DATA_SCALE' - ); - - $this->prepareDataHierarchy('columns', $schema, $table); - $parameters = array( - ':ownername' => $schema, - ':tablename' => $table - ); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM all_tab_columns' - . ' WHERE owner = :ownername AND table_name = :tablename'; - - $result = $this->adapter->query($sql)->execute($parameters); - $columns = array(); - - foreach ($result as $row) { - $columns[$row['COLUMN_NAME']] = array( - 'ordinal_position' => $row['COLUMN_ID'], - 'column_default' => $row['DATA_DEFAULT'], - 'is_nullable' => ('Y' == $row['NULLABLE']), - 'data_type' => $row['DATA_TYPE'], - 'character_maximum_length' => $row['DATA_LENGTH'], - 'character_octet_length' => null, - 'numeric_precision' => $row['DATA_PRECISION'], - 'numeric_scale' => $row['DATA_SCALE'], - 'numeric_unsigned' => false, - 'erratas' => array(), - ); - } - - $this->data['columns'][$schema][$table] = $columns; - return $this; - } - - /** - * Constraint type - * - * @param string $type - * @return string - */ - protected function getConstraintType($type) - { - if (isset($this->constraintTypeMap[$type])) { - return $this->constraintTypeMap[$type]; - } - - return $type; - } - - /** - * {@inheritdoc} - * @see \Zend\Db\Metadata\Source\AbstractSource::loadConstraintData() - */ - protected function loadConstraintData($table, $schema) - { - if (isset($this->data['constraints'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('constraints', $schema, $table); - $sql = ' - SELECT - ac.owner, - ac.constraint_name, - ac.constraint_type, - ac.search_condition check_clause, - ac.table_name, - ac.delete_rule, - cc1.column_name, - cc2.table_name as ref_table, - cc2.column_name as ref_column, - cc2.owner as ref_owner - FROM all_constraints ac - INNER JOIN all_cons_columns cc1 - ON cc1.constraint_name = ac.constraint_name - LEFT JOIN all_cons_columns cc2 - ON cc2.constraint_name = ac.r_constraint_name - AND cc2.position = cc1.position - - WHERE - ac.owner = :schema AND ac.table_name = :table - - ORDER BY ac.constraint_name; - '; - - $parameters = array( - ':schema' => $schema, - ':table' => $table - ); - - $results = $this->adapter->query($sql)->execute($parameters); - $isFK = false; - $name = null; - $constraints = array(); - - foreach ($results as $row) { - if ($row['CONSTRAINT_NAME'] !== $name) { - $name = $row['CONSTRAINT_NAME']; - $constraints[$name] = array( - 'constraint_name' => $name, - 'constraint_type' => $this->getConstraintType($row['CONSTRAINT_TYPE']), - 'table_name' => $row['TABLE_NAME'], - ); - - if ('C' == $row['CONSTRAINT_TYPE']) { - $constraints[$name]['CHECK_CLAUSE'] = $row['CHECK_CLAUSE']; - continue; - } - - $constraints[$name]['columns'] = array(); - - $isFK = ('R' == $row['CONSTRAINT_TYPE']); - if ($isFK) { - $constraints[$name]['referenced_table_schema'] = $row['REF_OWNER']; - $constraints[$name]['referenced_table_name'] = $row['REF_TABLE']; - $constraints[$name]['referenced_columns'] = array(); - $constraints[$name]['match_option'] = 'NONE'; - $constraints[$name]['update_rule'] = null; - $constraints[$name]['delete_rule'] = $row['DELETE_RULE']; - } - } - - $constraints[$name]['columns'][] = $row['COLUMN_NAME']; - if ($isFK) { - $constraints[$name]['referenced_columns'][] = $row['REF_COLUMN']; - } - } - - return $this; - } - - /** - * {@inheritdoc} - * @see \Zend\Db\Metadata\Source\AbstractSource::loadSchemaData() - */ - protected function loadSchemaData() - { - if (isset($this->data['schemas'])) { - return; - } - - $this->prepareDataHierarchy('schemas'); - $sql = 'SELECT USERNAME FROM ALL_USERS'; - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $schemas = array(); - foreach ($results->toArray() as $row) { - $schemas[] = $row['USERNAME']; - } - - $this->data['schemas'] = $schemas; - } - - /** - * {@inheritdoc} - * @see \Zend\Db\Metadata\Source\AbstractSource::loadTableNameData() - */ - protected function loadTableNameData($schema) - { - if (isset($this->data['table_names'][$schema])) { - return $this; - } - - $this->prepareDataHierarchy('table_names', $schema); - $tables = array(); - - // Tables - $bind = array(':OWNER' => strtoupper($schema)); - $result = $this->adapter->query('SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER=:OWNER')->execute($bind); - - foreach ($result as $row) { - $tables[$row['TABLE_NAME']] = array( - 'table_type' => 'BASE TABLE', - 'view_definition' => null, - 'check_option' => null, - 'is_updatable' => false, - ); - } - - // Views - $result = $this->adapter->query('SELECT VIEW_NAME, TEXT FROM ALL_VIEWS WHERE OWNER=:OWNER', $bind); - foreach ($result as $row) { - $tables[$row['VIEW_NAME']] = array( - 'table_type' => 'VIEW', - 'view_definition' => null, - 'check_option' => 'NONE', - 'is_updatable' => false, - ); - } - - $this->data['table_names'][$schema] = $tables; - return $this; - } - - /** - * FIXME: load trigger data - * - * {@inheritdoc} - * - * @see \Zend\Db\Metadata\Source\AbstractSource::loadTriggerData() - */ - protected function loadTriggerData($schema) - { - if (isset($this->data['triggers'][$schema])) { - return; - } - - $this->prepareDataHierarchy('triggers', $schema); - } -} diff --git a/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php b/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php deleted file mode 100755 index bb274487d..000000000 --- a/library/Zend/Db/Metadata/Source/PostgresqlMetadata.php +++ /dev/null @@ -1,345 +0,0 @@ -data['schemas'])) { - return; - } - $this->prepareDataHierarchy('schemas'); - - $p = $this->adapter->getPlatform(); - - $sql = 'SELECT ' . $p->quoteIdentifier('schema_name') - . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'schemata')) - . ' WHERE ' . $p->quoteIdentifier('schema_name') - . ' != \'information_schema\'' - . ' AND ' . $p->quoteIdentifier('schema_name') . " NOT LIKE 'pg_%'"; - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $schemas = array(); - foreach ($results->toArray() as $row) { - $schemas[] = $row['schema_name']; - } - - $this->data['schemas'] = $schemas; - } - - protected function loadTableNameData($schema) - { - if (isset($this->data['table_names'][$schema])) { - return; - } - $this->prepareDataHierarchy('table_names', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('t', 'table_name'), - array('t', 'table_type'), - array('v', 'view_definition'), - array('v', 'check_option'), - array('v', 'is_updatable'), - ); - - array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'tables')) . ' t' - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'views')) . ' v' - . ' ON ' . $p->quoteIdentifierChain(array('t', 'table_schema')) - . ' = ' . $p->quoteIdentifierChain(array('v', 'table_schema')) - . ' AND ' . $p->quoteIdentifierChain(array('t', 'table_name')) - . ' = ' . $p->quoteIdentifierChain(array('v', 'table_name')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('t', 'table_type')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema')) - . ' != \'information_schema\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $tables = array(); - foreach ($results->toArray() as $row) { - $tables[$row['table_name']] = array( - 'table_type' => $row['table_type'], - 'view_definition' => $row['view_definition'], - 'check_option' => $row['check_option'], - 'is_updatable' => ('YES' == $row['is_updatable']), - ); - } - - $this->data['table_names'][$schema] = $tables; - } - - protected function loadColumnData($table, $schema) - { - if (isset($this->data['columns'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('columns', $schema, $table); - - $platform = $this->adapter->getPlatform(); - - $isColumns = array( - 'table_name', - 'column_name', - 'ordinal_position', - 'column_default', - 'is_nullable', - 'data_type', - 'character_maximum_length', - 'character_octet_length', - 'numeric_precision', - 'numeric_scale', - ); - - array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $platform->quoteIdentifier('information_schema') - . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('columns') - . ' WHERE ' . $platform->quoteIdentifier('table_schema') - . ' != \'information\'' - . ' AND ' . $platform->quoteIdentifier('table_name') - . ' = ' . $platform->quoteTrustedValue($table); - - if ($schema != '__DEFAULT_SCHEMA__') { - $sql .= ' AND ' . $platform->quoteIdentifier('table_schema') - . ' = ' . $platform->quoteTrustedValue($schema); - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $columns = array(); - foreach ($results->toArray() as $row) { - $columns[$row['column_name']] = array( - 'ordinal_position' => $row['ordinal_position'], - 'column_default' => $row['column_default'], - 'is_nullable' => ('YES' == $row['is_nullable']), - 'data_type' => $row['data_type'], - 'character_maximum_length' => $row['character_maximum_length'], - 'character_octet_length' => $row['character_octet_length'], - 'numeric_precision' => $row['numeric_precision'], - 'numeric_scale' => $row['numeric_scale'], - 'numeric_unsigned' => null, - 'erratas' => array(), - ); - } - - $this->data['columns'][$schema][$table] = $columns; - } - - protected function loadConstraintData($table, $schema) - { - if (isset($this->data['constraints'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('constraints', $schema, $table); - - $isColumns = array( - array('t', 'table_name'), - array('tc', 'constraint_name'), - array('tc', 'constraint_type'), - array('kcu', 'column_name'), - array('cc', 'check_clause'), - array('rc', 'match_option'), - array('rc', 'update_rule'), - array('rc', 'delete_rule'), - array('referenced_table_schema' => 'kcu2', 'table_schema'), - array('referenced_table_name' => 'kcu2', 'table_name'), - array('referenced_column_name' => 'kcu2', 'column_name'), - ); - - $p = $this->adapter->getPlatform(); - - array_walk($isColumns, function (&$c) use ($p) { - $alias = key($c); - $c = $p->quoteIdentifierChain($c); - if (is_string($alias)) { - $c .= ' ' . $p->quoteIdentifier($alias); - } - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'tables')) . ' t' - - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'table_constraints')) . ' tc' - . ' ON ' . $p->quoteIdentifierChain(array('t', 'table_schema')) - . ' = ' . $p->quoteIdentifierChain(array('tc', 'table_schema')) - . ' AND ' . $p->quoteIdentifierChain(array('t', 'table_name')) - . ' = ' . $p->quoteIdentifierChain(array('tc', 'table_name')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'key_column_usage')) . ' kcu' - . ' ON ' . $p->quoteIdentifierChain(array('tc', 'table_schema')) - . ' = ' . $p->quoteIdentifierChain(array('kcu', 'table_schema')) - . ' AND ' . $p->quoteIdentifierChain(array('tc', 'table_name')) - . ' = ' . $p->quoteIdentifierChain(array('kcu', 'table_name')) - . ' AND ' . $p->quoteIdentifierChain(array('tc', 'constraint_name')) - . ' = ' . $p->quoteIdentifierChain(array('kcu', 'constraint_name')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'check_constraints')) . ' cc' - . ' ON ' . $p->quoteIdentifierChain(array('tc', 'constraint_schema')) - . ' = ' . $p->quoteIdentifierChain(array('cc', 'constraint_schema')) - . ' AND ' . $p->quoteIdentifierChain(array('tc', 'constraint_name')) - . ' = ' . $p->quoteIdentifierChain(array('cc', 'constraint_name')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'referential_constraints')) . ' rc' - . ' ON ' . $p->quoteIdentifierChain(array('tc', 'constraint_schema')) - . ' = ' . $p->quoteIdentifierChain(array('rc', 'constraint_schema')) - . ' AND ' . $p->quoteIdentifierChain(array('tc', 'constraint_name')) - . ' = ' . $p->quoteIdentifierChain(array('rc', 'constraint_name')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'key_column_usage')) . ' kcu2' - . ' ON ' . $p->quoteIdentifierChain(array('rc', 'unique_constraint_schema')) - . ' = ' . $p->quoteIdentifierChain(array('kcu2', 'constraint_schema')) - . ' AND ' . $p->quoteIdentifierChain(array('rc', 'unique_constraint_name')) - . ' = ' . $p->quoteIdentifierChain(array('kcu2', 'constraint_name')) - . ' AND ' . $p->quoteIdentifierChain(array('kcu', 'position_in_unique_constraint')) - . ' = ' . $p->quoteIdentifierChain(array('kcu2', 'ordinal_position')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('t', 'table_name')) - . ' = ' . $p->quoteTrustedValue($table) - . ' AND ' . $p->quoteIdentifierChain(array('t', 'table_type')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema')) - . ' != \'information_schema\''; - } - - $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('tc', 'constraint_type')) - . " WHEN 'PRIMARY KEY' THEN 1" - . " WHEN 'UNIQUE' THEN 2" - . " WHEN 'FOREIGN KEY' THEN 3" - . " WHEN 'CHECK' THEN 4" - . " ELSE 5 END" - . ', ' . $p->quoteIdentifierChain(array('tc', 'constraint_name')) - . ', ' . $p->quoteIdentifierChain(array('kcu', 'ordinal_position')); - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $name = null; - $constraints = array(); - foreach ($results->toArray() as $row) { - if ($row['constraint_name'] !== $name) { - $name = $row['constraint_name']; - $constraints[$name] = array( - 'constraint_name' => $name, - 'constraint_type' => $row['constraint_type'], - 'table_name' => $row['table_name'], - ); - if ('CHECK' == $row['constraint_type']) { - $constraints[$name]['check_clause'] = $row['check_clause']; - continue; - } - $constraints[$name]['columns'] = array(); - $isFK = ('FOREIGN KEY' == $row['constraint_type']); - if ($isFK) { - $constraints[$name]['referenced_table_schema'] = $row['referenced_table_schema']; - $constraints[$name]['referenced_table_name'] = $row['referenced_table_name']; - $constraints[$name]['referenced_columns'] = array(); - $constraints[$name]['match_option'] = $row['match_option']; - $constraints[$name]['update_rule'] = $row['update_rule']; - $constraints[$name]['delete_rule'] = $row['delete_rule']; - } - } - $constraints[$name]['columns'][] = $row['column_name']; - if ($isFK) { - $constraints[$name]['referenced_columns'][] = $row['referenced_column_name']; - } - } - - $this->data['constraints'][$schema][$table] = $constraints; - } - - protected function loadTriggerData($schema) - { - if (isset($this->data['triggers'][$schema])) { - return; - } - - $this->prepareDataHierarchy('triggers', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - 'trigger_name', - 'event_manipulation', - 'event_object_catalog', - 'event_object_schema', - 'event_object_table', - 'action_order', - 'action_condition', - 'action_statement', - 'action_orientation', - array('action_timing' => 'condition_timing'), - array('action_reference_old_table' => 'condition_reference_old_table'), - array('action_reference_new_table' => 'condition_reference_new_table'), - 'created', - ); - - array_walk($isColumns, function (&$c) use ($p) { - if (is_array($c)) { - $alias = key($c); - $c = $p->quoteIdentifierChain($c); - if (is_string($alias)) { - $c .= ' ' . $p->quoteIdentifier($alias); - } - } else { - $c = $p->quoteIdentifier($c); - } - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'triggers')) - . ' WHERE '; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= $p->quoteIdentifier('trigger_schema') - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= $p->quoteIdentifier('trigger_schema') - . ' != \'information_schema\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $data = array(); - foreach ($results->toArray() as $row) { - $row = array_change_key_case($row, CASE_LOWER); - $row['action_reference_old_row'] = 'OLD'; - $row['action_reference_new_row'] = 'NEW'; - if (null !== $row['created']) { - $row['created'] = new \DateTime($row['created']); - } - $data[$row['trigger_name']] = $row; - } - - $this->data['triggers'][$schema] = $data; - } -} diff --git a/library/Zend/Db/Metadata/Source/SqlServerMetadata.php b/library/Zend/Db/Metadata/Source/SqlServerMetadata.php deleted file mode 100755 index b2b3e76fa..000000000 --- a/library/Zend/Db/Metadata/Source/SqlServerMetadata.php +++ /dev/null @@ -1,341 +0,0 @@ -data['schemas'])) { - return; - } - $this->prepareDataHierarchy('schemas'); - - $p = $this->adapter->getPlatform(); - - $sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME') - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'SCHEMATA')) - . ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME') - . ' != \'INFORMATION_SCHEMA\''; - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $schemas = array(); - foreach ($results->toArray() as $row) { - $schemas[] = $row['SCHEMA_NAME']; - } - - $this->data['schemas'] = $schemas; - } - - protected function loadTableNameData($schema) - { - if (isset($this->data['table_names'][$schema])) { - return; - } - $this->prepareDataHierarchy('table_names', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('T', 'TABLE_NAME'), - array('T', 'TABLE_TYPE'), - array('V', 'VIEW_DEFINITION'), - array('V', 'CHECK_OPTION'), - array('V', 'IS_UPDATABLE'), - ); - - array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . ' t' - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'VIEWS')) . ' v' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('V', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('V', 'TABLE_NAME')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $tables = array(); - foreach ($results->toArray() as $row) { - $tables[$row['TABLE_NAME']] = array( - 'table_type' => $row['TABLE_TYPE'], - 'view_definition' => $row['VIEW_DEFINITION'], - 'check_option' => $row['CHECK_OPTION'], - 'is_updatable' => ('YES' == $row['IS_UPDATABLE']), - ); - } - - $this->data['table_names'][$schema] = $tables; - } - - protected function loadColumnData($table, $schema) - { - if (isset($this->data['columns'][$schema][$table])) { - return; - } - $this->prepareDataHierarchy('columns', $schema, $table); - $p = $this->adapter->getPlatform(); - - $isColumns = array( - array('C', 'ORDINAL_POSITION'), - array('C', 'COLUMN_DEFAULT'), - array('C', 'IS_NULLABLE'), - array('C', 'DATA_TYPE'), - array('C', 'CHARACTER_MAXIMUM_LENGTH'), - array('C', 'CHARACTER_OCTET_LENGTH'), - array('C', 'NUMERIC_PRECISION'), - array('C', 'NUMERIC_SCALE'), - array('C', 'COLUMN_NAME'), - ); - - array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . 'T' - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'COLUMNS')) . 'C' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('C', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('C', 'TABLE_NAME')) - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')' - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteTrustedValue($table); - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $columns = array(); - foreach ($results->toArray() as $row) { - $columns[$row['COLUMN_NAME']] = array( - 'ordinal_position' => $row['ORDINAL_POSITION'], - 'column_default' => $row['COLUMN_DEFAULT'], - 'is_nullable' => ('YES' == $row['IS_NULLABLE']), - 'data_type' => $row['DATA_TYPE'], - 'character_maximum_length' => $row['CHARACTER_MAXIMUM_LENGTH'], - 'character_octet_length' => $row['CHARACTER_OCTET_LENGTH'], - 'numeric_precision' => $row['NUMERIC_PRECISION'], - 'numeric_scale' => $row['NUMERIC_SCALE'], - 'numeric_unsigned' => null, - 'erratas' => array(), - ); - } - - $this->data['columns'][$schema][$table] = $columns; - } - - protected function loadConstraintData($table, $schema) - { - if (isset($this->data['constraints'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('constraints', $schema, $table); - - $isColumns = array( - array('T', 'TABLE_NAME'), - array('TC', 'CONSTRAINT_NAME'), - array('TC', 'CONSTRAINT_TYPE'), - array('KCU', 'COLUMN_NAME'), - array('CC', 'CHECK_CLAUSE'), - array('RC', 'MATCH_OPTION'), - array('RC', 'UPDATE_RULE'), - array('RC', 'DELETE_RULE'), - array('REFERENCED_TABLE_SCHEMA' => 'KCU2', 'TABLE_SCHEMA'), - array('REFERENCED_TABLE_NAME' => 'KCU2', 'TABLE_NAME'), - array('REFERENCED_COLUMN_NAME' => 'KCU2', 'COLUMN_NAME'), - ); - - $p = $this->adapter->getPlatform(); - - array_walk($isColumns, function (&$c) use ($p) { - $alias = key($c); - $c = $p->quoteIdentifierChain($c); - if (is_string($alias)) { - $c .= ' ' . $p->quoteIdentifier($alias); - } - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLES')) . ' T' - - . ' INNER JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS')) . ' TC' - . ' ON ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('TC', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('TC', 'TABLE_NAME')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE')) . ' KCU' - . ' ON ' . $p->quoteIdentifierChain(array('TC', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'TABLE_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'TABLE_NAME')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU', 'CONSTRAINT_NAME')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'CHECK_CONSTRAINTS')) . ' CC' - . ' ON ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('CC', 'CONSTRAINT_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('CC', 'CONSTRAINT_NAME')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS')) . ' RC' - . ' ON ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('RC', 'CONSTRAINT_NAME')) - - . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE')) . ' KCU2' - . ' ON ' . $p->quoteIdentifierChain(array('RC', 'UNIQUE_CONSTRAINT_SCHEMA')) - . ' = ' . $p->quoteIdentifierChain(array('KCU2', 'CONSTRAINT_SCHEMA')) - . ' AND ' . $p->quoteIdentifierChain(array('RC', 'UNIQUE_CONSTRAINT_NAME')) - . ' = ' . $p->quoteIdentifierChain(array('KCU2', 'CONSTRAINT_NAME')) - . ' AND ' . $p->quoteIdentifierChain(array('KCU', 'ORDINAL_POSITION')) - . ' = ' . $p->quoteIdentifierChain(array('KCU2', 'ORDINAL_POSITION')) - - . ' WHERE ' . $p->quoteIdentifierChain(array('T', 'TABLE_NAME')) - . ' = ' . $p->quoteTrustedValue($table) - . ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_TYPE')) - . ' IN (\'BASE TABLE\', \'VIEW\')'; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= ' AND ' . $p->quoteIdentifierChain(array('T', 'TABLE_SCHEMA')) - . ' != \'INFORMATION_SCHEMA\''; - } - - $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_TYPE')) - . " WHEN 'PRIMARY KEY' THEN 1" - . " WHEN 'UNIQUE' THEN 2" - . " WHEN 'FOREIGN KEY' THEN 3" - . " WHEN 'CHECK' THEN 4" - . " ELSE 5 END" - . ', ' . $p->quoteIdentifierChain(array('TC', 'CONSTRAINT_NAME')) - . ', ' . $p->quoteIdentifierChain(array('KCU', 'ORDINAL_POSITION')); - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $name = null; - $constraints = array(); - $isFK = false; - foreach ($results->toArray() as $row) { - if ($row['CONSTRAINT_NAME'] !== $name) { - $name = $row['CONSTRAINT_NAME']; - $constraints[$name] = array( - 'constraint_name' => $name, - 'constraint_type' => $row['CONSTRAINT_TYPE'], - 'table_name' => $row['TABLE_NAME'], - ); - if ('CHECK' == $row['CONSTRAINT_TYPE']) { - $constraints[$name]['check_clause'] = $row['CHECK_CLAUSE']; - continue; - } - $constraints[$name]['columns'] = array(); - $isFK = ('FOREIGN KEY' == $row['CONSTRAINT_TYPE']); - if ($isFK) { - $constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA']; - $constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME']; - $constraints[$name]['referenced_columns'] = array(); - $constraints[$name]['match_option'] = $row['MATCH_OPTION']; - $constraints[$name]['update_rule'] = $row['UPDATE_RULE']; - $constraints[$name]['delete_rule'] = $row['DELETE_RULE']; - } - } - $constraints[$name]['columns'][] = $row['COLUMN_NAME']; - if ($isFK) { - $constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME']; - } - } - - $this->data['constraints'][$schema][$table] = $constraints; - } - - protected function loadTriggerData($schema) - { - if (isset($this->data['triggers'][$schema])) { - return; - } - - $this->prepareDataHierarchy('triggers', $schema); - - $p = $this->adapter->getPlatform(); - - $isColumns = array( - 'TRIGGER_NAME', - 'EVENT_MANIPULATION', - 'EVENT_OBJECT_CATALOG', - 'EVENT_OBJECT_SCHEMA', - 'EVENT_OBJECT_TABLE', - 'ACTION_ORDER', - 'ACTION_CONDITION', - 'ACTION_STATEMENT', - 'ACTION_ORIENTATION', - 'ACTION_TIMING', - 'ACTION_REFERENCE_OLD_TABLE', - 'ACTION_REFERENCE_NEW_TABLE', - 'ACTION_REFERENCE_OLD_ROW', - 'ACTION_REFERENCE_NEW_ROW', - 'CREATED', - ); - - array_walk($isColumns, function (&$c) use ($p) { - $c = $p->quoteIdentifier($c); - }); - - $sql = 'SELECT ' . implode(', ', $isColumns) - . ' FROM ' . $p->quoteIdentifierChain(array('INFORMATION_SCHEMA', 'TRIGGERS')) - . ' WHERE '; - - if ($schema != self::DEFAULT_SCHEMA) { - $sql .= $p->quoteIdentifier('TRIGGER_SCHEMA') - . ' = ' . $p->quoteTrustedValue($schema); - } else { - $sql .= $p->quoteIdentifier('TRIGGER_SCHEMA') - . ' != \'INFORMATION_SCHEMA\''; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - - $data = array(); - foreach ($results->toArray() as $row) { - $row = array_change_key_case($row, CASE_LOWER); - if (null !== $row['created']) { - $row['created'] = new \DateTime($row['created']); - } - $data[$row['trigger_name']] = $row; - } - - $this->data['triggers'][$schema] = $data; - } -} diff --git a/library/Zend/Db/Metadata/Source/SqliteMetadata.php b/library/Zend/Db/Metadata/Source/SqliteMetadata.php deleted file mode 100755 index f3869af8c..000000000 --- a/library/Zend/Db/Metadata/Source/SqliteMetadata.php +++ /dev/null @@ -1,390 +0,0 @@ -data['schemas'])) { - return; - } - $this->prepareDataHierarchy('schemas'); - - $results = $this->fetchPragma('database_list'); - foreach ($results as $row) { - $schemas[] = $row['name']; - } - $this->data['schemas'] = $schemas; - } - - protected function loadTableNameData($schema) - { - if (isset($this->data['table_names'][$schema])) { - return; - } - $this->prepareDataHierarchy('table_names', $schema); - - // FEATURE: Filename? - - $p = $this->adapter->getPlatform(); - - $sql = 'SELECT "name", "type", "sql" FROM ' . $p->quoteIdentifierChain(array($schema, 'sqlite_master')) - . ' WHERE "type" IN (\'table\',\'view\') AND "name" NOT LIKE \'sqlite_%\''; - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $tables = array(); - foreach ($results->toArray() as $row) { - if ('table' == $row['type']) { - $table = array( - 'table_type' => 'BASE TABLE', - 'view_definition' => null, // VIEW only - 'check_option' => null, // VIEW only - 'is_updatable' => null, // VIEW only - ); - } else { - $table = array( - 'table_type' => 'VIEW', - 'view_definition' => null, - 'check_option' => 'NONE', - 'is_updatable' => false, - ); - - // Parse out extra data - if (null !== ($data = $this->parseView($row['sql']))) { - $table = array_merge($table, $data); - } - } - $tables[$row['name']] = $table; - } - $this->data['table_names'][$schema] = $tables; - } - - protected function loadColumnData($table, $schema) - { - if (isset($this->data['columns'][$schema][$table])) { - return; - } - $this->prepareDataHierarchy('columns', $schema, $table); - $this->prepareDataHierarchy('sqlite_columns', $schema, $table); - - $p = $this->adapter->getPlatform(); - - - $results = $this->fetchPragma('table_info', $table, $schema); - - $columns = array(); - - foreach ($results as $row) { - $columns[$row['name']] = array( - // cid appears to be zero-based, ordinal position needs to be one-based - 'ordinal_position' => $row['cid'] + 1, - 'column_default' => $row['dflt_value'], - 'is_nullable' => !((bool) $row['notnull']), - 'data_type' => $row['type'], - 'character_maximum_length' => null, - 'character_octet_length' => null, - 'numeric_precision' => null, - 'numeric_scale' => null, - 'numeric_unsigned' => null, - 'erratas' => array(), - ); - // TODO: populate character_ and numeric_values with correct info - } - - $this->data['columns'][$schema][$table] = $columns; - $this->data['sqlite_columns'][$schema][$table] = $results; - } - - protected function loadConstraintData($table, $schema) - { - if (isset($this->data['constraints'][$schema][$table])) { - return; - } - - $this->prepareDataHierarchy('constraints', $schema, $table); - - $this->loadColumnData($table, $schema); - $primaryKey = array(); - - foreach ($this->data['sqlite_columns'][$schema][$table] as $col) { - if ((bool) $col['pk']) { - $primaryKey[] = $col['name']; - } - } - - if (empty($primaryKey)) { - $primaryKey = null; - } - $constraints = array(); - $indexes = $this->fetchPragma('index_list', $table, $schema); - foreach ($indexes as $index) { - if (!((bool) $index['unique'])) { - continue; - } - $constraint = array( - 'constraint_name' => $index['name'], - 'constraint_type' => 'UNIQUE', - 'table_name' => $table, - 'columns' => array(), - ); - - $info = $this->fetchPragma('index_info', $index['name'], $schema); - - foreach ($info as $column) { - $constraint['columns'][] = $column['name']; - } - if ($primaryKey === $constraint['columns']) { - $constraint['constraint_type'] = 'PRIMARY KEY'; - $primaryKey = null; - } - $constraints[$constraint['constraint_name']] = $constraint; - } - - if (null !== $primaryKey) { - $constraintName = '_zf_' . $table . '_PRIMARY'; - $constraints[$constraintName] = array( - 'constraint_name' => $constraintName, - 'constraint_type' => 'PRIMARY KEY', - 'table_name' => $table, - 'columns' => $primaryKey, - ); - } - - $foreignKeys = $this->fetchPragma('foreign_key_list', $table, $schema); - - $id = $name = null; - foreach ($foreignKeys as $fk) { - if ($id !== $fk['id']) { - $id = $fk['id']; - $name = '_zf_' . $table . '_FOREIGN_KEY_' . ($id + 1); - $constraints[$name] = array( - 'constraint_name' => $name, - 'constraint_type' => 'FOREIGN KEY', - 'table_name' => $table, - 'columns' => array(), - 'referenced_table_schema' => $schema, - 'referenced_table_name' => $fk['table'], - 'referenced_columns' => array(), - // TODO: Verify match, on_update, and on_delete values conform to SQL Standard - 'match_option' => strtoupper($fk['match']), - 'update_rule' => strtoupper($fk['on_update']), - 'delete_rule' => strtoupper($fk['on_delete']), - ); - } - $constraints[$name]['columns'][] = $fk['from']; - $constraints[$name]['referenced_columns'][] = $fk['to']; - } - - $this->data['constraints'][$schema][$table] = $constraints; - } - - protected function loadTriggerData($schema) - { - if (isset($this->data['triggers'][$schema])) { - return; - } - - $this->prepareDataHierarchy('triggers', $schema); - - $p = $this->adapter->getPlatform(); - - $sql = 'SELECT "name", "tbl_name", "sql" FROM ' - . $p->quoteIdentifierChain(array($schema, 'sqlite_master')) - . ' WHERE "type" = \'trigger\''; - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - $triggers = array(); - foreach ($results->toArray() as $row) { - $trigger = array( - 'trigger_name' => $row['name'], - 'event_manipulation' => null, // in $row['sql'] - 'event_object_catalog' => null, - 'event_object_schema' => $schema, - 'event_object_table' => $row['tbl_name'], - 'action_order' => 0, - 'action_condition' => null, // in $row['sql'] - 'action_statement' => null, // in $row['sql'] - 'action_orientation' => 'ROW', - 'action_timing' => null, // in $row['sql'] - 'action_reference_old_table' => null, - 'action_reference_new_table' => null, - 'action_reference_old_row' => 'OLD', - 'action_reference_new_row' => 'NEW', - 'created' => null, - ); - - // Parse out extra data - if (null !== ($data = $this->parseTrigger($row['sql']))) { - $trigger = array_merge($trigger, $data); - } - $triggers[$trigger['trigger_name']] = $trigger; - } - - $this->data['triggers'][$schema] = $triggers; - } - - protected function fetchPragma($name, $value = null, $schema = null) - { - $p = $this->adapter->getPlatform(); - - $sql = 'PRAGMA '; - - if (null !== $schema) { - $sql .= $p->quoteIdentifier($schema) . '.'; - } - $sql .= $name; - - if (null !== $value) { - $sql .= '(' . $p->quoteTrustedValue($value) . ')'; - } - - $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE); - if ($results instanceof ResultSetInterface) { - return $results->toArray(); - } - return array(); - } - - protected function parseView($sql) - { - static $re = null; - if (null === $re) { - $identifierChain = $this->getIdentifierChainRegularExpression(); - $re = $this->buildRegularExpression(array( - 'CREATE', - array('TEMP|TEMPORARY'), - 'VIEW', - array('IF', 'NOT', 'EXISTS'), - $identifierChain, - 'AS', - '(?.+)', - array(';'), - )); - } - - if (!preg_match($re, $sql, $matches)) { - return null; - } - return array( - 'view_definition' => $matches['view_definition'], - ); - } - - protected function parseTrigger($sql) - { - static $re = null; - if (null === $re) { - $identifier = $this->getIdentifierRegularExpression(); - $identifierList = $this->getIdentifierListRegularExpression(); - $identifierChain = $this->getIdentifierChainRegularExpression(); - $re = $this->buildRegularExpression(array( - 'CREATE', - array('TEMP|TEMPORARY'), - 'TRIGGER', - array('IF', 'NOT', 'EXISTS'), - $identifierChain, - array('(?BEFORE|AFTER|INSTEAD\\s+OF)',), - '(?DELETE|INSERT|UPDATE)', - array('OF', '(?' . $identifierList . ')'), - 'ON', - '(?' . $identifier . ')', - array('FOR', 'EACH', 'ROW'), - array('WHEN', '(?.+)'), - '(?BEGIN', - '.+', - 'END)', - array(';'), - )); - } - - if (!preg_match($re, $sql, $matches)) { - return null; - } - $data = array(); - - foreach ($matches as $key => $value) { - if (is_string($key)) { - $data[$key] = $value; - } - } - - // Normalize data and populate defaults, if necessary - - $data['event_manipulation'] = strtoupper($data['event_manipulation']); - if (empty($data['action_condition'])) { - $data['action_condition'] = null; - } - if (!empty($data['action_timing'])) { - $data['action_timing'] = strtoupper($data['action_timing']); - if ('I' == $data['action_timing'][0]) { - // normalize the white-space between the two words - $data['action_timing'] = 'INSTEAD OF'; - } - } else { - $data['action_timing'] = 'AFTER'; - } - unset($data['column_usage']); - - return $data; - } - - protected function buildRegularExpression(array $re) - { - foreach ($re as &$value) { - if (is_array($value)) { - $value = '(?:' . implode('\\s*+', $value) . '\\s*+)?'; - } else { - $value .= '\\s*+'; - } - } - unset($value); - $re = '/^' . implode('\\s*+', $re) . '$/'; - return $re; - } - - protected function getIdentifierRegularExpression() - { - static $re = null; - if (null === $re) { - $re = '(?:' . implode('|', array( - '"(?:[^"\\\\]++|\\\\.)*+"', - '`(?:[^`]++|``)*+`', - '\\[[^\\]]+\\]', - '[^\\s\\.]+', - )) . ')'; - } - - return $re; - } - - protected function getIdentifierChainRegularExpression() - { - static $re = null; - if (null === $re) { - $identifier = $this->getIdentifierRegularExpression(); - $re = $identifier . '(?:\\s*\\.\\s*' . $identifier . ')*+'; - } - return $re; - } - - protected function getIdentifierListRegularExpression() - { - static $re = null; - if (null === $re) { - $identifier = $this->getIdentifierRegularExpression(); - $re = $identifier . '(?:\\s*,\\s*' . $identifier . ')*+'; - } - return $re; - } -} diff --git a/library/Zend/Db/README.md b/library/Zend/Db/README.md deleted file mode 100755 index 5c6788407..000000000 --- a/library/Zend/Db/README.md +++ /dev/null @@ -1,15 +0,0 @@ -DB Component from ZF2 -===================== - -This is the DB component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Db/ResultSet/AbstractResultSet.php b/library/Zend/Db/ResultSet/AbstractResultSet.php deleted file mode 100755 index 0db4c2d38..000000000 --- a/library/Zend/Db/ResultSet/AbstractResultSet.php +++ /dev/null @@ -1,280 +0,0 @@ -buffer)) { - $this->buffer = array(); - } - - if ($dataSource instanceof ResultInterface) { - $this->count = $dataSource->count(); - $this->fieldCount = $dataSource->getFieldCount(); - $this->dataSource = $dataSource; - if ($dataSource->isBuffered()) { - $this->buffer = -1; - } - if (is_array($this->buffer)) { - $this->dataSource->rewind(); - } - return $this; - } - - if (is_array($dataSource)) { - // its safe to get numbers from an array - $first = current($dataSource); - reset($dataSource); - $this->count = count($dataSource); - $this->fieldCount = count($first); - $this->dataSource = new ArrayIterator($dataSource); - $this->buffer = -1; // array's are a natural buffer - } elseif ($dataSource instanceof IteratorAggregate) { - $this->dataSource = $dataSource->getIterator(); - } elseif ($dataSource instanceof Iterator) { - $this->dataSource = $dataSource; - } else { - throw new Exception\InvalidArgumentException('DataSource provided is not an array, nor does it implement Iterator or IteratorAggregate'); - } - - if ($this->count == null && $this->dataSource instanceof Countable) { - $this->count = $this->dataSource->count(); - } - - return $this; - } - - public function buffer() - { - if ($this->buffer === -2) { - throw new Exception\RuntimeException('Buffering must be enabled before iteration is started'); - } elseif ($this->buffer === null) { - $this->buffer = array(); - if ($this->dataSource instanceof ResultInterface) { - $this->dataSource->rewind(); - } - } - return $this; - } - - public function isBuffered() - { - if ($this->buffer === -1 || is_array($this->buffer)) { - return true; - } - return false; - } - - /** - * Get the data source used to create the result set - * - * @return null|Iterator - */ - public function getDataSource() - { - return $this->dataSource; - } - - /** - * Retrieve count of fields in individual rows of the result set - * - * @return int - */ - public function getFieldCount() - { - if (null !== $this->fieldCount) { - return $this->fieldCount; - } - - $dataSource = $this->getDataSource(); - if (null === $dataSource) { - return 0; - } - - $dataSource->rewind(); - if (!$dataSource->valid()) { - $this->fieldCount = 0; - return 0; - } - - $row = $dataSource->current(); - if (is_object($row) && $row instanceof Countable) { - $this->fieldCount = $row->count(); - return $this->fieldCount; - } - - $row = (array) $row; - $this->fieldCount = count($row); - return $this->fieldCount; - } - - /** - * Iterator: move pointer to next item - * - * @return void - */ - public function next() - { - if ($this->buffer === null) { - $this->buffer = -2; // implicitly disable buffering from here on - } - $this->dataSource->next(); - $this->position++; - } - - /** - * Iterator: retrieve current key - * - * @return mixed - */ - public function key() - { - return $this->position; - } - - /** - * Iterator: get current item - * - * @return array - */ - public function current() - { - if ($this->buffer === null) { - $this->buffer = -2; // implicitly disable buffering from here on - } elseif (is_array($this->buffer) && isset($this->buffer[$this->position])) { - return $this->buffer[$this->position]; - } - $data = $this->dataSource->current(); - if (is_array($this->buffer)) { - $this->buffer[$this->position] = $data; - } - return $data; - } - - /** - * Iterator: is pointer valid? - * - * @return bool - */ - public function valid() - { - if (is_array($this->buffer) && isset($this->buffer[$this->position])) { - return true; - } - if ($this->dataSource instanceof Iterator) { - return $this->dataSource->valid(); - } else { - $key = key($this->dataSource); - return ($key !== null); - } - } - - /** - * Iterator: rewind - * - * @return void - */ - public function rewind() - { - if (!is_array($this->buffer)) { - if ($this->dataSource instanceof Iterator) { - $this->dataSource->rewind(); - } else { - reset($this->dataSource); - } - } - $this->position = 0; - } - - /** - * Countable: return count of rows - * - * @return int - */ - public function count() - { - if ($this->count !== null) { - return $this->count; - } - $this->count = count($this->dataSource); - return $this->count; - } - - /** - * Cast result set to array of arrays - * - * @return array - * @throws Exception\RuntimeException if any row is not castable to an array - */ - public function toArray() - { - $return = array(); - foreach ($this as $row) { - if (is_array($row)) { - $return[] = $row; - } elseif (method_exists($row, 'toArray')) { - $return[] = $row->toArray(); - } elseif (method_exists($row, 'getArrayCopy')) { - $return[] = $row->getArrayCopy(); - } else { - throw new Exception\RuntimeException( - 'Rows as part of this DataSource, with type ' . gettype($row) . ' cannot be cast to an array' - ); - } - } - return $return; - } -} diff --git a/library/Zend/Db/ResultSet/Exception/ExceptionInterface.php b/library/Zend/Db/ResultSet/Exception/ExceptionInterface.php deleted file mode 100755 index 7f7648b33..000000000 --- a/library/Zend/Db/ResultSet/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -setHydrator(($hydrator) ?: new ArraySerializable); - $this->setObjectPrototype(($objectPrototype) ?: new ArrayObject); - } - - /** - * Set the row object prototype - * - * @param object $objectPrototype - * @throws Exception\InvalidArgumentException - * @return ResultSet - */ - public function setObjectPrototype($objectPrototype) - { - if (!is_object($objectPrototype)) { - throw new Exception\InvalidArgumentException( - 'An object must be set as the object prototype, a ' . gettype($objectPrototype) . ' was provided.' - ); - } - $this->objectPrototype = $objectPrototype; - return $this; - } - - /** - * Set the hydrator to use for each row object - * - * @param HydratorInterface $hydrator - * @return HydratingResultSet - */ - public function setHydrator(HydratorInterface $hydrator) - { - $this->hydrator = $hydrator; - return $this; - } - - /** - * Get the hydrator to use for each row object - * - * @return HydratorInterface - */ - public function getHydrator() - { - return $this->hydrator; - } - - /** - * Iterator: get current item - * - * @return object - */ - public function current() - { - if ($this->buffer === null) { - $this->buffer = -2; // implicitly disable buffering from here on - } elseif (is_array($this->buffer) && isset($this->buffer[$this->position])) { - return $this->buffer[$this->position]; - } - $data = $this->dataSource->current(); - $object = is_array($data) ? $this->hydrator->hydrate($data, clone $this->objectPrototype) : false; - - if (is_array($this->buffer)) { - $this->buffer[$this->position] = $object; - } - - return $object; - } - - /** - * Cast result set to array of arrays - * - * @return array - * @throws Exception\RuntimeException if any row is not castable to an array - */ - public function toArray() - { - $return = array(); - foreach ($this as $row) { - $return[] = $this->getHydrator()->extract($row); - } - return $return; - } -} diff --git a/library/Zend/Db/ResultSet/ResultSet.php b/library/Zend/Db/ResultSet/ResultSet.php deleted file mode 100755 index 2286410c6..000000000 --- a/library/Zend/Db/ResultSet/ResultSet.php +++ /dev/null @@ -1,112 +0,0 @@ -returnType = (in_array($returnType, array(self::TYPE_ARRAY, self::TYPE_ARRAYOBJECT))) ? $returnType : self::TYPE_ARRAYOBJECT; - if ($this->returnType === self::TYPE_ARRAYOBJECT) { - $this->setArrayObjectPrototype(($arrayObjectPrototype) ?: new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS)); - } - } - - /** - * Set the row object prototype - * - * @param ArrayObject $arrayObjectPrototype - * @throws Exception\InvalidArgumentException - * @return ResultSet - */ - public function setArrayObjectPrototype($arrayObjectPrototype) - { - if (!is_object($arrayObjectPrototype) - || (!$arrayObjectPrototype instanceof ArrayObject && !method_exists($arrayObjectPrototype, 'exchangeArray')) - - ) { - throw new Exception\InvalidArgumentException('Object must be of type ArrayObject, or at least implement exchangeArray'); - } - $this->arrayObjectPrototype = $arrayObjectPrototype; - return $this; - } - - /** - * Get the row object prototype - * - * @return ArrayObject - */ - public function getArrayObjectPrototype() - { - return $this->arrayObjectPrototype; - } - - /** - * Get the return type to use when returning objects from the set - * - * @return string - */ - public function getReturnType() - { - return $this->returnType; - } - - /** - * @return array|\ArrayObject|null - */ - public function current() - { - $data = parent::current(); - - if ($this->returnType === self::TYPE_ARRAYOBJECT && is_array($data)) { - /** @var $ao ArrayObject */ - $ao = clone $this->arrayObjectPrototype; - if ($ao instanceof ArrayObject || method_exists($ao, 'exchangeArray')) { - $ao->exchangeArray($data); - } - return $ao; - } - - return $data; - } -} diff --git a/library/Zend/Db/ResultSet/ResultSetInterface.php b/library/Zend/Db/ResultSet/ResultSetInterface.php deleted file mode 100755 index c2bbd73b2..000000000 --- a/library/Zend/Db/ResultSet/ResultSetInterface.php +++ /dev/null @@ -1,33 +0,0 @@ -isInitialized) { - return; - } - - if (!$this->featureSet instanceof Feature\FeatureSet) { - $this->featureSet = new Feature\FeatureSet; - } - - $this->featureSet->setRowGateway($this); - $this->featureSet->apply('preInitialize', array()); - - if (!is_string($this->table) && !$this->table instanceof TableIdentifier) { - throw new Exception\RuntimeException('This row object does not have a valid table set.'); - } - - if ($this->primaryKeyColumn == null) { - throw new Exception\RuntimeException('This row object does not have a primary key column set.'); - } elseif (is_string($this->primaryKeyColumn)) { - $this->primaryKeyColumn = (array) $this->primaryKeyColumn; - } - - if (!$this->sql instanceof Sql) { - throw new Exception\RuntimeException('This row object does not have a Sql object set.'); - } - - $this->featureSet->apply('postInitialize', array()); - - $this->isInitialized = true; - } - - /** - * Populate Data - * - * @param array $rowData - * @param bool $rowExistsInDatabase - * @return AbstractRowGateway - */ - public function populate(array $rowData, $rowExistsInDatabase = false) - { - $this->initialize(); - - $this->data = $rowData; - if ($rowExistsInDatabase == true) { - $this->processPrimaryKeyData(); - } else { - $this->primaryKeyData = null; - } - - return $this; - } - - /** - * @param mixed $array - * @return array|void - */ - public function exchangeArray($array) - { - return $this->populate($array, true); - } - - /** - * Save - * - * @return int - */ - public function save() - { - $this->initialize(); - - if ($this->rowExistsInDatabase()) { - // UPDATE - - $data = $this->data; - $where = array(); - $isPkModified = false; - - // primary key is always an array even if its a single column - foreach ($this->primaryKeyColumn as $pkColumn) { - $where[$pkColumn] = $this->primaryKeyData[$pkColumn]; - if ($data[$pkColumn] == $this->primaryKeyData[$pkColumn]) { - unset($data[$pkColumn]); - } else { - $isPkModified = true; - } - } - - $statement = $this->sql->prepareStatementForSqlObject($this->sql->update()->set($data)->where($where)); - $result = $statement->execute(); - $rowsAffected = $result->getAffectedRows(); - unset($statement, $result); // cleanup - - // If one or more primary keys are modified, we update the where clause - if ($isPkModified) { - foreach ($this->primaryKeyColumn as $pkColumn) { - if ($data[$pkColumn] != $this->primaryKeyData[$pkColumn]) { - $where[$pkColumn] = $data[$pkColumn]; - } - } - } - } else { - // INSERT - $insert = $this->sql->insert(); - $insert->values($this->data); - - $statement = $this->sql->prepareStatementForSqlObject($insert); - - $result = $statement->execute(); - if (($primaryKeyValue = $result->getGeneratedValue()) && count($this->primaryKeyColumn) == 1) { - $this->primaryKeyData = array($this->primaryKeyColumn[0] => $primaryKeyValue); - } else { - // make primary key data available so that $where can be complete - $this->processPrimaryKeyData(); - } - $rowsAffected = $result->getAffectedRows(); - unset($statement, $result); // cleanup - - $where = array(); - // primary key is always an array even if its a single column - foreach ($this->primaryKeyColumn as $pkColumn) { - $where[$pkColumn] = $this->primaryKeyData[$pkColumn]; - } - } - - // refresh data - $statement = $this->sql->prepareStatementForSqlObject($this->sql->select()->where($where)); - $result = $statement->execute(); - $rowData = $result->current(); - unset($statement, $result); // cleanup - - // make sure data and original data are in sync after save - $this->populate($rowData, true); - - // return rows affected - return $rowsAffected; - } - - /** - * Delete - * - * @return int - */ - public function delete() - { - $this->initialize(); - - $where = array(); - // primary key is always an array even if its a single column - foreach ($this->primaryKeyColumn as $pkColumn) { - $where[$pkColumn] = $this->primaryKeyData[$pkColumn]; - } - - // @todo determine if we need to do a select to ensure 1 row will be affected - - $statement = $this->sql->prepareStatementForSqlObject($this->sql->delete()->where($where)); - $result = $statement->execute(); - - $affectedRows = $result->getAffectedRows(); - if ($affectedRows == 1) { - // detach from database - $this->primaryKeyData = null; - } - - return $affectedRows; - } - - /** - * Offset Exists - * - * @param string $offset - * @return bool - */ - public function offsetExists($offset) - { - return array_key_exists($offset, $this->data); - } - - /** - * Offset get - * - * @param string $offset - * @return mixed - */ - public function offsetGet($offset) - { - return $this->data[$offset]; - } - - /** - * Offset set - * - * @param string $offset - * @param mixed $value - * @return RowGateway - */ - public function offsetSet($offset, $value) - { - $this->data[$offset] = $value; - return $this; - } - - /** - * Offset unset - * - * @param string $offset - * @return AbstractRowGateway - */ - public function offsetUnset($offset) - { - $this->data[$offset] = null; - return $this; - } - - /** - * @return int - */ - public function count() - { - return count($this->data); - } - - /** - * To array - * - * @return array - */ - public function toArray() - { - return $this->data; - } - - /** - * __get - * - * @param string $name - * @throws Exception\InvalidArgumentException - * @return mixed - */ - public function __get($name) - { - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } else { - throw new Exception\InvalidArgumentException('Not a valid column in this row: ' . $name); - } - } - - /** - * __set - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) - { - $this->offsetSet($name, $value); - } - - /** - * __isset - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - return $this->offsetExists($name); - } - - /** - * __unset - * - * @param string $name - * @return void - */ - public function __unset($name) - { - $this->offsetUnset($name); - } - - /** - * @return bool - */ - public function rowExistsInDatabase() - { - return ($this->primaryKeyData !== null); - } - - /** - * @throws Exception\RuntimeException - */ - protected function processPrimaryKeyData() - { - $this->primaryKeyData = array(); - foreach ($this->primaryKeyColumn as $column) { - if (!isset($this->data[$column])) { - throw new Exception\RuntimeException('While processing primary key data, a known key ' . $column . ' was not found in the data array'); - } - $this->primaryKeyData[$column] = $this->data[$column]; - } - } -} diff --git a/library/Zend/Db/RowGateway/Exception/ExceptionInterface.php b/library/Zend/Db/RowGateway/Exception/ExceptionInterface.php deleted file mode 100755 index 7bb37fc98..000000000 --- a/library/Zend/Db/RowGateway/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -rowGateway = $rowGateway; - } - - /** - * @throws \Zend\Db\RowGateway\Exception\RuntimeException - */ - public function initialize() - { - throw new Exception\RuntimeException('This method is not intended to be called on this object.'); - } - - /** - * @return array - */ - public function getMagicMethodSpecifications() - { - return array(); - } -} diff --git a/library/Zend/Db/RowGateway/Feature/FeatureSet.php b/library/Zend/Db/RowGateway/Feature/FeatureSet.php deleted file mode 100755 index de3b2344f..000000000 --- a/library/Zend/Db/RowGateway/Feature/FeatureSet.php +++ /dev/null @@ -1,149 +0,0 @@ -addFeatures($features); - } - } - - public function setRowGateway(AbstractRowGateway $rowGateway) - { - $this->rowGateway = $rowGateway; - foreach ($this->features as $feature) { - $feature->setRowGateway($this->rowGateway); - } - return $this; - } - - public function getFeatureByClassName($featureClassName) - { - $feature = false; - foreach ($this->features as $potentialFeature) { - if ($potentialFeature instanceof $featureClassName) { - $feature = $potentialFeature; - break; - } - } - return $feature; - } - - public function addFeatures(array $features) - { - foreach ($features as $feature) { - $this->addFeature($feature); - } - return $this; - } - - public function addFeature(AbstractFeature $feature) - { - $this->features[] = $feature; - $feature->setRowGateway($feature); - return $this; - } - - public function apply($method, $args) - { - foreach ($this->features as $feature) { - if (method_exists($feature, $method)) { - $return = call_user_func_array(array($feature, $method), $args); - if ($return === self::APPLY_HALT) { - break; - } - } - } - } - - /** - * @param string $property - * @return bool - */ - public function canCallMagicGet($property) - { - return false; - } - - /** - * @param string $property - * @return mixed - */ - public function callMagicGet($property) - { - $return = null; - return $return; - } - - /** - * @param string $property - * @return bool - */ - public function canCallMagicSet($property) - { - return false; - } - - /** - * @param $property - * @param $value - * @return mixed - */ - public function callMagicSet($property, $value) - { - $return = null; - return $return; - } - - /** - * @param string $method - * @return bool - */ - public function canCallMagicCall($method) - { - return false; - } - - /** - * @param string $method - * @param array $arguments - * @return mixed - */ - public function callMagicCall($method, $arguments) - { - $return = null; - return $return; - } -} diff --git a/library/Zend/Db/RowGateway/RowGateway.php b/library/Zend/Db/RowGateway/RowGateway.php deleted file mode 100755 index df2295c14..000000000 --- a/library/Zend/Db/RowGateway/RowGateway.php +++ /dev/null @@ -1,48 +0,0 @@ -primaryKeyColumn = empty($primaryKeyColumn) ? null : (array) $primaryKeyColumn; - - // set table - $this->table = $table; - - // set Sql object - if ($adapterOrSql instanceof Sql) { - $this->sql = $adapterOrSql; - } elseif ($adapterOrSql instanceof Adapter) { - $this->sql = new Sql($adapterOrSql, $this->table); - } else { - throw new Exception\InvalidArgumentException('A valid Sql object was not provided.'); - } - - if ($this->sql->getTable() !== $this->table) { - throw new Exception\InvalidArgumentException('The Sql object provided does not have a table that matches this row object'); - } - - $this->initialize(); - } -} diff --git a/library/Zend/Db/RowGateway/RowGatewayInterface.php b/library/Zend/Db/RowGateway/RowGatewayInterface.php deleted file mode 100755 index e0a20b554..000000000 --- a/library/Zend/Db/RowGateway/RowGatewayInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - '', 'subselectCount' => 0); - - /** - * @var array - */ - protected $instanceParameterIndex = array(); - - protected function processExpression(ExpressionInterface $expression, PlatformInterface $platform, DriverInterface $driver = null, $namedParameterPrefix = null) - { - // static counter for the number of times this method was invoked across the PHP runtime - static $runtimeExpressionPrefix = 0; - - if ($driver && ((!is_string($namedParameterPrefix) || $namedParameterPrefix == ''))) { - $namedParameterPrefix = sprintf('expr%04dParam', ++$runtimeExpressionPrefix); - } - - $sql = ''; - $statementContainer = new StatementContainer; - $parameterContainer = $statementContainer->getParameterContainer(); - - // initialize variables - $parts = $expression->getExpressionData(); - - if (!isset($this->instanceParameterIndex[$namedParameterPrefix])) { - $this->instanceParameterIndex[$namedParameterPrefix] = 1; - } - - $expressionParamIndex = &$this->instanceParameterIndex[$namedParameterPrefix]; - - foreach ($parts as $part) { - // if it is a string, simply tack it onto the return sql "specification" string - if (is_string($part)) { - $sql .= $part; - continue; - } - - if (!is_array($part)) { - throw new Exception\RuntimeException('Elements returned from getExpressionData() array must be a string or array.'); - } - - // process values and types (the middle and last position of the expression data) - $values = $part[1]; - $types = (isset($part[2])) ? $part[2] : array(); - foreach ($values as $vIndex => $value) { - if (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_IDENTIFIER) { - $values[$vIndex] = $platform->quoteIdentifierInFragment($value); - } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_VALUE && $value instanceof Select) { - // process sub-select - if ($driver) { - $values[$vIndex] = '(' . $this->processSubSelect($value, $platform, $driver, $parameterContainer) . ')'; - } else { - $values[$vIndex] = '(' . $this->processSubSelect($value, $platform) . ')'; - } - } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_VALUE && $value instanceof ExpressionInterface) { - // recursive call to satisfy nested expressions - $innerStatementContainer = $this->processExpression($value, $platform, $driver, $namedParameterPrefix . $vIndex . 'subpart'); - $values[$vIndex] = $innerStatementContainer->getSql(); - if ($driver) { - $parameterContainer->merge($innerStatementContainer->getParameterContainer()); - } - } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_VALUE) { - // if prepareType is set, it means that this particular value must be - // passed back to the statement in a way it can be used as a placeholder value - if ($driver) { - $name = $namedParameterPrefix . $expressionParamIndex++; - $parameterContainer->offsetSet($name, $value); - $values[$vIndex] = $driver->formatParameterName($name); - continue; - } - - // if not a preparable statement, simply quote the value and move on - $values[$vIndex] = $platform->quoteValue($value); - } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_LITERAL) { - $values[$vIndex] = $value; - } - } - - // after looping the values, interpolate them into the sql string (they might be placeholder names, or values) - $sql .= vsprintf($part[0], $values); - } - - $statementContainer->setSql($sql); - return $statementContainer; - } - - /** - * @param $specifications - * @param $parameters - * @return string - * @throws Exception\RuntimeException - */ - protected function createSqlFromSpecificationAndParameters($specifications, $parameters) - { - if (is_string($specifications)) { - return vsprintf($specifications, $parameters); - } - - $parametersCount = count($parameters); - foreach ($specifications as $specificationString => $paramSpecs) { - if ($parametersCount == count($paramSpecs)) { - break; - } - unset($specificationString, $paramSpecs); - } - - if (!isset($specificationString)) { - throw new Exception\RuntimeException( - 'A number of parameters was found that is not supported by this specification' - ); - } - - $topParameters = array(); - foreach ($parameters as $position => $paramsForPosition) { - if (isset($paramSpecs[$position]['combinedby'])) { - $multiParamValues = array(); - foreach ($paramsForPosition as $multiParamsForPosition) { - $ppCount = count($multiParamsForPosition); - if (!isset($paramSpecs[$position][$ppCount])) { - throw new Exception\RuntimeException('A number of parameters (' . $ppCount . ') was found that is not supported by this specification'); - } - $multiParamValues[] = vsprintf($paramSpecs[$position][$ppCount], $multiParamsForPosition); - } - $topParameters[] = implode($paramSpecs[$position]['combinedby'], $multiParamValues); - } elseif ($paramSpecs[$position] !== null) { - $ppCount = count($paramsForPosition); - if (!isset($paramSpecs[$position][$ppCount])) { - throw new Exception\RuntimeException('A number of parameters (' . $ppCount . ') was found that is not supported by this specification'); - } - $topParameters[] = vsprintf($paramSpecs[$position][$ppCount], $paramsForPosition); - } else { - $topParameters[] = $paramsForPosition; - } - } - return vsprintf($specificationString, $topParameters); - } - - protected function processSubSelect(Select $subselect, PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($driver) { - $stmtContainer = new StatementContainer; - - // Track subselect prefix and count for parameters - $this->processInfo['subselectCount']++; - $subselect->processInfo['subselectCount'] = $this->processInfo['subselectCount']; - $subselect->processInfo['paramPrefix'] = 'subselect' . $subselect->processInfo['subselectCount']; - - // call subselect - if ($this instanceof PlatformDecoratorInterface) { - /** @var Select|PlatformDecoratorInterface $subselectDecorator */ - $subselectDecorator = clone $this; - $subselectDecorator->setSubject($subselect); - $subselectDecorator->prepareStatement(new Adapter($driver, $platform), $stmtContainer); - } else { - $subselect->prepareStatement(new Adapter($driver, $platform), $stmtContainer); - } - - // copy count - $this->processInfo['subselectCount'] = $subselect->processInfo['subselectCount']; - - $parameterContainer->merge($stmtContainer->getParameterContainer()->getNamedArray()); - $sql = $stmtContainer->getSql(); - } else { - if ($this instanceof PlatformDecoratorInterface) { - $subselectDecorator = clone $this; - $subselectDecorator->setSubject($subselect); - $sql = $subselectDecorator->getSqlString($platform); - } else { - $sql = $subselect->getSqlString($platform); - } - } - return $sql; - } -} diff --git a/library/Zend/Db/Sql/Ddl/AlterTable.php b/library/Zend/Db/Sql/Ddl/AlterTable.php deleted file mode 100755 index 2721db5a2..000000000 --- a/library/Zend/Db/Sql/Ddl/AlterTable.php +++ /dev/null @@ -1,268 +0,0 @@ - "ALTER TABLE %1\$s\n", - self::ADD_COLUMNS => array( - "%1\$s" => array( - array(1 => 'ADD COLUMN %1$s', 'combinedby' => ",\n") - ) - ), - self::CHANGE_COLUMNS => array( - "%1\$s" => array( - array(2 => 'CHANGE COLUMN %1$s %2$s', 'combinedby' => ",\n"), - ) - ), - self::DROP_COLUMNS => array( - "%1\$s" => array( - array(1 => 'DROP COLUMN %1$s', 'combinedby' => ",\n"), - ) - ), - self::ADD_CONSTRAINTS => array( - "%1\$s" => array( - array(1 => 'ADD %1$s', 'combinedby' => ",\n"), - ) - ), - self::DROP_CONSTRAINTS => array( - "%1\$s" => array( - array(1 => 'DROP CONSTRAINT %1$s', 'combinedby' => ",\n"), - ) - ) - ); - - /** - * @var string - */ - protected $table = ''; - - /** - * @param string $table - */ - public function __construct($table = '') - { - ($table) ? $this->setTable($table) : null; - } - - /** - * @param string $name - * @return self - */ - public function setTable($name) - { - $this->table = $name; - - return $this; - } - - /** - * @param Column\ColumnInterface $column - * @return self - */ - public function addColumn(Column\ColumnInterface $column) - { - $this->addColumns[] = $column; - - return $this; - } - - /** - * @param string $name - * @param Column\ColumnInterface $column - * @return self - */ - public function changeColumn($name, Column\ColumnInterface $column) - { - $this->changeColumns[$name] = $column; - - return $this; - } - - /** - * @param string $name - * @return self - */ - public function dropColumn($name) - { - $this->dropColumns[] = $name; - - return $this; - } - - /** - * @param string $name - * @return self - */ - public function dropConstraint($name) - { - $this->dropConstraints[] = $name; - - return $this; - } - - /** - * @param Constraint\ConstraintInterface $constraint - * @return self - */ - public function addConstraint(Constraint\ConstraintInterface $constraint) - { - $this->addConstraints[] = $constraint; - - return $this; - } - - /** - * @param string|null $key - * @return array - */ - public function getRawState($key = null) - { - $rawState = array( - self::TABLE => $this->table, - self::ADD_COLUMNS => $this->addColumns, - self::DROP_COLUMNS => $this->dropColumns, - self::CHANGE_COLUMNS => $this->changeColumns, - self::ADD_CONSTRAINTS => $this->addConstraints, - self::DROP_CONSTRAINTS => $this->dropConstraints, - ); - - return (isset($key) && array_key_exists($key, $rawState)) ? $rawState[$key] : $rawState; - } - - /** - * @param PlatformInterface $adapterPlatform - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - // get platform, or create default - $adapterPlatform = ($adapterPlatform) ?: new AdapterSql92Platform; - - $sqls = array(); - $parameters = array(); - - foreach ($this->specifications as $name => $specification) { - $parameters[$name] = $this->{'process' . $name}($adapterPlatform, null, null, $sqls, $parameters); - if ($specification && is_array($parameters[$name]) && ($parameters[$name] != array(array()))) { - $sqls[$name] = $this->createSqlFromSpecificationAndParameters($specification, $parameters[$name]); - } - if (stripos($name, 'table') === false && $parameters[$name] !== array(array())) { - $sqls[] = ",\n"; - } - } - - // remove last ,\n - array_pop($sqls); - - $sql = implode('', $sqls); - - return $sql; - } - - protected function processTable(PlatformInterface $adapterPlatform = null) - { - return array($adapterPlatform->quoteIdentifier($this->table)); - } - - protected function processAddColumns(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->addColumns as $column) { - $sqls[] = $this->processExpression($column, $adapterPlatform)->getSql(); - } - - return array($sqls); - } - - protected function processChangeColumns(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->changeColumns as $name => $column) { - $sqls[] = array( - $adapterPlatform->quoteIdentifier($name), - $this->processExpression($column, $adapterPlatform)->getSql() - ); - } - - return array($sqls); - } - - protected function processDropColumns(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->dropColumns as $column) { - $sqls[] = $adapterPlatform->quoteIdentifier($column); - } - - return array($sqls); - } - - protected function processAddConstraints(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->addConstraints as $constraint) { - $sqls[] = $this->processExpression($constraint, $adapterPlatform); - } - - return array($sqls); - } - - protected function processDropConstraints(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->dropConstraints as $constraint) { - $sqls[] = $adapterPlatform->quoteIdentifier($constraint); - } - - return array($sqls); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/BigInteger.php b/library/Zend/Db/Sql/Ddl/Column/BigInteger.php deleted file mode 100755 index d915a948f..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/BigInteger.php +++ /dev/null @@ -1,18 +0,0 @@ -setName($name); - $this->setLength($length); - $this->setNullable($nullable); - $this->setDefault($default); - $this->setOptions($options); - } - - /** - * @param int $length - * @return self - */ - public function setLength($length) - { - $this->length = $length; - return $this; - } - - /** - * @return int - */ - public function getLength() - { - return $this->length; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - - $params = array(); - $params[] = $this->name; - $params[] = $this->type; - - if ($this->length) { - $params[1] .= ' ' . $this->length; - } - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - - if (!$this->isNullable) { - $params[1] .= ' NOT NULL'; - } - - if ($this->default !== null) { - $spec .= ' DEFAULT %s'; - $params[] = $this->default; - $types[] = self::TYPE_VALUE; - } - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Boolean.php b/library/Zend/Db/Sql/Ddl/Column/Boolean.php deleted file mode 100755 index 36c07187c..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Boolean.php +++ /dev/null @@ -1,42 +0,0 @@ -name = $name; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array($this->name); - $types = array(self::TYPE_IDENTIFIER); - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Char.php b/library/Zend/Db/Sql/Ddl/Column/Char.php deleted file mode 100755 index 507cfe2c6..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Char.php +++ /dev/null @@ -1,58 +0,0 @@ -name = $name; - $this->length = $length; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - $params[] = $this->name; - $params[] = $this->length; - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Column.php b/library/Zend/Db/Sql/Ddl/Column/Column.php deleted file mode 100755 index de2f852b0..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Column.php +++ /dev/null @@ -1,164 +0,0 @@ -setName($name); - } - - /** - * @param string $name - * @return self - */ - public function setName($name) - { - $this->name = $name; - return $this; - } - - /** - * @return null|string - */ - public function getName() - { - return $this->name; - } - - /** - * @param bool $nullable - * @return self - */ - public function setNullable($nullable) - { - $this->isNullable = (bool) $nullable; - return $this; - } - - /** - * @return bool - */ - public function isNullable() - { - return $this->isNullable; - } - - /** - * @param null|string|int $default - * @return self - */ - public function setDefault($default) - { - $this->default = $default; - return $this; - } - - /** - * @return null|string|int - */ - public function getDefault() - { - return $this->default; - } - - /** - * @param array $options - * @return self - */ - public function setOptions(array $options) - { - $this->options = $options; - return $this; - } - - /** - * @param string $name - * @param string $value - * @return self - */ - public function setOption($name, $value) - { - $this->options[$name] = $value; - return $this; - } - - /** - * @return array - */ - public function getOptions() - { - return $this->options; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - - $params = array(); - $params[] = $this->name; - $params[] = $this->type; - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - - if (!$this->isNullable) { - $params[1] .= ' NOT NULL'; - } - - if ($this->default !== null) { - $spec .= ' DEFAULT %s'; - $params[] = $this->default; - $types[] = self::TYPE_VALUE; - } - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/ColumnInterface.php b/library/Zend/Db/Sql/Ddl/Column/ColumnInterface.php deleted file mode 100755 index 331e5254f..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/ColumnInterface.php +++ /dev/null @@ -1,20 +0,0 @@ -name = $name; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER); - $params[] = $this->name; - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Decimal.php b/library/Zend/Db/Sql/Ddl/Column/Decimal.php deleted file mode 100755 index 8a0ff25e3..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Decimal.php +++ /dev/null @@ -1,69 +0,0 @@ -name = $name; - $this->precision = $precision; - $this->scale = $scale; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - $params[] = $this->name; - $params[] = $this->precision; - - if ($this->scale !== null) { - $params[1] .= ', ' . $this->scale; - } - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Float.php b/library/Zend/Db/Sql/Ddl/Column/Float.php deleted file mode 100755 index e866abcf5..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Float.php +++ /dev/null @@ -1,66 +0,0 @@ -name = $name; - $this->digits = $digits; - $this->decimal = $decimal; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - $params[] = $this->name; - $params[] = $this->digits; - $params[1] .= ', ' . $this->decimal; - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Integer.php b/library/Zend/Db/Sql/Ddl/Column/Integer.php deleted file mode 100755 index 5e424285c..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Integer.php +++ /dev/null @@ -1,32 +0,0 @@ -setName($name); - $this->setNullable($nullable); - $this->setDefault($default); - $this->setOptions($options); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Text.php b/library/Zend/Db/Sql/Ddl/Column/Text.php deleted file mode 100755 index 3e4070909..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Text.php +++ /dev/null @@ -1,51 +0,0 @@ -name = $name; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - $params[] = $this->name; - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Time.php b/library/Zend/Db/Sql/Ddl/Column/Time.php deleted file mode 100755 index 68d3c6648..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Time.php +++ /dev/null @@ -1,50 +0,0 @@ -name = $name; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER); - $params[] = $this->name; - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Column/Varchar.php b/library/Zend/Db/Sql/Ddl/Column/Varchar.php deleted file mode 100755 index 49a718c78..000000000 --- a/library/Zend/Db/Sql/Ddl/Column/Varchar.php +++ /dev/null @@ -1,58 +0,0 @@ -name = $name; - $this->length = $length; - } - - /** - * @return array - */ - public function getExpressionData() - { - $spec = $this->specification; - $params = array(); - - $types = array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL); - $params[] = $this->name; - $params[] = $this->length; - - $types[] = self::TYPE_LITERAL; - $params[] = (!$this->isNullable) ? 'NOT NULL' : ''; - - $types[] = ($this->default !== null) ? self::TYPE_VALUE : self::TYPE_LITERAL; - $params[] = ($this->default !== null) ? $this->default : ''; - - return array(array( - $spec, - $params, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Constraint/AbstractConstraint.php b/library/Zend/Db/Sql/Ddl/Constraint/AbstractConstraint.php deleted file mode 100755 index 19909fadb..000000000 --- a/library/Zend/Db/Sql/Ddl/Constraint/AbstractConstraint.php +++ /dev/null @@ -1,58 +0,0 @@ -setColumns($columns); - } - - /** - * @param null|string|array $columns - * @return self - */ - public function setColumns($columns) - { - if (!is_array($columns)) { - $columns = array($columns); - } - - $this->columns = $columns; - return $this; - } - - /** - * @param string $column - * @return self - */ - public function addColumn($column) - { - $this->columns[] = $column; - return $this; - } - - /** - * @return array - */ - public function getColumns() - { - return $this->columns; - } -} diff --git a/library/Zend/Db/Sql/Ddl/Constraint/Check.php b/library/Zend/Db/Sql/Ddl/Constraint/Check.php deleted file mode 100755 index 1afbeb39c..000000000 --- a/library/Zend/Db/Sql/Ddl/Constraint/Check.php +++ /dev/null @@ -1,45 +0,0 @@ -expression = $expression; - $this->name = $name; - } - - /** - * @return array - */ - public function getExpressionData() - { - return array(array( - $this->specification, - array($this->name, $this->expression), - array(self::TYPE_IDENTIFIER, self::TYPE_LITERAL), - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Constraint/ConstraintInterface.php b/library/Zend/Db/Sql/Ddl/Constraint/ConstraintInterface.php deleted file mode 100755 index bcb964394..000000000 --- a/library/Zend/Db/Sql/Ddl/Constraint/ConstraintInterface.php +++ /dev/null @@ -1,17 +0,0 @@ -setName($name); - $this->setColumns($column); - $this->setReferenceTable($referenceTable); - $this->setReferenceColumn($referenceColumn); - (!$onDeleteRule) ?: $this->setOnDeleteRule($onDeleteRule); - (!$onUpdateRule) ?: $this->setOnUpdateRule($onUpdateRule); - } - - /** - * @param string $name - * @return self - */ - public function setName($name) - { - $this->name = $name; - return $this; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $referenceTable - * @return self - */ - public function setReferenceTable($referenceTable) - { - $this->referenceTable = $referenceTable; - return $this; - } - - /** - * @return string - */ - public function getReferenceTable() - { - return $this->referenceTable; - } - - /** - * @param string $referenceColumn - * @return self - */ - public function setReferenceColumn($referenceColumn) - { - $this->referenceColumn = $referenceColumn; - return $this; - } - - /** - * @return string - */ - public function getReferenceColumn() - { - return $this->referenceColumn; - } - - /** - * @param string $onDeleteRule - * @return self - */ - public function setOnDeleteRule($onDeleteRule) - { - $this->onDeleteRule = $onDeleteRule; - return $this; - } - - /** - * @return string - */ - public function getOnDeleteRule() - { - return $this->onDeleteRule; - } - - /** - * @param string $onUpdateRule - * @return self - */ - public function setOnUpdateRule($onUpdateRule) - { - $this->onUpdateRule = $onUpdateRule; - return $this; - } - - /** - * @return string - */ - public function getOnUpdateRule() - { - return $this->onUpdateRule; - } - - /** - * @return array - */ - public function getExpressionData() - { - return array(array( - $this->specification, - array( - $this->name, - $this->columns[0], - $this->referenceTable, - $this->referenceColumn, - $this->onDeleteRule, - $this->onUpdateRule, - ), - array( - self::TYPE_IDENTIFIER, - self::TYPE_IDENTIFIER, - self::TYPE_IDENTIFIER, - self::TYPE_IDENTIFIER, - self::TYPE_LITERAL, - self::TYPE_LITERAL, - ), - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Constraint/PrimaryKey.php b/library/Zend/Db/Sql/Ddl/Constraint/PrimaryKey.php deleted file mode 100755 index 84124a4d0..000000000 --- a/library/Zend/Db/Sql/Ddl/Constraint/PrimaryKey.php +++ /dev/null @@ -1,36 +0,0 @@ -columns); - $newSpecParts = array_fill(0, $colCount, '%s'); - $newSpecTypes = array_fill(0, $colCount, self::TYPE_IDENTIFIER); - - $newSpec = sprintf($this->specification, implode(', ', $newSpecParts)); - - return array(array( - $newSpec, - $this->columns, - $newSpecTypes, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/Constraint/UniqueKey.php b/library/Zend/Db/Sql/Ddl/Constraint/UniqueKey.php deleted file mode 100755 index 8d871054e..000000000 --- a/library/Zend/Db/Sql/Ddl/Constraint/UniqueKey.php +++ /dev/null @@ -1,55 +0,0 @@ -setColumns($column); - $this->name = $name; - } - - /** - * @return array - */ - public function getExpressionData() - { - $colCount = count($this->columns); - - $values = array(); - $values[] = ($this->name) ? $this->name : ''; - - $newSpecTypes = array(self::TYPE_IDENTIFIER); - $newSpecParts = array(); - - for ($i = 0; $i < $colCount; $i++) { - $newSpecParts[] = '%s'; - $newSpecTypes[] = self::TYPE_IDENTIFIER; - } - - $newSpec = str_replace('...', implode(', ', $newSpecParts), $this->specification); - - return array(array( - $newSpec, - array_merge($values, $this->columns), - $newSpecTypes, - )); - } -} diff --git a/library/Zend/Db/Sql/Ddl/CreateTable.php b/library/Zend/Db/Sql/Ddl/CreateTable.php deleted file mode 100755 index 45bfd982d..000000000 --- a/library/Zend/Db/Sql/Ddl/CreateTable.php +++ /dev/null @@ -1,218 +0,0 @@ - 'CREATE %1$sTABLE %2$s (', - self::COLUMNS => array( - "\n %1\$s" => array( - array(1 => '%1$s', 'combinedby' => ",\n ") - ) - ), - self::CONSTRAINTS => array( - "\n %1\$s" => array( - array(1 => '%1$s', 'combinedby' => ",\n ") - ) - ), - ); - - /** - * @var string - */ - protected $table = ''; - - /** - * @param string $table - * @param bool $isTemporary - */ - public function __construct($table = '', $isTemporary = false) - { - $this->table = $table; - $this->setTemporary($isTemporary); - } - - /** - * @param bool $temporary - * @return self - */ - public function setTemporary($temporary) - { - $this->isTemporary = (bool) $temporary; - return $this; - } - - /** - * @return bool - */ - public function isTemporary() - { - return $this->isTemporary; - } - - /** - * @param string $name - * @return self - */ - public function setTable($name) - { - $this->table = $name; - return $this; - } - - /** - * @param Column\ColumnInterface $column - * @return self - */ - public function addColumn(Column\ColumnInterface $column) - { - $this->columns[] = $column; - return $this; - } - - /** - * @param Constraint\ConstraintInterface $constraint - * @return self - */ - public function addConstraint(Constraint\ConstraintInterface $constraint) - { - $this->constraints[] = $constraint; - return $this; - } - - /** - * @param string|null $key - * @return array - */ - public function getRawState($key = null) - { - $rawState = array( - self::COLUMNS => $this->columns, - self::CONSTRAINTS => $this->constraints, - self::TABLE => $this->table, - ); - - return (isset($key) && array_key_exists($key, $rawState)) ? $rawState[$key] : $rawState; - } - - /** - * @param PlatformInterface $adapterPlatform - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - // get platform, or create default - $adapterPlatform = ($adapterPlatform) ?: new AdapterSql92Platform; - - $sqls = array(); - $parameters = array(); - - foreach ($this->specifications as $name => $specification) { - if (is_int($name)) { - $sqls[] = $specification; - continue; - } - - $parameters[$name] = $this->{'process' . $name}( - $adapterPlatform, - null, - null, - $sqls, - $parameters - ); - - - if ($specification - && is_array($parameters[$name]) - && ($parameters[$name] != array(array())) - ) { - $sqls[$name] = $this->createSqlFromSpecificationAndParameters( - $specification, - $parameters[$name] - ); - } - - if (stripos($name, 'table') === false - && $parameters[$name] !== array(array()) - ) { - $sqls[] = ",\n"; - } - } - - - // remove last , - if (count($sqls) > 2) { - array_pop($sqls); - } - - $sql = implode('', $sqls) . "\n)"; - - return $sql; - } - - protected function processTable(PlatformInterface $adapterPlatform = null) - { - $ret = array(); - if ($this->isTemporary) { - $ret[] = 'TEMPORARY '; - } else { - $ret[] = ''; - } - - $ret[] = $adapterPlatform->quoteIdentifier($this->table); - return $ret; - } - - protected function processColumns(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->columns as $column) { - $sqls[] = $this->processExpression($column, $adapterPlatform)->getSql(); - } - return array($sqls); - } - - protected function processConstraints(PlatformInterface $adapterPlatform = null) - { - $sqls = array(); - foreach ($this->constraints as $constraint) { - $sqls[] = $this->processExpression($constraint, $adapterPlatform)->getSql(); - } - return array($sqls); - } -} diff --git a/library/Zend/Db/Sql/Ddl/DropTable.php b/library/Zend/Db/Sql/Ddl/DropTable.php deleted file mode 100755 index e38425c6b..000000000 --- a/library/Zend/Db/Sql/Ddl/DropTable.php +++ /dev/null @@ -1,77 +0,0 @@ - 'DROP TABLE %1$s' - ); - - /** - * @var string - */ - protected $table = ''; - - /** - * @param string $table - */ - public function __construct($table = '') - { - $this->table = $table; - } - - /** - * @param null|PlatformInterface $adapterPlatform - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - // get platform, or create default - $adapterPlatform = ($adapterPlatform) ?: new AdapterSql92Platform; - - $sqls = array(); - $parameters = array(); - - foreach ($this->specifications as $name => $specification) { - $parameters[$name] = $this->{'process' . $name}( - $adapterPlatform, - null, - null, - $sqls, - $parameters - ); - - if ($specification && is_array($parameters[$name])) { - $sqls[$name] = $this->createSqlFromSpecificationAndParameters( - $specification, - $parameters[$name] - ); - } - } - - $sql = implode(' ', $sqls); - return $sql; - } - - protected function processTable(PlatformInterface $adapterPlatform = null) - { - return array($adapterPlatform->quoteIdentifier($this->table)); - } -} diff --git a/library/Zend/Db/Sql/Ddl/SqlInterface.php b/library/Zend/Db/Sql/Ddl/SqlInterface.php deleted file mode 100755 index 761312458..000000000 --- a/library/Zend/Db/Sql/Ddl/SqlInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - 'DELETE FROM %1$s', - self::SPECIFICATION_WHERE => 'WHERE %1$s' - ); - - /** - * @var string|TableIdentifier - */ - protected $table = ''; - - /** - * @var bool - */ - protected $emptyWhereProtection = true; - - /** - * @var array - */ - protected $set = array(); - - /** - * @var null|string|Where - */ - protected $where = null; - - /** - * Constructor - * - * @param null|string|TableIdentifier $table - */ - public function __construct($table = null) - { - if ($table) { - $this->from($table); - } - $this->where = new Where(); - } - - /** - * Create from statement - * - * @param string|TableIdentifier $table - * @return Delete - */ - public function from($table) - { - $this->table = $table; - return $this; - } - - public function getRawState($key = null) - { - $rawState = array( - 'emptyWhereProtection' => $this->emptyWhereProtection, - 'table' => $this->table, - 'set' => $this->set, - 'where' => $this->where - ); - return (isset($key) && array_key_exists($key, $rawState)) ? $rawState[$key] : $rawState; - } - - /** - * Create where clause - * - * @param Where|\Closure|string|array $predicate - * @param string $combination One of the OP_* constants from Predicate\PredicateSet - * @return Delete - */ - public function where($predicate, $combination = Predicate\PredicateSet::OP_AND) - { - if ($predicate instanceof Where) { - $this->where = $predicate; - } else { - $this->where->addPredicates($predicate, $combination); - } - return $this; - } - - /** - * Prepare the delete statement - * - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - * @return void - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - $driver = $adapter->getDriver(); - $platform = $adapter->getPlatform(); - $parameterContainer = $statementContainer->getParameterContainer(); - - if (!$parameterContainer instanceof ParameterContainer) { - $parameterContainer = new ParameterContainer(); - $statementContainer->setParameterContainer($parameterContainer); - } - - $table = $this->table; - $schema = null; - - // create quoted table name to use in delete processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - $table = $platform->quoteIdentifier($table); - - if ($schema) { - $table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table; - } - - $sql = sprintf($this->specifications[static::SPECIFICATION_DELETE], $table); - - // process where - if ($this->where->count() > 0) { - $whereParts = $this->processExpression($this->where, $platform, $driver, 'where'); - $parameterContainer->merge($whereParts->getParameterContainer()); - $sql .= ' ' . sprintf($this->specifications[static::SPECIFICATION_WHERE], $whereParts->getSql()); - } - $statementContainer->setSql($sql); - } - - /** - * Get the SQL string, based on the platform - * - * Platform defaults to Sql92 if none provided - * - * @param null|PlatformInterface $adapterPlatform - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - $adapterPlatform = ($adapterPlatform) ?: new Sql92; - $table = $this->table; - $schema = null; - - // create quoted table name to use in delete processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - $table = $adapterPlatform->quoteIdentifier($table); - - if ($schema) { - $table = $adapterPlatform->quoteIdentifier($schema) . $adapterPlatform->getIdentifierSeparator() . $table; - } - - $sql = sprintf($this->specifications[static::SPECIFICATION_DELETE], $table); - - if ($this->where->count() > 0) { - $whereParts = $this->processExpression($this->where, $adapterPlatform, null, 'where'); - $sql .= ' ' . sprintf($this->specifications[static::SPECIFICATION_WHERE], $whereParts->getSql()); - } - - return $sql; - } - - /** - * Property overloading - * - * Overloads "where" only. - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - switch (strtolower($name)) { - case 'where': - return $this->where; - } - } -} diff --git a/library/Zend/Db/Sql/Exception/ExceptionInterface.php b/library/Zend/Db/Sql/Exception/ExceptionInterface.php deleted file mode 100755 index 337266de8..000000000 --- a/library/Zend/Db/Sql/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -setExpression($expression); - } - if ($parameters) { - $this->setParameters($parameters); - } - if ($types) { - $this->setTypes($types); - } - } - - /** - * @param $expression - * @return Expression - * @throws Exception\InvalidArgumentException - */ - public function setExpression($expression) - { - if (!is_string($expression) || $expression == '') { - throw new Exception\InvalidArgumentException('Supplied expression must be a string.'); - } - $this->expression = $expression; - return $this; - } - - /** - * @return string - */ - public function getExpression() - { - return $this->expression; - } - - /** - * @param $parameters - * @return Expression - * @throws Exception\InvalidArgumentException - */ - public function setParameters($parameters) - { - if (!is_scalar($parameters) && !is_array($parameters)) { - throw new Exception\InvalidArgumentException('Expression parameters must be a scalar or array.'); - } - $this->parameters = $parameters; - return $this; - } - - /** - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * @param array $types - * @return Expression - */ - public function setTypes(array $types) - { - $this->types = $types; - return $this; - } - - /** - * @return array - */ - public function getTypes() - { - return $this->types; - } - - /** - * @return array - * @throws Exception\RuntimeException - */ - public function getExpressionData() - { - $parameters = (is_scalar($this->parameters)) ? array($this->parameters) : $this->parameters; - - $types = array(); - $parametersCount = count($parameters); - - if ($parametersCount == 0 && strpos($this->expression, self::PLACEHOLDER) !== false) { - // if there are no parameters, but there is a placeholder - $parametersCount = substr_count($this->expression, self::PLACEHOLDER); - $parameters = array_fill(0, $parametersCount, null); - } - - for ($i = 0; $i < $parametersCount; $i++) { - $types[$i] = (isset($this->types[$i]) && ($this->types[$i] == self::TYPE_IDENTIFIER || $this->types[$i] == self::TYPE_LITERAL)) - ? $this->types[$i] : self::TYPE_VALUE; - } - - // assign locally, escaping % signs - $expression = str_replace('%', '%%', $this->expression); - - if ($parametersCount > 0) { - $count = 0; - $expression = str_replace(self::PLACEHOLDER, '%s', $expression, $count); - if ($count !== $parametersCount) { - throw new Exception\RuntimeException('The number of replacements in the expression does not match the number of parameters'); - } - } - - return array(array( - $expression, - $parameters, - $types - )); - } -} diff --git a/library/Zend/Db/Sql/ExpressionInterface.php b/library/Zend/Db/Sql/ExpressionInterface.php deleted file mode 100755 index 99c929939..000000000 --- a/library/Zend/Db/Sql/ExpressionInterface.php +++ /dev/null @@ -1,36 +0,0 @@ - 'INSERT INTO %1$s (%2$s) VALUES (%3$s)', - self::SPECIFICATION_SELECT => 'INSERT INTO %1$s %2$s %3$s', - ); - - /** - * @var string|TableIdentifier - */ - protected $table = null; - protected $columns = array(); - - /** - * @var array|Select - */ - protected $values = null; - - /** - * Constructor - * - * @param null|string|TableIdentifier $table - */ - public function __construct($table = null) - { - if ($table) { - $this->into($table); - } - } - - /** - * Create INTO clause - * - * @param string|TableIdentifier $table - * @return Insert - */ - public function into($table) - { - $this->table = $table; - return $this; - } - - /** - * Specify columns - * - * @param array $columns - * @return Insert - */ - public function columns(array $columns) - { - $this->columns = $columns; - return $this; - } - - /** - * Specify values to insert - * - * @param array|Select $values - * @param string $flag one of VALUES_MERGE or VALUES_SET; defaults to VALUES_SET - * @throws Exception\InvalidArgumentException - * @return Insert - */ - public function values($values, $flag = self::VALUES_SET) - { - if (!is_array($values) && !$values instanceof Select) { - throw new Exception\InvalidArgumentException('values() expects an array of values or Zend\Db\Sql\Select instance'); - } - - if ($values instanceof Select) { - if ($flag == self::VALUES_MERGE && (is_array($this->values) && !empty($this->values))) { - throw new Exception\InvalidArgumentException( - 'A Zend\Db\Sql\Select instance cannot be provided with the merge flag when values already exist.' - ); - } - $this->values = $values; - return $this; - } - - // determine if this is assoc or a set of values - $keys = array_keys($values); - $firstKey = current($keys); - - if ($flag == self::VALUES_SET) { - $this->columns = array(); - $this->values = array(); - } elseif ($this->values instanceof Select) { - throw new Exception\InvalidArgumentException( - 'An array of values cannot be provided with the merge flag when a Zend\Db\Sql\Select' - . ' instance already exists as the value source.' - ); - } - - if (is_string($firstKey)) { - foreach ($keys as $key) { - if (($index = array_search($key, $this->columns)) !== false) { - $this->values[$index] = $values[$key]; - } else { - $this->columns[] = $key; - $this->values[] = $values[$key]; - } - } - } elseif (is_int($firstKey)) { - // determine if count of columns should match count of values - $this->values = array_merge($this->values, array_values($values)); - } - - return $this; - } - - /** - * Create INTO SELECT clause - * - * @param Select $select - * @return self - */ - public function select(Select $select) - { - return $this->values($select); - } - - /** - * Get raw state - * - * @param string $key - * @return mixed - */ - public function getRawState($key = null) - { - $rawState = array( - 'table' => $this->table, - 'columns' => $this->columns, - 'values' => $this->values - ); - return (isset($key) && array_key_exists($key, $rawState)) ? $rawState[$key] : $rawState; - } - - /** - * Prepare statement - * - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - * @return void - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - $driver = $adapter->getDriver(); - $platform = $adapter->getPlatform(); - $parameterContainer = $statementContainer->getParameterContainer(); - - if (!$parameterContainer instanceof ParameterContainer) { - $parameterContainer = new ParameterContainer(); - $statementContainer->setParameterContainer($parameterContainer); - } - - $table = $this->table; - $schema = null; - - // create quoted table name to use in insert processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - $table = $platform->quoteIdentifier($table); - - if ($schema) { - $table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table; - } - - $columns = array(); - $values = array(); - - if (is_array($this->values)) { - foreach ($this->columns as $cIndex => $column) { - $columns[$cIndex] = $platform->quoteIdentifier($column); - if (isset($this->values[$cIndex]) && $this->values[$cIndex] instanceof Expression) { - $exprData = $this->processExpression($this->values[$cIndex], $platform, $driver); - $values[$cIndex] = $exprData->getSql(); - $parameterContainer->merge($exprData->getParameterContainer()); - } else { - $values[$cIndex] = $driver->formatParameterName($column); - if (isset($this->values[$cIndex])) { - $parameterContainer->offsetSet($column, $this->values[$cIndex]); - } else { - $parameterContainer->offsetSet($column, null); - } - } - } - $sql = sprintf( - $this->specifications[static::SPECIFICATION_INSERT], - $table, - implode(', ', $columns), - implode(', ', $values) - ); - } elseif ($this->values instanceof Select) { - $this->values->prepareStatement($adapter, $statementContainer); - - $columns = array_map(array($platform, 'quoteIdentifier'), $this->columns); - $columns = implode(', ', $columns); - - $sql = sprintf( - $this->specifications[static::SPECIFICATION_SELECT], - $table, - $columns ? "($columns)" : "", - $statementContainer->getSql() - ); - } else { - throw new Exception\InvalidArgumentException('values or select should be present'); - } - $statementContainer->setSql($sql); - } - - /** - * Get SQL string for this statement - * - * @param null|PlatformInterface $adapterPlatform Defaults to Sql92 if none provided - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - $adapterPlatform = ($adapterPlatform) ?: new Sql92; - $table = $this->table; - $schema = null; - - // create quoted table name to use in insert processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - $table = $adapterPlatform->quoteIdentifier($table); - - if ($schema) { - $table = $adapterPlatform->quoteIdentifier($schema) . $adapterPlatform->getIdentifierSeparator() . $table; - } - - $columns = array_map(array($adapterPlatform, 'quoteIdentifier'), $this->columns); - $columns = implode(', ', $columns); - - if (is_array($this->values)) { - $values = array(); - foreach ($this->values as $value) { - if ($value instanceof Expression) { - $exprData = $this->processExpression($value, $adapterPlatform); - $values[] = $exprData->getSql(); - } elseif ($value === null) { - $values[] = 'NULL'; - } else { - $values[] = $adapterPlatform->quoteValue($value); - } - } - return sprintf( - $this->specifications[static::SPECIFICATION_INSERT], - $table, - $columns, - implode(', ', $values) - ); - } elseif ($this->values instanceof Select) { - $selectString = $this->values->getSqlString($adapterPlatform); - if ($columns) { - $columns = "($columns)"; - } - return sprintf( - $this->specifications[static::SPECIFICATION_SELECT], - $table, - $columns, - $selectString - ); - } else { - throw new Exception\InvalidArgumentException('values or select should be present'); - } - } - - /** - * Overloading: variable setting - * - * Proxies to values, using VALUES_MERGE strategy - * - * @param string $name - * @param mixed $value - * @return Insert - */ - public function __set($name, $value) - { - $values = array($name => $value); - $this->values($values, self::VALUES_MERGE); - return $this; - } - - /** - * Overloading: variable unset - * - * Proxies to values and columns - * - * @param string $name - * @throws Exception\InvalidArgumentException - * @return void - */ - public function __unset($name) - { - if (($position = array_search($name, $this->columns)) === false) { - throw new Exception\InvalidArgumentException('The key ' . $name . ' was not found in this objects column list'); - } - - unset($this->columns[$position]); - if (is_array($this->values)) { - unset($this->values[$position]); - } - } - - /** - * Overloading: variable isset - * - * Proxies to columns; does a column of that name exist? - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - return in_array($name, $this->columns); - } - - /** - * Overloading: variable retrieval - * - * Retrieves value by column name - * - * @param string $name - * @throws Exception\InvalidArgumentException - * @return mixed - */ - public function __get($name) - { - if (!is_array($this->values)) { - return null; - } - if (($position = array_search($name, $this->columns)) === false) { - throw new Exception\InvalidArgumentException('The key ' . $name . ' was not found in this objects column list'); - } - return $this->values[$position]; - } -} diff --git a/library/Zend/Db/Sql/Literal.php b/library/Zend/Db/Sql/Literal.php deleted file mode 100755 index ba67415a3..000000000 --- a/library/Zend/Db/Sql/Literal.php +++ /dev/null @@ -1,56 +0,0 @@ -literal = $literal; - } - - /** - * @param string $literal - * @return Literal - */ - public function setLiteral($literal) - { - $this->literal = $literal; - return $this; - } - - /** - * @return string - */ - public function getLiteral() - { - return $this->literal; - } - - /** - * @return array - */ - public function getExpressionData() - { - return array(array( - str_replace('%', '%%', $this->literal), - array(), - array() - )); - } -} diff --git a/library/Zend/Db/Sql/Platform/AbstractPlatform.php b/library/Zend/Db/Sql/Platform/AbstractPlatform.php deleted file mode 100755 index c5ddd6ce6..000000000 --- a/library/Zend/Db/Sql/Platform/AbstractPlatform.php +++ /dev/null @@ -1,110 +0,0 @@ -subject = $subject; - } - - /** - * @param $type - * @param PlatformDecoratorInterface $decorator - */ - public function setTypeDecorator($type, PlatformDecoratorInterface $decorator) - { - $this->decorators[$type] = $decorator; - } - - /** - * @return array|PlatformDecoratorInterface[] - */ - public function getDecorators() - { - return $this->decorators; - } - - /** - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - * @throws Exception\RuntimeException - * @return void - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - if (!$this->subject instanceof PreparableSqlInterface) { - throw new Exception\RuntimeException('The subject does not appear to implement Zend\Db\Sql\PreparableSqlInterface, thus calling prepareStatement() has no effect'); - } - - $decoratorForType = false; - foreach ($this->decorators as $type => $decorator) { - if ($this->subject instanceof $type && $decorator instanceof PreparableSqlInterface) { - /** @var $decoratorForType PreparableSqlInterface|PlatformDecoratorInterface */ - $decoratorForType = $decorator; - break; - } - } - if ($decoratorForType) { - $decoratorForType->setSubject($this->subject); - $decoratorForType->prepareStatement($adapter, $statementContainer); - } else { - $this->subject->prepareStatement($adapter, $statementContainer); - } - } - - /** - * @param null|\Zend\Db\Adapter\Platform\PlatformInterface $adapterPlatform - * @return mixed - * @throws Exception\RuntimeException - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - if (!$this->subject instanceof SqlInterface) { - throw new Exception\RuntimeException('The subject does not appear to implement Zend\Db\Sql\PreparableSqlInterface, thus calling prepareStatement() has no effect'); - } - - $decoratorForType = false; - foreach ($this->decorators as $type => $decorator) { - if ($this->subject instanceof $type && $decorator instanceof SqlInterface) { - /** @var $decoratorForType SqlInterface|PlatformDecoratorInterface */ - $decoratorForType = $decorator; - break; - } - } - if ($decoratorForType) { - $decoratorForType->setSubject($this->subject); - return $decoratorForType->getSqlString($adapterPlatform); - } - - return $this->subject->getSqlString($adapterPlatform); - } -} diff --git a/library/Zend/Db/Sql/Platform/IbmDb2/IbmDb2.php b/library/Zend/Db/Sql/Platform/IbmDb2/IbmDb2.php deleted file mode 100755 index f744bb470..000000000 --- a/library/Zend/Db/Sql/Platform/IbmDb2/IbmDb2.php +++ /dev/null @@ -1,23 +0,0 @@ -setTypeDecorator('Zend\Db\Sql\Select', ($selectDecorator) ?: new SelectDecorator()); - } -} diff --git a/library/Zend/Db/Sql/Platform/IbmDb2/SelectDecorator.php b/library/Zend/Db/Sql/Platform/IbmDb2/SelectDecorator.php deleted file mode 100755 index 4ad323694..000000000 --- a/library/Zend/Db/Sql/Platform/IbmDb2/SelectDecorator.php +++ /dev/null @@ -1,192 +0,0 @@ -isSelectContainDistinct; - } - - /** - * @param boolean $isSelectContainDistinct - */ - public function setIsSelectContainDistinct($isSelectContainDistinct) - { - $this->isSelectContainDistinct = $isSelectContainDistinct; - } - - /** - * @param Select $select - */ - public function setSubject($select) - { - $this->select = $select; - } - - /** - * @see Select::renderTable - */ - protected function renderTable($table, $alias = null) - { - return $table . ' ' . $alias; - } - - /** - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - // set specifications - unset($this->specifications[self::LIMIT]); - unset($this->specifications[self::OFFSET]); - - $this->specifications['LIMITOFFSET'] = null; - parent::prepareStatement($adapter, $statementContainer); - } - - /** - * @param PlatformInterface $platform - * @return string - */ - public function getSqlString(PlatformInterface $platform = null) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - - unset($this->specifications[self::LIMIT]); - unset($this->specifications[self::OFFSET]); - $this->specifications['LIMITOFFSET'] = null; - - return parent::getSqlString($platform); - } - - /** - * @param PlatformInterface $platform - * @param DriverInterface $driver - * @param ParameterContainer $parameterContainer - * @param array $sqls - * @param array $parameters - */ - protected function processLimitOffset(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null, &$sqls, &$parameters) - { - if ($this->limit === null && $this->offset === null) { - return; - } - - $selectParameters = $parameters[self::SELECT]; - - $starSuffix = $platform->getIdentifierSeparator() . self::SQL_STAR; - foreach ($selectParameters[0] as $i => $columnParameters) { - if ($columnParameters[0] == self::SQL_STAR - || (isset($columnParameters[1]) && $columnParameters[1] == self::SQL_STAR) - || strpos($columnParameters[0], $starSuffix) - ) { - $selectParameters[0] = array(array(self::SQL_STAR)); - break; - } - - if (isset($columnParameters[1])) { - array_shift($columnParameters); - $selectParameters[0][$i] = $columnParameters; - } - } - - // first, produce column list without compound names (using the AS portion only) - array_unshift($sqls, $this->createSqlFromSpecificationAndParameters( - array('SELECT %1$s FROM (' => current($this->specifications[self::SELECT])), - $selectParameters - )); - - if (preg_match('/DISTINCT/i', $sqls[0])) { - $this->setIsSelectContainDistinct(true); - } - - if ($parameterContainer) { - // create bottom part of query, with offset and limit using row_number - $limitParamName = $driver->formatParameterName('limit'); - $offsetParamName = $driver->formatParameterName('offset'); - - array_push($sqls, sprintf( - ") AS ZEND_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION WHERE ZEND_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION.ZEND_DB_ROWNUM BETWEEN %s AND %s", - $offsetParamName, - $limitParamName - )); - - if ((int) $this->offset > 0) { - $parameterContainer->offsetSet('offset', (int) $this->offset + 1); - } else { - $parameterContainer->offsetSet('offset', (int) $this->offset); - } - - $parameterContainer->offsetSet('limit', (int) $this->limit + (int) $this->offset); - } else { - if ((int) $this->offset > 0) { - $offset = (int) $this->offset + 1; - } else { - $offset = (int) $this->offset; - } - - array_push($sqls, sprintf( - ") AS ZEND_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION WHERE ZEND_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION.ZEND_DB_ROWNUM BETWEEN %d AND %d", - $offset, - (int) $this->limit + (int) $this->offset - )); - } - - if (isset($sqls[self::ORDER])) { - $orderBy = $sqls[self::ORDER]; - unset($sqls[self::ORDER]); - } else { - $orderBy = ''; - } - - // add a column for row_number() using the order specification //dense_rank() - if ($this->getIsSelectContainDistinct()) { - $parameters[self::SELECT][0][] = array('DENSE_RANK() OVER (' . $orderBy . ')', 'ZEND_DB_ROWNUM'); - } else { - $parameters[self::SELECT][0][] = array('ROW_NUMBER() OVER (' . $orderBy . ')', 'ZEND_DB_ROWNUM'); - } - - $sqls[self::SELECT] = $this->createSqlFromSpecificationAndParameters( - $this->specifications[self::SELECT], - $parameters[self::SELECT] - ); - } -} diff --git a/library/Zend/Db/Sql/Platform/Mysql/Ddl/CreateTableDecorator.php b/library/Zend/Db/Sql/Platform/Mysql/Ddl/CreateTableDecorator.php deleted file mode 100755 index d9cfa1556..000000000 --- a/library/Zend/Db/Sql/Platform/Mysql/Ddl/CreateTableDecorator.php +++ /dev/null @@ -1,86 +0,0 @@ -createTable = $subject; - } - - /** - * @param null|PlatformInterface $platform - * @return string - */ - public function getSqlString(PlatformInterface $platform = null) - { - // localize variables - foreach (get_object_vars($this->createTable) as $name => $value) { - $this->{$name} = $value; - } - return parent::getSqlString($platform); - } - - protected function processColumns(PlatformInterface $platform = null) - { - $sqls = array(); - foreach ($this->columns as $i => $column) { - $stmtContainer = $this->processExpression($column, $platform); - $sql = $stmtContainer->getSql(); - $columnOptions = $column->getOptions(); - - foreach ($columnOptions as $coName => $coValue) { - switch (strtolower(str_replace(array('-', '_', ' '), '', $coName))) { - case 'identity': - case 'serial': - case 'autoincrement': - $sql .= ' AUTO_INCREMENT'; - break; - /* - case 'primary': - case 'primarykey': - $sql .= ' PRIMARY KEY'; - break; - case 'unique': - case 'uniquekey': - $sql .= ' UNIQUE KEY'; - break; - */ - case 'comment': - $sql .= ' COMMENT \'' . $coValue . '\''; - break; - case 'columnformat': - case 'format': - $sql .= ' COLUMN_FORMAT ' . strtoupper($coValue); - break; - case 'storage': - $sql .= ' STORAGE ' . strtoupper($coValue); - break; - } - } - $stmtContainer->setSql($sql); - $sqls[$i] = $stmtContainer; - } - return array($sqls); - } -} diff --git a/library/Zend/Db/Sql/Platform/Mysql/Mysql.php b/library/Zend/Db/Sql/Platform/Mysql/Mysql.php deleted file mode 100755 index 80455869a..000000000 --- a/library/Zend/Db/Sql/Platform/Mysql/Mysql.php +++ /dev/null @@ -1,21 +0,0 @@ -setTypeDecorator('Zend\Db\Sql\Select', new SelectDecorator()); - $this->setTypeDecorator('Zend\Db\Sql\Ddl\CreateTable', new Ddl\CreateTableDecorator()); - } -} diff --git a/library/Zend/Db/Sql/Platform/Mysql/SelectDecorator.php b/library/Zend/Db/Sql/Platform/Mysql/SelectDecorator.php deleted file mode 100755 index 5c4678a73..000000000 --- a/library/Zend/Db/Sql/Platform/Mysql/SelectDecorator.php +++ /dev/null @@ -1,97 +0,0 @@ -select = $select; - } - - /** - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - if ($this->limit === null && $this->offset !== null) { - $this->specifications[self::LIMIT] = 'LIMIT 18446744073709551615'; - } - parent::prepareStatement($adapter, $statementContainer); - } - - /** - * @param PlatformInterface $platform - * @return string - */ - public function getSqlString(PlatformInterface $platform = null) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - if ($this->limit === null && $this->offset !== null) { - $this->specifications[self::LIMIT] = 'LIMIT 18446744073709551615'; - } - return parent::getSqlString($platform); - } - - protected function processLimit(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->limit === null && $this->offset !== null) { - return array(''); - } - if ($this->limit === null) { - return null; - } - if ($driver) { - $sql = $driver->formatParameterName('limit'); - $parameterContainer->offsetSet('limit', $this->limit, ParameterContainer::TYPE_INTEGER); - } else { - $sql = $this->limit; - } - - return array($sql); - } - - protected function processOffset(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->offset === null) { - return null; - } - if ($driver) { - $parameterContainer->offsetSet('offset', $this->offset, ParameterContainer::TYPE_INTEGER); - return array($driver->formatParameterName('offset')); - } - - return array($this->offset); - } -} diff --git a/library/Zend/Db/Sql/Platform/Oracle/Oracle.php b/library/Zend/Db/Sql/Platform/Oracle/Oracle.php deleted file mode 100755 index e5af22fa9..000000000 --- a/library/Zend/Db/Sql/Platform/Oracle/Oracle.php +++ /dev/null @@ -1,20 +0,0 @@ -setTypeDecorator('Zend\Db\Sql\Select', ($selectDecorator) ?: new SelectDecorator()); - } -} diff --git a/library/Zend/Db/Sql/Platform/Oracle/SelectDecorator.php b/library/Zend/Db/Sql/Platform/Oracle/SelectDecorator.php deleted file mode 100755 index 457c696bb..000000000 --- a/library/Zend/Db/Sql/Platform/Oracle/SelectDecorator.php +++ /dev/null @@ -1,180 +0,0 @@ -select = $select; - } - - /** - * @see \Zend\Db\Sql\Select::renderTable - */ - protected function renderTable($table, $alias = null) - { - return $table . ' ' . $alias; - } - - /** - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - // set specifications - unset($this->specifications[self::LIMIT]); - unset($this->specifications[self::OFFSET]); - - $this->specifications['LIMITOFFSET'] = null; - parent::prepareStatement($adapter, $statementContainer); - } - - /** - * @param PlatformInterface $platform - * @return string - */ - public function getSqlString(PlatformInterface $platform = null) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - - // set specifications - unset($this->specifications[self::LIMIT]); - unset($this->specifications[self::OFFSET]); - - $this->specifications['LIMITOFFSET'] = null; - return parent::getSqlString($platform); - } - - /** - * @param PlatformInterface $platform - * @param DriverInterface $driver - * @param ParameterContainer $parameterContainer - * @param $sqls - * @param $parameters - * @return null - */ - protected function processLimitOffset(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null, &$sqls, &$parameters) - { - if ($this->limit === null && $this->offset === null) { - return null; - } - - $selectParameters = $parameters[self::SELECT]; - - $starSuffix = $platform->getIdentifierSeparator() . self::SQL_STAR; - foreach ($selectParameters[0] as $i => $columnParameters) { - if ($columnParameters[0] == self::SQL_STAR || (isset($columnParameters[1]) && $columnParameters[1] == self::SQL_STAR) || strpos($columnParameters[0], $starSuffix)) { - $selectParameters[0] = array(array(self::SQL_STAR)); - break; - } - if (isset($columnParameters[1])) { - array_shift($columnParameters); - $selectParameters[0][$i] = $columnParameters; - } - } - - if ($this->offset === null) { - $this->offset = 0; - } - - // first, produce column list without compound names (using the AS portion only) - array_unshift($sqls, $this->createSqlFromSpecificationAndParameters( - array('SELECT %1$s FROM (SELECT b.%1$s, rownum b_rownum FROM (' => current($this->specifications[self::SELECT])), $selectParameters - )); - - if ($parameterContainer) { - if ($this->limit === null) { - array_push($sqls, ') b ) WHERE b_rownum > (:offset)'); - $parameterContainer->offsetSet('offset', $this->offset, $parameterContainer::TYPE_INTEGER); - } else { - // create bottom part of query, with offset and limit using row_number - array_push($sqls, ') b WHERE rownum <= (:offset+:limit)) WHERE b_rownum >= (:offset + 1)'); - $parameterContainer->offsetSet('offset', $this->offset, $parameterContainer::TYPE_INTEGER); - $parameterContainer->offsetSet('limit', $this->limit, $parameterContainer::TYPE_INTEGER); - } - } else { - if ($this->limit === null) { - array_push($sqls, ') b ) WHERE b_rownum > ('. (int) $this->offset. ')' - ); - } else { - array_push($sqls, ') b WHERE rownum <= (' - . (int) $this->offset - . '+' - . (int) $this->limit - . ')) WHERE b_rownum >= (' - . (int) $this->offset - . ' + 1)' - ); - } - } - - $sqls[self::SELECT] = $this->createSqlFromSpecificationAndParameters( - $this->specifications[self::SELECT], $parameters[self::SELECT] - ); - } - - - protected function processJoins(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if (!$this->joins) { - return null; - } - - // process joins - $joinSpecArgArray = array(); - foreach ($this->joins as $j => $join) { - $joinSpecArgArray[$j] = array(); - // type - $joinSpecArgArray[$j][] = strtoupper($join['type']); - // table name - $joinSpecArgArray[$j][] = (is_array($join['name'])) - ? $platform->quoteIdentifier(current($join['name'])) . ' ' . $platform->quoteIdentifier(key($join['name'])) - : $platform->quoteIdentifier($join['name']); - // on expression - $joinSpecArgArray[$j][] = ($join['on'] instanceof ExpressionInterface) - ? $this->processExpression($join['on'], $platform, $driver, $this->processInfo['paramPrefix'] . 'join') - : $platform->quoteIdentifierInFragment($join['on'], array('=', 'AND', 'OR', '(', ')', 'BETWEEN')); // on - if ($joinSpecArgArray[$j][2] instanceof StatementContainerInterface) { - if ($parameterContainer) { - $parameterContainer->merge($joinSpecArgArray[$j][2]->getParameterContainer()); - } - $joinSpecArgArray[$j][2] = $joinSpecArgArray[$j][2]->getSql(); - } - } - - return array($joinSpecArgArray); - } -} diff --git a/library/Zend/Db/Sql/Platform/Platform.php b/library/Zend/Db/Sql/Platform/Platform.php deleted file mode 100755 index 4a6fc2e98..000000000 --- a/library/Zend/Db/Sql/Platform/Platform.php +++ /dev/null @@ -1,46 +0,0 @@ -adapter = $adapter; - $platform = $adapter->getPlatform(); - switch (strtolower($platform->getName())) { - case 'mysql': - $platform = new Mysql\Mysql(); - $this->decorators = $platform->decorators; - break; - case 'sqlserver': - $platform = new SqlServer\SqlServer(); - $this->decorators = $platform->decorators; - break; - case 'oracle': - $platform = new Oracle\Oracle(); - $this->decorators = $platform->decorators; - break; - case 'ibm db2': - case 'ibm_db2': - case 'ibmdb2': - $platform = new IbmDb2\IbmDb2(); - $this->decorators = $platform->decorators; - default: - } - } -} diff --git a/library/Zend/Db/Sql/Platform/PlatformDecoratorInterface.php b/library/Zend/Db/Sql/Platform/PlatformDecoratorInterface.php deleted file mode 100755 index 2ff7c97ce..000000000 --- a/library/Zend/Db/Sql/Platform/PlatformDecoratorInterface.php +++ /dev/null @@ -1,15 +0,0 @@ -createTable = $subject; - return $this; - } - - /** - * @param null|PlatformInterface $platform - * @return string - */ - public function getSqlString(PlatformInterface $platform = null) - { - // localize variables - foreach (get_object_vars($this->createTable) as $name => $value) { - $this->{$name} = $value; - } - return parent::getSqlString($platform); - } - - /** - * @param PlatformInterface $adapterPlatform - * @return array - */ - protected function processTable(PlatformInterface $adapterPlatform = null) - { - $ret = array(''); - if ($this->isTemporary) { - $table = '#'; - } else { - $table = ''; - } - $ret[] = $adapterPlatform->quoteIdentifier($table . ltrim($this->table, '#')); - return $ret; - } -} diff --git a/library/Zend/Db/Sql/Platform/SqlServer/SelectDecorator.php b/library/Zend/Db/Sql/Platform/SqlServer/SelectDecorator.php deleted file mode 100755 index 7667ebcbd..000000000 --- a/library/Zend/Db/Sql/Platform/SqlServer/SelectDecorator.php +++ /dev/null @@ -1,145 +0,0 @@ -select = $select; - } - - /** - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - - // set specifications - unset($this->specifications[self::LIMIT]); - unset($this->specifications[self::OFFSET]); - - $this->specifications['LIMITOFFSET'] = null; - parent::prepareStatement($adapter, $statementContainer); - - //set statement cursor type - if ($statementContainer instanceof Statement) { - $statementContainer->setPrepareOptions(array('Scrollable'=>\SQLSRV_CURSOR_STATIC)); - } - } - - /** - * @param PlatformInterface $platform - * @return string - */ - public function getSqlString(PlatformInterface $platform = null) - { - // localize variables - foreach (get_object_vars($this->select) as $name => $value) { - $this->{$name} = $value; - } - - // set specifications - unset($this->specifications[self::LIMIT]); - unset($this->specifications[self::OFFSET]); - - $this->specifications['LIMITOFFSET'] = null; - return parent::getSqlString($platform); - } - - /** - * @param PlatformInterface $platform - * @param DriverInterface $driver - * @param ParameterContainer $parameterContainer - * @param $sqls - * @param $parameters - * @return null - */ - protected function processLimitOffset(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null, &$sqls, &$parameters) - { - if ($this->limit === null && $this->offset === null) { - return null; - } - - $selectParameters = $parameters[self::SELECT]; - - $starSuffix = $platform->getIdentifierSeparator() . self::SQL_STAR; - foreach ($selectParameters[0] as $i => $columnParameters) { - if ($columnParameters[0] == self::SQL_STAR || (isset($columnParameters[1]) && $columnParameters[1] == self::SQL_STAR) || strpos($columnParameters[0], $starSuffix)) { - $selectParameters[0] = array(array(self::SQL_STAR)); - break; - } - if (isset($columnParameters[1])) { - array_shift($columnParameters); - $selectParameters[0][$i] = $columnParameters; - } - } - - // first, produce column list without compound names (using the AS portion only) - array_unshift($sqls, $this->createSqlFromSpecificationAndParameters( - array('SELECT %1$s FROM (' => current($this->specifications[self::SELECT])), - $selectParameters - )); - - if ($parameterContainer) { - // create bottom part of query, with offset and limit using row_number - $limitParamName = $driver->formatParameterName('limit'); - $offsetParamName = $driver->formatParameterName('offset'); - $offsetForSumParamName = $driver->formatParameterName('offsetForSum'); - array_push($sqls, ') AS [ZEND_SQL_SERVER_LIMIT_OFFSET_EMULATION] WHERE [ZEND_SQL_SERVER_LIMIT_OFFSET_EMULATION].[__ZEND_ROW_NUMBER] BETWEEN ' - . $offsetParamName . '+1 AND ' . $limitParamName . '+' . $offsetForSumParamName); - $parameterContainer->offsetSet('offset', $this->offset); - $parameterContainer->offsetSet('limit', $this->limit); - $parameterContainer->offsetSetReference('offsetForSum', 'offset'); - } else { - array_push($sqls, ') AS [ZEND_SQL_SERVER_LIMIT_OFFSET_EMULATION] WHERE [ZEND_SQL_SERVER_LIMIT_OFFSET_EMULATION].[__ZEND_ROW_NUMBER] BETWEEN ' - . (int) $this->offset . '+1 AND ' - . (int) $this->limit . '+' . (int) $this->offset - ); - } - - if (isset($sqls[self::ORDER])) { - $orderBy = $sqls[self::ORDER]; - unset($sqls[self::ORDER]); - } else { - $orderBy = 'ORDER BY (SELECT 1)'; - } - - // add a column for row_number() using the order specification - $parameters[self::SELECT][0][] = array('ROW_NUMBER() OVER (' . $orderBy . ')', '[__ZEND_ROW_NUMBER]'); - - $sqls[self::SELECT] = $this->createSqlFromSpecificationAndParameters( - $this->specifications[self::SELECT], - $parameters[self::SELECT] - ); - } -} diff --git a/library/Zend/Db/Sql/Platform/SqlServer/SqlServer.php b/library/Zend/Db/Sql/Platform/SqlServer/SqlServer.php deleted file mode 100755 index ed72b77aa..000000000 --- a/library/Zend/Db/Sql/Platform/SqlServer/SqlServer.php +++ /dev/null @@ -1,21 +0,0 @@ -setTypeDecorator('Zend\Db\Sql\Select', ($selectDecorator) ?: new SelectDecorator()); - $this->setTypeDecorator('Zend\Db\Sql\Ddl\CreateTable', new Ddl\CreateTableDecorator()); - } -} diff --git a/library/Zend/Db/Sql/Predicate/Between.php b/library/Zend/Db/Sql/Predicate/Between.php deleted file mode 100755 index 686b65db5..000000000 --- a/library/Zend/Db/Sql/Predicate/Between.php +++ /dev/null @@ -1,142 +0,0 @@ -setIdentifier($identifier); - } - if ($minValue !== null) { - $this->setMinValue($minValue); - } - if ($maxValue !== null) { - $this->setMaxValue($maxValue); - } - } - - /** - * Set identifier for comparison - * - * @param string $identifier - * @return Between - */ - public function setIdentifier($identifier) - { - $this->identifier = $identifier; - return $this; - } - - /** - * Get identifier of comparison - * - * @return null|string - */ - public function getIdentifier() - { - return $this->identifier; - } - - /** - * Set minimum boundary for comparison - * - * @param int|float|string $minValue - * @return Between - */ - public function setMinValue($minValue) - { - $this->minValue = $minValue; - return $this; - } - - /** - * Get minimum boundary for comparison - * - * @return null|int|float|string - */ - public function getMinValue() - { - return $this->minValue; - } - - /** - * Set maximum boundary for comparison - * - * @param int|float|string $maxValue - * @return Between - */ - public function setMaxValue($maxValue) - { - $this->maxValue = $maxValue; - return $this; - } - - /** - * Get maximum boundary for comparison - * - * @return null|int|float|string - */ - public function getMaxValue() - { - return $this->maxValue; - } - - /** - * Set specification string to use in forming SQL predicate - * - * @param string $specification - * @return Between - */ - public function setSpecification($specification) - { - $this->specification = $specification; - return $this; - } - - /** - * Get specification string to use in forming SQL predicate - * - * @return string - */ - public function getSpecification() - { - return $this->specification; - } - - /** - * Return "where" parts - * - * @return array - */ - public function getExpressionData() - { - return array( - array( - $this->getSpecification(), - array($this->identifier, $this->minValue, $this->maxValue), - array(self::TYPE_IDENTIFIER, self::TYPE_VALUE, self::TYPE_VALUE), - ), - ); - } -} diff --git a/library/Zend/Db/Sql/Predicate/Expression.php b/library/Zend/Db/Sql/Predicate/Expression.php deleted file mode 100755 index 4822dd081..000000000 --- a/library/Zend/Db/Sql/Predicate/Expression.php +++ /dev/null @@ -1,41 +0,0 @@ -setExpression($expression); - } - - if (is_array($valueParameter)) { - $this->setParameters($valueParameter); - } else { - $argNum = func_num_args(); - if ($argNum > 2 || is_scalar($valueParameter)) { - $parameters = array(); - for ($i = 1; $i < $argNum; $i++) { - $parameters[] = func_get_arg($i); - } - $this->setParameters($parameters); - } - } - } -} diff --git a/library/Zend/Db/Sql/Predicate/In.php b/library/Zend/Db/Sql/Predicate/In.php deleted file mode 100755 index eb7ccc36c..000000000 --- a/library/Zend/Db/Sql/Predicate/In.php +++ /dev/null @@ -1,133 +0,0 @@ -setIdentifier($identifier); - } - if ($valueSet) { - $this->setValueSet($valueSet); - } - } - - /** - * Set identifier for comparison - * - * @param string|array $identifier - * @return In - */ - public function setIdentifier($identifier) - { - $this->identifier = $identifier; - - return $this; - } - - /** - * Get identifier of comparison - * - * @return null|string|array - */ - public function getIdentifier() - { - return $this->identifier; - } - - /** - * Set set of values for IN comparison - * - * @param array|Select $valueSet - * @throws Exception\InvalidArgumentException - * @return In - */ - public function setValueSet($valueSet) - { - if (!is_array($valueSet) && !$valueSet instanceof Select) { - throw new Exception\InvalidArgumentException( - '$valueSet must be either an array or a Zend\Db\Sql\Select object, ' . gettype($valueSet) . ' given' - ); - } - $this->valueSet = $valueSet; - - return $this; - } - - /** - * Gets set of values in IN comparision - * - * @return array|Select - */ - public function getValueSet() - { - return $this->valueSet; - } - - /** - * Return array of parts for where statement - * - * @return array - */ - public function getExpressionData() - { - $identifier = $this->getIdentifier(); - $values = $this->getValueSet(); - $replacements = array(); - - if (is_array($identifier)) { - $identifierSpecFragment = '(' . implode(', ', array_fill(0, count($identifier), '%s')) . ')'; - $types = array_fill(0, count($identifier), self::TYPE_IDENTIFIER); - $replacements = $identifier; - } else { - $identifierSpecFragment = '%s'; - $replacements[] = $identifier; - $types = array(self::TYPE_IDENTIFIER); - } - - if ($values instanceof Select) { - $specification = vsprintf( - $this->specification, - array($identifierSpecFragment, '%s') - ); - $replacements[] = $values; - $types[] = self::TYPE_VALUE; - } else { - $specification = vsprintf( - $this->specification, - array($identifierSpecFragment, '(' . implode(', ', array_fill(0, count($values), '%s')) . ')') - ); - $replacements = array_merge($replacements, $values); - $types = array_merge($types, array_fill(0, count($values), self::TYPE_VALUE)); - } - - return array(array( - $specification, - $replacements, - $types, - )); - } -} diff --git a/library/Zend/Db/Sql/Predicate/IsNotNull.php b/library/Zend/Db/Sql/Predicate/IsNotNull.php deleted file mode 100755 index e09f34912..000000000 --- a/library/Zend/Db/Sql/Predicate/IsNotNull.php +++ /dev/null @@ -1,15 +0,0 @@ -setIdentifier($identifier); - } - } - - /** - * Set identifier for comparison - * - * @param string $identifier - * @return IsNull - */ - public function setIdentifier($identifier) - { - $this->identifier = $identifier; - return $this; - } - - /** - * Get identifier of comparison - * - * @return null|string - */ - public function getIdentifier() - { - return $this->identifier; - } - - /** - * Set specification string to use in forming SQL predicate - * - * @param string $specification - * @return IsNull - */ - public function setSpecification($specification) - { - $this->specification = $specification; - return $this; - } - - /** - * Get specification string to use in forming SQL predicate - * - * @return string - */ - public function getSpecification() - { - return $this->specification; - } - - /** - * Get parts for where statement - * - * @return array - */ - public function getExpressionData() - { - return array(array( - $this->getSpecification(), - array($this->identifier), - array(self::TYPE_IDENTIFIER), - )); - } -} diff --git a/library/Zend/Db/Sql/Predicate/Like.php b/library/Zend/Db/Sql/Predicate/Like.php deleted file mode 100755 index b5d6676fe..000000000 --- a/library/Zend/Db/Sql/Predicate/Like.php +++ /dev/null @@ -1,106 +0,0 @@ -setIdentifier($identifier); - } - if ($like) { - $this->setLike($like); - } - } - - /** - * @param string $identifier - * @return self - */ - public function setIdentifier($identifier) - { - $this->identifier = $identifier; - return $this; - } - - /** - * @return string - */ - public function getIdentifier() - { - return $this->identifier; - } - - /** - * @param string $like - * @return self - */ - public function setLike($like) - { - $this->like = $like; - return $this; - } - - /** - * @return string - */ - public function getLike() - { - return $this->like; - } - - /** - * @param string $specification - * @return self - */ - public function setSpecification($specification) - { - $this->specification = $specification; - return $this; - } - - /** - * @return string - */ - public function getSpecification() - { - return $this->specification; - } - - /** - * @return array - */ - public function getExpressionData() - { - return array( - array($this->specification, array($this->identifier, $this->like), array(self::TYPE_IDENTIFIER, self::TYPE_VALUE)) - ); - } -} diff --git a/library/Zend/Db/Sql/Predicate/Literal.php b/library/Zend/Db/Sql/Predicate/Literal.php deleted file mode 100755 index 5ee68c998..000000000 --- a/library/Zend/Db/Sql/Predicate/Literal.php +++ /dev/null @@ -1,16 +0,0 @@ -'; - const OP_GT = '>'; - - const OPERATOR_GREATER_THAN_OR_EQUAL_TO = '>='; - const OP_GTE = '>='; - - protected $allowedTypes = array( - self::TYPE_IDENTIFIER, - self::TYPE_VALUE, - ); - - protected $left = null; - protected $leftType = self::TYPE_IDENTIFIER; - protected $operator = self::OPERATOR_EQUAL_TO; - protected $right = null; - protected $rightType = self::TYPE_VALUE; - - /** - * Constructor - * - * @param int|float|bool|string $left - * @param string $operator - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - */ - public function __construct($left = null, $operator = self::OPERATOR_EQUAL_TO, $right = null, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - if ($left !== null) { - $this->setLeft($left); - } - - if ($operator !== self::OPERATOR_EQUAL_TO) { - $this->setOperator($operator); - } - - if ($right !== null) { - $this->setRight($right); - } - - if ($leftType !== self::TYPE_IDENTIFIER) { - $this->setLeftType($leftType); - } - - if ($rightType !== self::TYPE_VALUE) { - $this->setRightType($rightType); - } - } - - /** - * Set left side of operator - * - * @param int|float|bool|string $left - * @return Operator - */ - public function setLeft($left) - { - $this->left = $left; - return $this; - } - - /** - * Get left side of operator - * - * @return int|float|bool|string - */ - public function getLeft() - { - return $this->left; - } - - /** - * Set parameter type for left side of operator - * - * @param string $type TYPE_IDENTIFIER or TYPE_VALUE {@see allowedTypes} - * @throws Exception\InvalidArgumentException - * @return Operator - */ - public function setLeftType($type) - { - if (!in_array($type, $this->allowedTypes)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid type "%s" provided; must be of type "%s" or "%s"', - $type, - __CLASS__ . '::TYPE_IDENTIFIER', - __CLASS__ . '::TYPE_VALUE' - )); - } - $this->leftType = $type; - return $this; - } - - /** - * Get parameter type on left side of operator - * - * @return string - */ - public function getLeftType() - { - return $this->leftType; - } - - /** - * Set operator string - * - * @param string $operator - * @return Operator - */ - public function setOperator($operator) - { - $this->operator = $operator; - return $this; - } - - /** - * Get operator string - * - * @return string - */ - public function getOperator() - { - return $this->operator; - } - - /** - * Set right side of operator - * - * @param int|float|bool|string $value - * @return Operator - */ - public function setRight($value) - { - $this->right = $value; - return $this; - } - - /** - * Get right side of operator - * - * @return int|float|bool|string - */ - public function getRight() - { - return $this->right; - } - - /** - * Set parameter type for right side of operator - * - * @param string $type TYPE_IDENTIFIER or TYPE_VALUE {@see allowedTypes} - * @throws Exception\InvalidArgumentException - * @return Operator - */ - public function setRightType($type) - { - if (!in_array($type, $this->allowedTypes)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid type "%s" provided; must be of type "%s" or "%s"', - $type, - __CLASS__ . '::TYPE_IDENTIFIER', - __CLASS__ . '::TYPE_VALUE' - )); - } - $this->rightType = $type; - return $this; - } - - /** - * Get parameter type on right side of operator - * - * @return string - */ - public function getRightType() - { - return $this->rightType; - } - - /** - * Get predicate parts for where statement - * - * @return array - */ - public function getExpressionData() - { - return array(array( - '%s ' . $this->operator . ' %s', - array($this->left, $this->right), - array($this->leftType, $this->rightType) - )); - } -} diff --git a/library/Zend/Db/Sql/Predicate/Predicate.php b/library/Zend/Db/Sql/Predicate/Predicate.php deleted file mode 100755 index e9ef5757d..000000000 --- a/library/Zend/Db/Sql/Predicate/Predicate.php +++ /dev/null @@ -1,409 +0,0 @@ -setUnnest($this); - $this->addPredicate($predicateSet, ($this->nextPredicateCombineOperator) ?: $this->defaultCombination); - $this->nextPredicateCombineOperator = null; - return $predicateSet; - } - - /** - * Indicate what predicate will be unnested - * - * @param Predicate $predicate - * @return void - */ - public function setUnnest(Predicate $predicate) - { - $this->unnest = $predicate; - } - - /** - * Indicate end of nested predicate - * - * @return Predicate - * @throws RuntimeException - */ - public function unnest() - { - if ($this->unnest == null) { - throw new RuntimeException('Not nested'); - } - $unnset = $this->unnest; - $this->unnest = null; - return $unnset; - } - - /** - * Create "Equal To" predicate - * - * Utilizes Operator predicate - * - * @param int|float|bool|string $left - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - * @return Predicate - */ - public function equalTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - $this->addPredicate( - new Operator($left, Operator::OPERATOR_EQUAL_TO, $right, $leftType, $rightType), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Not Equal To" predicate - * - * Utilizes Operator predicate - * - * @param int|float|bool|string $left - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - * @return Predicate - */ - public function notEqualTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - $this->addPredicate( - new Operator($left, Operator::OPERATOR_NOT_EQUAL_TO, $right, $leftType, $rightType), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Less Than" predicate - * - * Utilizes Operator predicate - * - * @param int|float|bool|string $left - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - * @return Predicate - */ - public function lessThan($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - $this->addPredicate( - new Operator($left, Operator::OPERATOR_LESS_THAN, $right, $leftType, $rightType), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Greater Than" predicate - * - * Utilizes Operator predicate - * - * @param int|float|bool|string $left - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - * @return Predicate - */ - public function greaterThan($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - $this->addPredicate( - new Operator($left, Operator::OPERATOR_GREATER_THAN, $right, $leftType, $rightType), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Less Than Or Equal To" predicate - * - * Utilizes Operator predicate - * - * @param int|float|bool|string $left - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - * @return Predicate - */ - public function lessThanOrEqualTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - $this->addPredicate( - new Operator($left, Operator::OPERATOR_LESS_THAN_OR_EQUAL_TO, $right, $leftType, $rightType), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Greater Than Or Equal To" predicate - * - * Utilizes Operator predicate - * - * @param int|float|bool|string $left - * @param int|float|bool|string $right - * @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes} - * @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes} - * @return Predicate - */ - public function greaterThanOrEqualTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE) - { - $this->addPredicate( - new Operator($left, Operator::OPERATOR_GREATER_THAN_OR_EQUAL_TO, $right, $leftType, $rightType), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Like" predicate - * - * Utilizes Like predicate - * - * @param string $identifier - * @param string $like - * @return Predicate - */ - public function like($identifier, $like) - { - $this->addPredicate( - new Like($identifier, $like), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - /** - * Create "notLike" predicate - * - * Utilizes In predicate - * - * @param string $identifier - * @param string $notLike - * @return Predicate - */ - public function notLike($identifier, $notLike) - { - $this->addPredicate( - new NotLike($identifier, $notLike), - ($this->nextPredicateCombineOperator) ? : $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - return $this; - } - - /** - * Create an expression, with parameter placeholders - * - * @param $expression - * @param $parameters - * @return $this - */ - public function expression($expression, $parameters) - { - $this->addPredicate( - new Expression($expression, $parameters), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "Literal" predicate - * - * Literal predicate, for parameters, use expression() - * - * @param string $literal - * @return Predicate - */ - public function literal($literal) - { - // process deprecated parameters from previous literal($literal, $parameters = null) signature - if (func_num_args() >= 2) { - $parameters = func_get_arg(1); - $predicate = new Expression($literal, $parameters); - } - - // normal workflow for "Literals" here - if (!isset($predicate)) { - $predicate = new Literal($literal); - } - - $this->addPredicate( - $predicate, - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "IS NULL" predicate - * - * Utilizes IsNull predicate - * - * @param string $identifier - * @return Predicate - */ - public function isNull($identifier) - { - $this->addPredicate( - new IsNull($identifier), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "IS NOT NULL" predicate - * - * Utilizes IsNotNull predicate - * - * @param string $identifier - * @return Predicate - */ - public function isNotNull($identifier) - { - $this->addPredicate( - new IsNotNull($identifier), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "IN" predicate - * - * Utilizes In predicate - * - * @param string $identifier - * @param array|\Zend\Db\Sql\Select $valueSet - * @return Predicate - */ - public function in($identifier, $valueSet = null) - { - $this->addPredicate( - new In($identifier, $valueSet), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "NOT IN" predicate - * - * Utilizes NotIn predicate - * - * @param string $identifier - * @param array|\Zend\Db\Sql\Select $valueSet - * @return Predicate - */ - public function notIn($identifier, $valueSet = null) - { - $this->addPredicate( - new NotIn($identifier, $valueSet), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Create "between" predicate - * - * Utilizes Between predicate - * - * @param string $identifier - * @param int|float|string $minValue - * @param int|float|string $maxValue - * @return Predicate - */ - public function between($identifier, $minValue, $maxValue) - { - $this->addPredicate( - new Between($identifier, $minValue, $maxValue), - ($this->nextPredicateCombineOperator) ?: $this->defaultCombination - ); - $this->nextPredicateCombineOperator = null; - - return $this; - } - - /** - * Overloading - * - * Overloads "or", "and", "nest", and "unnest" - * - * @param string $name - * @return Predicate - */ - public function __get($name) - { - switch (strtolower($name)) { - case 'or': - $this->nextPredicateCombineOperator = self::OP_OR; - break; - case 'and': - $this->nextPredicateCombineOperator = self::OP_AND; - break; - case 'nest': - return $this->nest(); - case 'unnest': - return $this->unnest(); - } - return $this; - } -} diff --git a/library/Zend/Db/Sql/Predicate/PredicateInterface.php b/library/Zend/Db/Sql/Predicate/PredicateInterface.php deleted file mode 100755 index 68b197f84..000000000 --- a/library/Zend/Db/Sql/Predicate/PredicateInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -defaultCombination = $defaultCombination; - if ($predicates) { - foreach ($predicates as $predicate) { - $this->addPredicate($predicate); - } - } - } - - /** - * Add predicate to set - * - * @param PredicateInterface $predicate - * @param string $combination - * @return PredicateSet - */ - public function addPredicate(PredicateInterface $predicate, $combination = null) - { - if ($combination === null || !in_array($combination, array(self::OP_AND, self::OP_OR))) { - $combination = $this->defaultCombination; - } - - if ($combination == self::OP_OR) { - $this->orPredicate($predicate); - return $this; - } - - $this->andPredicate($predicate); - return $this; - } - - public function addPredicates($predicates, $combination = self::OP_AND) - { - if ($predicates === null) { - throw new Exception\InvalidArgumentException('Predicate cannot be null'); - } - if ($predicates instanceof PredicateInterface) { - $this->addPredicate($predicates, $combination); - return $this; - } - if ($predicates instanceof \Closure) { - $predicates($this); - return $this; - } - if (is_string($predicates)) { - // String $predicate should be passed as an expression - $predicates = (strpos($predicates, Expression::PLACEHOLDER) !== false) - ? new Expression($predicates) : new Literal($predicates); - $this->addPredicate($predicates, $combination); - return $this; - } - if (is_array($predicates)) { - foreach ($predicates as $pkey => $pvalue) { - // loop through predicates - if (is_string($pkey)) { - if (strpos($pkey, '?') !== false) { - // First, process strings that the abstraction replacement character ? - // as an Expression predicate - $predicates = new Expression($pkey, $pvalue); - } elseif ($pvalue === null) { // Otherwise, if still a string, do something intelligent with the PHP type provided - // map PHP null to SQL IS NULL expression - $predicates = new IsNull($pkey, $pvalue); - } elseif (is_array($pvalue)) { - // if the value is an array, assume IN() is desired - $predicates = new In($pkey, $pvalue); - } elseif ($pvalue instanceof PredicateInterface) { - throw new Exception\InvalidArgumentException( - 'Using Predicate must not use string keys' - ); - } else { - // otherwise assume that array('foo' => 'bar') means "foo" = 'bar' - $predicates = new Operator($pkey, Operator::OP_EQ, $pvalue); - } - } elseif ($pvalue instanceof PredicateInterface) { - // Predicate type is ok - $predicates = $pvalue; - } else { - // must be an array of expressions (with int-indexed array) - $predicates = (strpos($pvalue, Expression::PLACEHOLDER) !== false) - ? new Expression($pvalue) : new Literal($pvalue); - } - $this->addPredicate($predicates, $combination); - } - } - return $this; - } - - /** - * Return the predicates - * - * @return PredicateInterface[] - */ - public function getPredicates() - { - return $this->predicates; - } - - /** - * Add predicate using OR operator - * - * @param PredicateInterface $predicate - * @return PredicateSet - */ - public function orPredicate(PredicateInterface $predicate) - { - $this->predicates[] = array(self::OP_OR, $predicate); - return $this; - } - - /** - * Add predicate using AND operator - * - * @param PredicateInterface $predicate - * @return PredicateSet - */ - public function andPredicate(PredicateInterface $predicate) - { - $this->predicates[] = array(self::OP_AND, $predicate); - return $this; - } - - /** - * Get predicate parts for where statement - * - * @return array - */ - public function getExpressionData() - { - $parts = array(); - for ($i = 0, $count = count($this->predicates); $i < $count; $i++) { - /** @var $predicate PredicateInterface */ - $predicate = $this->predicates[$i][1]; - - if ($predicate instanceof PredicateSet) { - $parts[] = '('; - } - - $parts = array_merge($parts, $predicate->getExpressionData()); - - if ($predicate instanceof PredicateSet) { - $parts[] = ')'; - } - - if (isset($this->predicates[$i+1])) { - $parts[] = sprintf(' %s ', $this->predicates[$i+1][0]); - } - } - return $parts; - } - - /** - * Get count of attached predicates - * - * @return int - */ - public function count() - { - return count($this->predicates); - } -} diff --git a/library/Zend/Db/Sql/PreparableSqlInterface.php b/library/Zend/Db/Sql/PreparableSqlInterface.php deleted file mode 100755 index ea32cd65b..000000000 --- a/library/Zend/Db/Sql/PreparableSqlInterface.php +++ /dev/null @@ -1,23 +0,0 @@ - '%1$s', - self::SELECT => array( - 'SELECT %1$s FROM %2$s' => array( - array(1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '), - null - ), - 'SELECT %1$s %2$s FROM %3$s' => array( - null, - array(1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '), - null - ), - 'SELECT %1$s' => array( - array(1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '), - ), - ), - self::JOINS => array( - '%1$s' => array( - array(3 => '%1$s JOIN %2$s ON %3$s', 'combinedby' => ' ') - ) - ), - self::WHERE => 'WHERE %1$s', - self::GROUP => array( - 'GROUP BY %1$s' => array( - array(1 => '%1$s', 'combinedby' => ', ') - ) - ), - self::HAVING => 'HAVING %1$s', - self::ORDER => array( - 'ORDER BY %1$s' => array( - array(1 => '%1$s', 2 => '%1$s %2$s', 'combinedby' => ', ') - ) - ), - self::LIMIT => 'LIMIT %1$s', - self::OFFSET => 'OFFSET %1$s', - 'statementEnd' => '%1$s', - self::COMBINE => '%1$s ( %2$s )', - ); - - /** - * @var bool - */ - protected $tableReadOnly = false; - - /** - * @var bool - */ - protected $prefixColumnsWithTable = true; - - /** - * @var string|array|TableIdentifier - */ - protected $table = null; - - /** - * @var null|string|Expression - */ - protected $quantifier = null; - - /** - * @var array - */ - protected $columns = array(self::SQL_STAR); - - /** - * @var array - */ - protected $joins = array(); - - /** - * @var Where - */ - protected $where = null; - - /** - * @var array - */ - protected $order = array(); - - /** - * @var null|array - */ - protected $group = null; - - /** - * @var null|string|array - */ - protected $having = null; - - /** - * @var int|null - */ - protected $limit = null; - - /** - * @var int|null - */ - protected $offset = null; - - /** - * @var array - */ - protected $combine = array(); - - /** - * Constructor - * - * @param null|string|array|TableIdentifier $table - */ - public function __construct($table = null) - { - if ($table) { - $this->from($table); - $this->tableReadOnly = true; - } - - $this->where = new Where; - $this->having = new Having; - } - - /** - * Create from clause - * - * @param string|array|TableIdentifier $table - * @throws Exception\InvalidArgumentException - * @return Select - */ - public function from($table) - { - if ($this->tableReadOnly) { - throw new Exception\InvalidArgumentException('Since this object was created with a table and/or schema in the constructor, it is read only.'); - } - - if (!is_string($table) && !is_array($table) && !$table instanceof TableIdentifier) { - throw new Exception\InvalidArgumentException('$table must be a string, array, or an instance of TableIdentifier'); - } - - if (is_array($table) && (!is_string(key($table)) || count($table) !== 1)) { - throw new Exception\InvalidArgumentException('from() expects $table as an array is a single element associative array'); - } - - $this->table = $table; - return $this; - } - - /** - * @param string|Expression $quantifier DISTINCT|ALL - * @return Select - */ - public function quantifier($quantifier) - { - if (!is_string($quantifier) && !$quantifier instanceof Expression) { - throw new Exception\InvalidArgumentException( - 'Quantifier must be one of DISTINCT, ALL, or some platform specific Expression object' - ); - } - $this->quantifier = $quantifier; - return $this; - } - - /** - * Specify columns from which to select - * - * Possible valid states: - * - * array(*) - * - * array(value, ...) - * value can be strings or Expression objects - * - * array(string => value, ...) - * key string will be use as alias, - * value can be string or Expression objects - * - * @param array $columns - * @param bool $prefixColumnsWithTable - * @return Select - */ - public function columns(array $columns, $prefixColumnsWithTable = true) - { - $this->columns = $columns; - $this->prefixColumnsWithTable = (bool) $prefixColumnsWithTable; - return $this; - } - - /** - * Create join clause - * - * @param string|array $name - * @param string $on - * @param string|array $columns - * @param string $type one of the JOIN_* constants - * @throws Exception\InvalidArgumentException - * @return Select - */ - public function join($name, $on, $columns = self::SQL_STAR, $type = self::JOIN_INNER) - { - if (is_array($name) && (!is_string(key($name)) || count($name) !== 1)) { - throw new Exception\InvalidArgumentException( - sprintf("join() expects '%s' as an array is a single element associative array", array_shift($name)) - ); - } - if (!is_array($columns)) { - $columns = array($columns); - } - $this->joins[] = array( - 'name' => $name, - 'on' => $on, - 'columns' => $columns, - 'type' => $type - ); - return $this; - } - - /** - * Create where clause - * - * @param Where|\Closure|string|array|Predicate\PredicateInterface $predicate - * @param string $combination One of the OP_* constants from Predicate\PredicateSet - * @throws Exception\InvalidArgumentException - * @return Select - */ - public function where($predicate, $combination = Predicate\PredicateSet::OP_AND) - { - if ($predicate instanceof Where) { - $this->where = $predicate; - } else { - $this->where->addPredicates($predicate, $combination); - } - return $this; - } - - public function group($group) - { - if (is_array($group)) { - foreach ($group as $o) { - $this->group[] = $o; - } - } else { - $this->group[] = $group; - } - return $this; - } - - /** - * Create where clause - * - * @param Where|\Closure|string|array $predicate - * @param string $combination One of the OP_* constants from Predicate\PredicateSet - * @return Select - */ - public function having($predicate, $combination = Predicate\PredicateSet::OP_AND) - { - if ($predicate instanceof Having) { - $this->having = $predicate; - } else { - $this->having->addPredicates($predicate, $combination); - } - return $this; - } - - /** - * @param string|array $order - * @return Select - */ - public function order($order) - { - if (is_string($order)) { - if (strpos($order, ',') !== false) { - $order = preg_split('#,\s+#', $order); - } else { - $order = (array) $order; - } - } elseif (!is_array($order)) { - $order = array($order); - } - foreach ($order as $k => $v) { - if (is_string($k)) { - $this->order[$k] = $v; - } else { - $this->order[] = $v; - } - } - return $this; - } - - /** - * @param int $limit - * @return Select - */ - public function limit($limit) - { - if (!is_numeric($limit)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects parameter to be numeric, "%s" given', - __METHOD__, - (is_object($limit) ? get_class($limit) : gettype($limit)) - )); - } - - $this->limit = $limit; - return $this; - } - - /** - * @param int $offset - * @return Select - */ - public function offset($offset) - { - if (!is_numeric($offset)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects parameter to be numeric, "%s" given', - __METHOD__, - (is_object($offset) ? get_class($offset) : gettype($offset)) - )); - } - - $this->offset = $offset; - return $this; - } - - /** - * @param Select $select - * @param string $type - * @param string $modifier - * @return Select - * @throws Exception\InvalidArgumentException - */ - public function combine(Select $select, $type = self::COMBINE_UNION, $modifier = '') - { - if ($this->combine !== array()) { - throw new Exception\InvalidArgumentException('This Select object is already combined and cannot be combined with multiple Selects objects'); - } - $this->combine = array( - 'select' => $select, - 'type' => $type, - 'modifier' => $modifier - ); - return $this; - } - - /** - * @param string $part - * @return Select - * @throws Exception\InvalidArgumentException - */ - public function reset($part) - { - switch ($part) { - case self::TABLE: - if ($this->tableReadOnly) { - throw new Exception\InvalidArgumentException( - 'Since this object was created with a table and/or schema in the constructor, it is read only.' - ); - } - $this->table = null; - break; - case self::QUANTIFIER: - $this->quantifier = null; - break; - case self::COLUMNS: - $this->columns = array(); - break; - case self::JOINS: - $this->joins = array(); - break; - case self::WHERE: - $this->where = new Where; - break; - case self::GROUP: - $this->group = null; - break; - case self::HAVING: - $this->having = new Having; - break; - case self::LIMIT: - $this->limit = null; - break; - case self::OFFSET: - $this->offset = null; - break; - case self::ORDER: - $this->order = array(); - break; - case self::COMBINE: - $this->combine = array(); - break; - } - return $this; - } - - public function setSpecification($index, $specification) - { - if (!method_exists($this, 'process' . $index)) { - throw new Exception\InvalidArgumentException('Not a valid specification name.'); - } - $this->specifications[$index] = $specification; - return $this; - } - - public function getRawState($key = null) - { - $rawState = array( - self::TABLE => $this->table, - self::QUANTIFIER => $this->quantifier, - self::COLUMNS => $this->columns, - self::JOINS => $this->joins, - self::WHERE => $this->where, - self::ORDER => $this->order, - self::GROUP => $this->group, - self::HAVING => $this->having, - self::LIMIT => $this->limit, - self::OFFSET => $this->offset, - self::COMBINE => $this->combine - ); - return (isset($key) && array_key_exists($key, $rawState)) ? $rawState[$key] : $rawState; - } - - /** - * Prepare statement - * - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - * @return void - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - // ensure statement has a ParameterContainer - $parameterContainer = $statementContainer->getParameterContainer(); - if (!$parameterContainer instanceof ParameterContainer) { - $parameterContainer = new ParameterContainer(); - $statementContainer->setParameterContainer($parameterContainer); - } - - $sqls = array(); - $parameters = array(); - $platform = $adapter->getPlatform(); - $driver = $adapter->getDriver(); - - foreach ($this->specifications as $name => $specification) { - $parameters[$name] = $this->{'process' . $name}($platform, $driver, $parameterContainer, $sqls, $parameters); - if ($specification && is_array($parameters[$name])) { - $sqls[$name] = $this->createSqlFromSpecificationAndParameters($specification, $parameters[$name]); - } - } - - $sql = implode(' ', $sqls); - - $statementContainer->setSql($sql); - return; - } - - /** - * Get SQL string for statement - * - * @param null|PlatformInterface $adapterPlatform If null, defaults to Sql92 - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - // get platform, or create default - $adapterPlatform = ($adapterPlatform) ?: new AdapterSql92Platform; - - $sqls = array(); - $parameters = array(); - - foreach ($this->specifications as $name => $specification) { - $parameters[$name] = $this->{'process' . $name}($adapterPlatform, null, null, $sqls, $parameters); - if ($specification && is_array($parameters[$name])) { - $sqls[$name] = $this->createSqlFromSpecificationAndParameters($specification, $parameters[$name]); - } - } - - $sql = implode(' ', $sqls); - return $sql; - } - - /** - * Returns whether the table is read only or not. - * - * @return bool - */ - public function isTableReadOnly() - { - return $this->tableReadOnly; - } - - /** - * Render table with alias in from/join parts - * - * @todo move TableIdentifier concatination here - * @param string $table - * @param string $alias - * @return string - */ - protected function renderTable($table, $alias = null) - { - $sql = $table; - if ($alias) { - $sql .= ' AS ' . $alias; - } - return $sql; - } - - protected function processStatementStart(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->combine !== array()) { - return array('('); - } - } - - protected function processStatementEnd(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->combine !== array()) { - return array(')'); - } - } - - /** - * Process the select part - * - * @param PlatformInterface $platform - * @param DriverInterface $driver - * @param ParameterContainer $parameterContainer - * @return null|array - */ - protected function processSelect(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - $expr = 1; - - if ($this->table) { - $table = $this->table; - $schema = $alias = null; - - if (is_array($table)) { - $alias = key($this->table); - $table = current($this->table); - } - - // create quoted table name to use in columns processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - if ($table instanceof Select) { - $table = '(' . $this->processSubselect($table, $platform, $driver, $parameterContainer) . ')'; - } else { - $table = $platform->quoteIdentifier($table); - } - - if ($schema) { - $table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table; - } - - if ($alias) { - $fromTable = $platform->quoteIdentifier($alias); - $table = $this->renderTable($table, $fromTable); - } else { - $fromTable = $table; - } - } else { - $fromTable = ''; - } - - if ($this->prefixColumnsWithTable) { - $fromTable .= $platform->getIdentifierSeparator(); - } else { - $fromTable = ''; - } - - // process table columns - $columns = array(); - foreach ($this->columns as $columnIndexOrAs => $column) { - $columnName = ''; - if ($column === self::SQL_STAR) { - $columns[] = array($fromTable . self::SQL_STAR); - continue; - } - - if ($column instanceof ExpressionInterface) { - $columnParts = $this->processExpression( - $column, - $platform, - $driver, - $this->processInfo['paramPrefix'] . ((is_string($columnIndexOrAs)) ? $columnIndexOrAs : 'column') - ); - if ($parameterContainer) { - $parameterContainer->merge($columnParts->getParameterContainer()); - } - $columnName .= $columnParts->getSql(); - } else { - $columnName .= $fromTable . $platform->quoteIdentifier($column); - } - - // process As portion - if (is_string($columnIndexOrAs)) { - $columnAs = $platform->quoteIdentifier($columnIndexOrAs); - } elseif (stripos($columnName, ' as ') === false) { - $columnAs = (is_string($column)) ? $platform->quoteIdentifier($column) : 'Expression' . $expr++; - } - $columns[] = (isset($columnAs)) ? array($columnName, $columnAs) : array($columnName); - } - - $separator = $platform->getIdentifierSeparator(); - - // process join columns - foreach ($this->joins as $join) { - foreach ($join['columns'] as $jKey => $jColumn) { - $jColumns = array(); - if ($jColumn instanceof ExpressionInterface) { - $jColumnParts = $this->processExpression( - $jColumn, - $platform, - $driver, - $this->processInfo['paramPrefix'] . ((is_string($jKey)) ? $jKey : 'column') - ); - if ($parameterContainer) { - $parameterContainer->merge($jColumnParts->getParameterContainer()); - } - $jColumns[] = $jColumnParts->getSql(); - } else { - $name = (is_array($join['name'])) ? key($join['name']) : $name = $join['name']; - if ($name instanceof TableIdentifier) { - $name = ($name->hasSchema() ? $platform->quoteIdentifier($name->getSchema()) . $separator : '') . $platform->quoteIdentifier($name->getTable()); - } else { - $name = $platform->quoteIdentifier($name); - } - $jColumns[] = $name . $separator . $platform->quoteIdentifierInFragment($jColumn); - } - if (is_string($jKey)) { - $jColumns[] = $platform->quoteIdentifier($jKey); - } elseif ($jColumn !== self::SQL_STAR) { - $jColumns[] = $platform->quoteIdentifier($jColumn); - } - $columns[] = $jColumns; - } - } - - if ($this->quantifier) { - if ($this->quantifier instanceof ExpressionInterface) { - $quantifierParts = $this->processExpression($this->quantifier, $platform, $driver, 'quantifier'); - if ($parameterContainer) { - $parameterContainer->merge($quantifierParts->getParameterContainer()); - } - $quantifier = $quantifierParts->getSql(); - } else { - $quantifier = $this->quantifier; - } - } - - if (!isset($table)) { - return array($columns); - } elseif (isset($quantifier)) { - return array($quantifier, $columns, $table); - } else { - return array($columns, $table); - } - } - - protected function processJoins(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if (!$this->joins) { - return null; - } - - // process joins - $joinSpecArgArray = array(); - foreach ($this->joins as $j => $join) { - $joinSpecArgArray[$j] = array(); - $joinName = null; - $joinAs = null; - - // type - $joinSpecArgArray[$j][] = strtoupper($join['type']); - - // table name - if (is_array($join['name'])) { - $joinName = current($join['name']); - $joinAs = $platform->quoteIdentifier(key($join['name'])); - } else { - $joinName = $join['name']; - } - if ($joinName instanceof ExpressionInterface) { - $joinName = $joinName->getExpression(); - } elseif ($joinName instanceof TableIdentifier) { - $joinName = $joinName->getTableAndSchema(); - $joinName = ($joinName[1] ? $platform->quoteIdentifier($joinName[1]) . $platform->getIdentifierSeparator() : '') . $platform->quoteIdentifier($joinName[0]); - } else { - if ($joinName instanceof Select) { - $joinName = '(' . $this->processSubSelect($joinName, $platform, $driver, $parameterContainer) . ')'; - } else { - $joinName = $platform->quoteIdentifier($joinName); - } - } - $joinSpecArgArray[$j][] = (isset($joinAs)) ? $joinName . ' AS ' . $joinAs : $joinName; - - // on expression - // note: for Expression objects, pass them to processExpression with a prefix specific to each join (used for named parameters) - $joinSpecArgArray[$j][] = ($join['on'] instanceof ExpressionInterface) - ? $this->processExpression($join['on'], $platform, $driver, $this->processInfo['paramPrefix'] . 'join' . ($j+1) . 'part') - : $platform->quoteIdentifierInFragment($join['on'], array('=', 'AND', 'OR', '(', ')', 'BETWEEN', '<', '>')); // on - if ($joinSpecArgArray[$j][2] instanceof StatementContainerInterface) { - if ($parameterContainer) { - $parameterContainer->merge($joinSpecArgArray[$j][2]->getParameterContainer()); - } - $joinSpecArgArray[$j][2] = $joinSpecArgArray[$j][2]->getSql(); - } - } - - return array($joinSpecArgArray); - } - - protected function processWhere(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->where->count() == 0) { - return null; - } - $whereParts = $this->processExpression($this->where, $platform, $driver, $this->processInfo['paramPrefix'] . 'where'); - if ($parameterContainer) { - $parameterContainer->merge($whereParts->getParameterContainer()); - } - return array($whereParts->getSql()); - } - - protected function processGroup(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->group === null) { - return null; - } - // process table columns - $groups = array(); - foreach ($this->group as $column) { - $columnSql = ''; - if ($column instanceof Expression) { - $columnParts = $this->processExpression($column, $platform, $driver, $this->processInfo['paramPrefix'] . 'group'); - if ($parameterContainer) { - $parameterContainer->merge($columnParts->getParameterContainer()); - } - $columnSql .= $columnParts->getSql(); - } else { - $columnSql .= $platform->quoteIdentifierInFragment($column); - } - $groups[] = $columnSql; - } - return array($groups); - } - - protected function processHaving(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->having->count() == 0) { - return null; - } - $whereParts = $this->processExpression($this->having, $platform, $driver, $this->processInfo['paramPrefix'] . 'having'); - if ($parameterContainer) { - $parameterContainer->merge($whereParts->getParameterContainer()); - } - return array($whereParts->getSql()); - } - - protected function processOrder(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if (empty($this->order)) { - return null; - } - $orders = array(); - foreach ($this->order as $k => $v) { - if ($v instanceof Expression) { - /** @var $orderParts \Zend\Db\Adapter\StatementContainer */ - $orderParts = $this->processExpression($v, $platform, $driver); - if ($parameterContainer) { - $parameterContainer->merge($orderParts->getParameterContainer()); - } - $orders[] = array($orderParts->getSql()); - continue; - } - if (is_int($k)) { - if (strpos($v, ' ') !== false) { - list($k, $v) = preg_split('# #', $v, 2); - } else { - $k = $v; - $v = self::ORDER_ASCENDING; - } - } - if (strtoupper($v) == self::ORDER_DESCENDING) { - $orders[] = array($platform->quoteIdentifierInFragment($k), self::ORDER_DESCENDING); - } else { - $orders[] = array($platform->quoteIdentifierInFragment($k), self::ORDER_ASCENDING); - } - } - return array($orders); - } - - protected function processLimit(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->limit === null) { - return null; - } - - $limit = $this->limit; - - if ($driver) { - $sql = $driver->formatParameterName('limit'); - $parameterContainer->offsetSet('limit', $limit, ParameterContainer::TYPE_INTEGER); - } else { - $sql = $platform->quoteValue($limit); - } - - return array($sql); - } - - protected function processOffset(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->offset === null) { - return null; - } - - $offset = $this->offset; - - if ($driver) { - $parameterContainer->offsetSet('offset', $offset, ParameterContainer::TYPE_INTEGER); - return array($driver->formatParameterName('offset')); - } - - return array($platform->quoteValue($offset)); - } - - protected function processCombine(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null) - { - if ($this->combine == array()) { - return null; - } - - $type = $this->combine['type']; - if ($this->combine['modifier']) { - $type .= ' ' . $this->combine['modifier']; - } - $type = strtoupper($type); - - if ($driver) { - $sql = $this->processSubSelect($this->combine['select'], $platform, $driver, $parameterContainer); - return array($type, $sql); - } - return array( - $type, - $this->processSubSelect($this->combine['select'], $platform) - ); - } - - /** - * Variable overloading - * - * @param string $name - * @throws Exception\InvalidArgumentException - * @return mixed - */ - public function __get($name) - { - switch (strtolower($name)) { - case 'where': - return $this->where; - case 'having': - return $this->having; - default: - throw new Exception\InvalidArgumentException('Not a valid magic property for this object'); - } - } - - /** - * __clone - * - * Resets the where object each time the Select is cloned. - * - * @return void - */ - public function __clone() - { - $this->where = clone $this->where; - $this->having = clone $this->having; - } -} diff --git a/library/Zend/Db/Sql/Sql.php b/library/Zend/Db/Sql/Sql.php deleted file mode 100755 index 17a697e2d..000000000 --- a/library/Zend/Db/Sql/Sql.php +++ /dev/null @@ -1,151 +0,0 @@ -adapter = $adapter; - if ($table) { - $this->setTable($table); - } - $this->sqlPlatform = ($sqlPlatform) ?: new Platform\Platform($adapter); - } - - /** - * @return null|\Zend\Db\Adapter\AdapterInterface - */ - public function getAdapter() - { - return $this->adapter; - } - - public function hasTable() - { - return ($this->table != null); - } - - public function setTable($table) - { - if (is_string($table) || is_array($table) || $table instanceof TableIdentifier) { - $this->table = $table; - } else { - throw new Exception\InvalidArgumentException('Table must be a string, array or instance of TableIdentifier.'); - } - return $this; - } - - public function getTable() - { - return $this->table; - } - - public function getSqlPlatform() - { - return $this->sqlPlatform; - } - - public function select($table = null) - { - if ($this->table !== null && $table !== null) { - throw new Exception\InvalidArgumentException(sprintf( - 'This Sql object is intended to work with only the table "%s" provided at construction time.', - $this->table - )); - } - return new Select(($table) ?: $this->table); - } - - public function insert($table = null) - { - if ($this->table !== null && $table !== null) { - throw new Exception\InvalidArgumentException(sprintf( - 'This Sql object is intended to work with only the table "%s" provided at construction time.', - $this->table - )); - } - return new Insert(($table) ?: $this->table); - } - - public function update($table = null) - { - if ($this->table !== null && $table !== null) { - throw new Exception\InvalidArgumentException(sprintf( - 'This Sql object is intended to work with only the table "%s" provided at construction time.', - $this->table - )); - } - return new Update(($table) ?: $this->table); - } - - public function delete($table = null) - { - if ($this->table !== null && $table !== null) { - throw new Exception\InvalidArgumentException(sprintf( - 'This Sql object is intended to work with only the table "%s" provided at construction time.', - $this->table - )); - } - return new Delete(($table) ?: $this->table); - } - - /** - * @param PreparableSqlInterface $sqlObject - * @param StatementInterface|null $statement - * @return StatementInterface - */ - public function prepareStatementForSqlObject(PreparableSqlInterface $sqlObject, StatementInterface $statement = null) - { - $statement = ($statement) ?: $this->adapter->getDriver()->createStatement(); - - if ($this->sqlPlatform) { - $this->sqlPlatform->setSubject($sqlObject); - $this->sqlPlatform->prepareStatement($this->adapter, $statement); - } else { - $sqlObject->prepareStatement($this->adapter, $statement); - } - - return $statement; - } - - /** - * Get sql string using platform or sql object - * - * @param SqlInterface $sqlObject - * @param PlatformInterface $platform - * - * @return string - */ - public function getSqlStringForSqlObject(SqlInterface $sqlObject, PlatformInterface $platform = null) - { - $platform = ($platform) ?: $this->adapter->getPlatform(); - - if ($this->sqlPlatform) { - $this->sqlPlatform->setSubject($sqlObject); - return $this->sqlPlatform->getSqlString($platform); - } - - return $sqlObject->getSqlString($platform); - } -} diff --git a/library/Zend/Db/Sql/SqlInterface.php b/library/Zend/Db/Sql/SqlInterface.php deleted file mode 100755 index f7db64c17..000000000 --- a/library/Zend/Db/Sql/SqlInterface.php +++ /dev/null @@ -1,22 +0,0 @@ -table = $table; - $this->schema = $schema; - } - - /** - * @param string $table - */ - public function setTable($table) - { - $this->table = $table; - } - - /** - * @return string - */ - public function getTable() - { - return $this->table; - } - - /** - * @return bool - */ - public function hasSchema() - { - return ($this->schema != null); - } - - /** - * @param $schema - */ - public function setSchema($schema) - { - $this->schema = $schema; - } - - /** - * @return null|string - */ - public function getSchema() - { - return $this->schema; - } - - public function getTableAndSchema() - { - return array($this->table, $this->schema); - } -} diff --git a/library/Zend/Db/Sql/Update.php b/library/Zend/Db/Sql/Update.php deleted file mode 100755 index 11e44e834..000000000 --- a/library/Zend/Db/Sql/Update.php +++ /dev/null @@ -1,271 +0,0 @@ - 'UPDATE %1$s SET %2$s', - self::SPECIFICATION_WHERE => 'WHERE %1$s' - ); - - /** - * @var string|TableIdentifier - */ - protected $table = ''; - - /** - * @var bool - */ - protected $emptyWhereProtection = true; - - /** - * @var PriorityList - */ - protected $set; - - /** - * @var string|Where - */ - protected $where = null; - - /** - * Constructor - * - * @param null|string|TableIdentifier $table - */ - public function __construct($table = null) - { - if ($table) { - $this->table($table); - } - $this->where = new Where(); - $this->set = new PriorityList(); - $this->set->isLIFO(false); - } - - /** - * Specify table for statement - * - * @param string|TableIdentifier $table - * @return Update - */ - public function table($table) - { - $this->table = $table; - return $this; - } - - /** - * Set key/value pairs to update - * - * @param array $values Associative array of key values - * @param string $flag One of the VALUES_* constants - * @throws Exception\InvalidArgumentException - * @return Update - */ - public function set(array $values, $flag = self::VALUES_SET) - { - if ($values == null) { - throw new Exception\InvalidArgumentException('set() expects an array of values'); - } - - if ($flag == self::VALUES_SET) { - $this->set->clear(); - } - $priority = is_numeric($flag) ? $flag : 0; - foreach ($values as $k => $v) { - if (!is_string($k)) { - throw new Exception\InvalidArgumentException('set() expects a string for the value key'); - } - $this->set->insert($k, $v, $priority); - } - return $this; - } - - /** - * Create where clause - * - * @param Where|\Closure|string|array $predicate - * @param string $combination One of the OP_* constants from Predicate\PredicateSet - * @throws Exception\InvalidArgumentException - * @return Select - */ - public function where($predicate, $combination = Predicate\PredicateSet::OP_AND) - { - if ($predicate instanceof Where) { - $this->where = $predicate; - } else { - $this->where->addPredicates($predicate, $combination); - } - return $this; - } - - public function getRawState($key = null) - { - $rawState = array( - 'emptyWhereProtection' => $this->emptyWhereProtection, - 'table' => $this->table, - 'set' => $this->set->toArray(), - 'where' => $this->where - ); - return (isset($key) && array_key_exists($key, $rawState)) ? $rawState[$key] : $rawState; - } - - /** - * Prepare statement - * - * @param AdapterInterface $adapter - * @param StatementContainerInterface $statementContainer - * @return void - */ - public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) - { - $driver = $adapter->getDriver(); - $platform = $adapter->getPlatform(); - $parameterContainer = $statementContainer->getParameterContainer(); - - if (!$parameterContainer instanceof ParameterContainer) { - $parameterContainer = new ParameterContainer(); - $statementContainer->setParameterContainer($parameterContainer); - } - - $table = $this->table; - $schema = null; - - // create quoted table name to use in update processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - $table = $platform->quoteIdentifier($table); - - if ($schema) { - $table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table; - } - - $setSql = array(); - foreach ($this->set as $column => $value) { - if ($value instanceof Expression) { - $exprData = $this->processExpression($value, $platform, $driver); - $setSql[] = $platform->quoteIdentifier($column) . ' = ' . $exprData->getSql(); - $parameterContainer->merge($exprData->getParameterContainer()); - } else { - $setSql[] = $platform->quoteIdentifier($column) . ' = ' . $driver->formatParameterName($column); - $parameterContainer->offsetSet($column, $value); - } - } - $set = implode(', ', $setSql); - - $sql = sprintf($this->specifications[static::SPECIFICATION_UPDATE], $table, $set); - - // process where - if ($this->where->count() > 0) { - $whereParts = $this->processExpression($this->where, $platform, $driver, 'where'); - $parameterContainer->merge($whereParts->getParameterContainer()); - $sql .= ' ' . sprintf($this->specifications[static::SPECIFICATION_WHERE], $whereParts->getSql()); - } - $statementContainer->setSql($sql); - } - - /** - * Get SQL string for statement - * - * @param null|PlatformInterface $adapterPlatform If null, defaults to Sql92 - * @return string - */ - public function getSqlString(PlatformInterface $adapterPlatform = null) - { - $adapterPlatform = ($adapterPlatform) ?: new Sql92; - $table = $this->table; - $schema = null; - - // create quoted table name to use in update processing - if ($table instanceof TableIdentifier) { - list($table, $schema) = $table->getTableAndSchema(); - } - - $table = $adapterPlatform->quoteIdentifier($table); - - if ($schema) { - $table = $adapterPlatform->quoteIdentifier($schema) . $adapterPlatform->getIdentifierSeparator() . $table; - } - - $setSql = array(); - foreach ($this->set as $column => $value) { - if ($value instanceof ExpressionInterface) { - $exprData = $this->processExpression($value, $adapterPlatform); - $setSql[] = $adapterPlatform->quoteIdentifier($column) . ' = ' . $exprData->getSql(); - } elseif ($value === null) { - $setSql[] = $adapterPlatform->quoteIdentifier($column) . ' = NULL'; - } else { - $setSql[] = $adapterPlatform->quoteIdentifier($column) . ' = ' . $adapterPlatform->quoteValue($value); - } - } - $set = implode(', ', $setSql); - - $sql = sprintf($this->specifications[static::SPECIFICATION_UPDATE], $table, $set); - if ($this->where->count() > 0) { - $whereParts = $this->processExpression($this->where, $adapterPlatform, null, 'where'); - $sql .= ' ' . sprintf($this->specifications[static::SPECIFICATION_WHERE], $whereParts->getSql()); - } - return $sql; - } - - /** - * Variable overloading - * - * Proxies to "where" only - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - switch (strtolower($name)) { - case 'where': - return $this->where; - } - } - - /** - * __clone - * - * Resets the where object each time the Update is cloned. - * - * @return void - */ - public function __clone() - { - $this->where = clone $this->where; - $this->set = clone $this->set; - } -} diff --git a/library/Zend/Db/Sql/Where.php b/library/Zend/Db/Sql/Where.php deleted file mode 100755 index f50efb46f..000000000 --- a/library/Zend/Db/Sql/Where.php +++ /dev/null @@ -1,14 +0,0 @@ -isInitialized; - } - - /** - * Initialize - * - * @throws Exception\RuntimeException - * @return null - */ - public function initialize() - { - if ($this->isInitialized) { - return; - } - - if (!$this->featureSet instanceof Feature\FeatureSet) { - $this->featureSet = new Feature\FeatureSet; - } - - $this->featureSet->setTableGateway($this); - $this->featureSet->apply('preInitialize', array()); - - if (!$this->adapter instanceof AdapterInterface) { - throw new Exception\RuntimeException('This table does not have an Adapter setup'); - } - - if (!is_string($this->table) && !$this->table instanceof TableIdentifier) { - throw new Exception\RuntimeException('This table object does not have a valid table set.'); - } - - if (!$this->resultSetPrototype instanceof ResultSetInterface) { - $this->resultSetPrototype = new ResultSet; - } - - if (!$this->sql instanceof Sql) { - $this->sql = new Sql($this->adapter, $this->table); - } - - $this->featureSet->apply('postInitialize', array()); - - $this->isInitialized = true; - } - - /** - * Get table name - * - * @return string - */ - public function getTable() - { - return $this->table; - } - - /** - * Get adapter - * - * @return AdapterInterface - */ - public function getAdapter() - { - return $this->adapter; - } - - /** - * @return array - */ - public function getColumns() - { - return $this->columns; - } - - /** - * @return Feature\FeatureSet - */ - public function getFeatureSet() - { - return $this->featureSet; - } - - /** - * Get select result prototype - * - * @return ResultSet - */ - public function getResultSetPrototype() - { - return $this->resultSetPrototype; - } - - /** - * @return Sql - */ - public function getSql() - { - return $this->sql; - } - - /** - * Select - * - * @param Where|\Closure|string|array $where - * @return ResultSet - */ - public function select($where = null) - { - if (!$this->isInitialized) { - $this->initialize(); - } - - $select = $this->sql->select(); - - if ($where instanceof \Closure) { - $where($select); - } elseif ($where !== null) { - $select->where($where); - } - - return $this->selectWith($select); - } - - /** - * @param Select $select - * @return null|ResultSetInterface - * @throws \RuntimeException - */ - public function selectWith(Select $select) - { - if (!$this->isInitialized) { - $this->initialize(); - } - return $this->executeSelect($select); - } - - /** - * @param Select $select - * @return ResultSet - * @throws Exception\RuntimeException - */ - protected function executeSelect(Select $select) - { - $selectState = $select->getRawState(); - if ($selectState['table'] != $this->table && (is_array($selectState['table']) && end($selectState['table']) != $this->table)) { - throw new Exception\RuntimeException('The table name of the provided select object must match that of the table'); - } - - if ($selectState['columns'] == array(Select::SQL_STAR) - && $this->columns !== array()) { - $select->columns($this->columns); - } - - // apply preSelect features - $this->featureSet->apply('preSelect', array($select)); - - // prepare and execute - $statement = $this->sql->prepareStatementForSqlObject($select); - $result = $statement->execute(); - - // build result set - $resultSet = clone $this->resultSetPrototype; - $resultSet->initialize($result); - - // apply postSelect features - $this->featureSet->apply('postSelect', array($statement, $result, $resultSet)); - - return $resultSet; - } - - /** - * Insert - * - * @param array $set - * @return int - */ - public function insert($set) - { - if (!$this->isInitialized) { - $this->initialize(); - } - $insert = $this->sql->insert(); - $insert->values($set); - return $this->executeInsert($insert); - } - - /** - * @param Insert $insert - * @return mixed - */ - public function insertWith(Insert $insert) - { - if (!$this->isInitialized) { - $this->initialize(); - } - return $this->executeInsert($insert); - } - - /** - * @todo add $columns support - * - * @param Insert $insert - * @return mixed - * @throws Exception\RuntimeException - */ - protected function executeInsert(Insert $insert) - { - $insertState = $insert->getRawState(); - if ($insertState['table'] != $this->table) { - throw new Exception\RuntimeException('The table name of the provided Insert object must match that of the table'); - } - - // apply preInsert features - $this->featureSet->apply('preInsert', array($insert)); - - $statement = $this->sql->prepareStatementForSqlObject($insert); - $result = $statement->execute(); - $this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue(); - - // apply postInsert features - $this->featureSet->apply('postInsert', array($statement, $result)); - - return $result->getAffectedRows(); - } - - /** - * Update - * - * @param array $set - * @param string|array|\Closure $where - * @return int - */ - public function update($set, $where = null) - { - if (!$this->isInitialized) { - $this->initialize(); - } - $sql = $this->sql; - $update = $sql->update(); - $update->set($set); - if ($where !== null) { - $update->where($where); - } - return $this->executeUpdate($update); - } - - /** - * @param \Zend\Db\Sql\Update $update - * @return mixed - */ - public function updateWith(Update $update) - { - if (!$this->isInitialized) { - $this->initialize(); - } - return $this->executeUpdate($update); - } - - /** - * @todo add $columns support - * - * @param Update $update - * @return mixed - * @throws Exception\RuntimeException - */ - protected function executeUpdate(Update $update) - { - $updateState = $update->getRawState(); - if ($updateState['table'] != $this->table) { - throw new Exception\RuntimeException('The table name of the provided Update object must match that of the table'); - } - - // apply preUpdate features - $this->featureSet->apply('preUpdate', array($update)); - - $statement = $this->sql->prepareStatementForSqlObject($update); - $result = $statement->execute(); - - // apply postUpdate features - $this->featureSet->apply('postUpdate', array($statement, $result)); - - return $result->getAffectedRows(); - } - - /** - * Delete - * - * @param Where|\Closure|string|array $where - * @return int - */ - public function delete($where) - { - if (!$this->isInitialized) { - $this->initialize(); - } - $delete = $this->sql->delete(); - if ($where instanceof \Closure) { - $where($delete); - } else { - $delete->where($where); - } - return $this->executeDelete($delete); - } - - /** - * @param Delete $delete - * @return mixed - */ - public function deleteWith(Delete $delete) - { - $this->initialize(); - return $this->executeDelete($delete); - } - - /** - * @todo add $columns support - * - * @param Delete $delete - * @return mixed - * @throws Exception\RuntimeException - */ - protected function executeDelete(Delete $delete) - { - $deleteState = $delete->getRawState(); - if ($deleteState['table'] != $this->table) { - throw new Exception\RuntimeException('The table name of the provided Update object must match that of the table'); - } - - // pre delete update - $this->featureSet->apply('preDelete', array($delete)); - - $statement = $this->sql->prepareStatementForSqlObject($delete); - $result = $statement->execute(); - - // apply postDelete features - $this->featureSet->apply('postDelete', array($statement, $result)); - - return $result->getAffectedRows(); - } - - /** - * Get last insert value - * - * @return int - */ - public function getLastInsertValue() - { - return $this->lastInsertValue; - } - - /** - * __get - * - * @param string $property - * @throws Exception\InvalidArgumentException - * @return mixed - */ - public function __get($property) - { - switch (strtolower($property)) { - case 'lastinsertvalue': - return $this->lastInsertValue; - case 'adapter': - return $this->adapter; - case 'table': - return $this->table; - } - if ($this->featureSet->canCallMagicGet($property)) { - return $this->featureSet->callMagicGet($property); - } - throw new Exception\InvalidArgumentException('Invalid magic property access in ' . __CLASS__ . '::__get()'); - } - - /** - * @param string $property - * @param mixed $value - * @return mixed - * @throws Exception\InvalidArgumentException - */ - public function __set($property, $value) - { - if ($this->featureSet->canCallMagicSet($property)) { - return $this->featureSet->callMagicSet($property, $value); - } - throw new Exception\InvalidArgumentException('Invalid magic property access in ' . __CLASS__ . '::__set()'); - } - - /** - * @param $method - * @param $arguments - * @return mixed - * @throws Exception\InvalidArgumentException - */ - public function __call($method, $arguments) - { - if ($this->featureSet->canCallMagicCall($method)) { - return $this->featureSet->callMagicCall($method, $arguments); - } - throw new Exception\InvalidArgumentException('Invalid method (' . $method . ') called, caught by ' . __CLASS__ . '::__call()'); - } - - /** - * __clone - */ - public function __clone() - { - $this->resultSetPrototype = (isset($this->resultSetPrototype)) ? clone $this->resultSetPrototype : null; - $this->sql = clone $this->sql; - if (is_object($this->table)) { - $this->table = clone $this->table; - } - } -} diff --git a/library/Zend/Db/TableGateway/Exception/ExceptionInterface.php b/library/Zend/Db/TableGateway/Exception/ExceptionInterface.php deleted file mode 100755 index ecd3085ac..000000000 --- a/library/Zend/Db/TableGateway/Exception/ExceptionInterface.php +++ /dev/null @@ -1,16 +0,0 @@ -tableGateway = $tableGateway; - } - - public function initialize() - { - throw new Exception\RuntimeException('This method is not intended to be called on this object.'); - } - - public function getMagicMethodSpecifications() - { - return array(); - } - - - /* - public function preInitialize(); - public function postInitialize(); - public function preSelect(Select $select); - public function postSelect(StatementInterface $statement, ResultInterface $result, ResultSetInterface $resultSet); - public function preInsert(Insert $insert); - public function postInsert(StatementInterface $statement, ResultInterface $result); - public function preUpdate(Update $update); - public function postUpdate(StatementInterface $statement, ResultInterface $result); - public function preDelete(Delete $delete); - public function postDelete(StatementInterface $statement, ResultInterface $result); - */ -} diff --git a/library/Zend/Db/TableGateway/Feature/EventFeature.php b/library/Zend/Db/TableGateway/Feature/EventFeature.php deleted file mode 100755 index 08e3cffbd..000000000 --- a/library/Zend/Db/TableGateway/Feature/EventFeature.php +++ /dev/null @@ -1,255 +0,0 @@ -eventManager = ($eventManager instanceof EventManagerInterface) - ? $eventManager - : new EventManager; - - $this->eventManager->addIdentifiers(array( - 'Zend\Db\TableGateway\TableGateway', - )); - - $this->event = ($tableGatewayEvent) ?: new EventFeature\TableGatewayEvent(); - } - - /** - * Retrieve composed event manager instance - * - * @return EventManagerInterface - */ - public function getEventManager() - { - return $this->eventManager; - } - - /** - * Retrieve composed event instance - * - * @return EventFeature\TableGatewayEvent - */ - public function getEvent() - { - return $this->event; - } - - /** - * Initialize feature and trigger "preInitialize" event - * - * Ensures that the composed TableGateway has identifiers based on the - * class name, and that the event target is set to the TableGateway - * instance. It then triggers the "preInitialize" event. - * - * @return void - */ - public function preInitialize() - { - if (get_class($this->tableGateway) != 'Zend\Db\TableGateway\TableGateway') { - $this->eventManager->addIdentifiers(get_class($this->tableGateway)); - } - - $this->event->setTarget($this->tableGateway); - $this->event->setName(__FUNCTION__); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "postInitialize" event - * - * @return void - */ - public function postInitialize() - { - $this->event->setName(__FUNCTION__); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "preSelect" event - * - * Triggers the "preSelect" event mapping the following parameters: - * - $select as "select" - * - * @param Select $select - * @return void - */ - public function preSelect(Select $select) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array('select' => $select)); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "postSelect" event - * - * Triggers the "postSelect" event mapping the following parameters: - * - $statement as "statement" - * - $result as "result" - * - $resultSet as "result_set" - * - * @param StatementInterface $statement - * @param ResultInterface $result - * @param ResultSetInterface $resultSet - * @return void - */ - public function postSelect(StatementInterface $statement, ResultInterface $result, ResultSetInterface $resultSet) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array( - 'statement' => $statement, - 'result' => $result, - 'result_set' => $resultSet - )); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "preInsert" event - * - * Triggers the "preInsert" event mapping the following parameters: - * - $insert as "insert" - * - * @param Insert $insert - * @return void - */ - public function preInsert(Insert $insert) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array('insert' => $insert)); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "postInsert" event - * - * Triggers the "postInsert" event mapping the following parameters: - * - $statement as "statement" - * - $result as "result" - * - * @param StatementInterface $statement - * @param ResultInterface $result - * @return void - */ - public function postInsert(StatementInterface $statement, ResultInterface $result) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array( - 'statement' => $statement, - 'result' => $result, - )); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "preUpdate" event - * - * Triggers the "preUpdate" event mapping the following parameters: - * - $update as "update" - * - * @param Update $update - * @return void - */ - public function preUpdate(Update $update) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array('update' => $update)); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "postUpdate" event - * - * Triggers the "postUpdate" event mapping the following parameters: - * - $statement as "statement" - * - $result as "result" - * - * @param StatementInterface $statement - * @param ResultInterface $result - * @return void - */ - public function postUpdate(StatementInterface $statement, ResultInterface $result) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array( - 'statement' => $statement, - 'result' => $result, - )); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "preDelete" event - * - * Triggers the "preDelete" event mapping the following parameters: - * - $delete as "delete" - * - * @param Delete $delete - * @return void - */ - public function preDelete(Delete $delete) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array('delete' => $delete)); - $this->eventManager->trigger($this->event); - } - - /** - * Trigger the "postDelete" event - * - * Triggers the "postDelete" event mapping the following parameters: - * - $statement as "statement" - * - $result as "result" - * - * @param StatementInterface $statement - * @param ResultInterface $result - * @return void - */ - public function postDelete(StatementInterface $statement, ResultInterface $result) - { - $this->event->setName(__FUNCTION__); - $this->event->setParams(array( - 'statement' => $statement, - 'result' => $result, - )); - $this->eventManager->trigger($this->event); - } -} diff --git a/library/Zend/Db/TableGateway/Feature/EventFeature/TableGatewayEvent.php b/library/Zend/Db/TableGateway/Feature/EventFeature/TableGatewayEvent.php deleted file mode 100755 index 1097a86fe..000000000 --- a/library/Zend/Db/TableGateway/Feature/EventFeature/TableGatewayEvent.php +++ /dev/null @@ -1,139 +0,0 @@ -name; - } - - /** - * Get target/context from which event was triggered - * - * @return null|string|object - */ - public function getTarget() - { - return $this->target; - } - - /** - * Get parameters passed to the event - * - * @return array|\ArrayAccess - */ - public function getParams() - { - return $this->params; - } - - /** - * Get a single parameter by name - * - * @param string $name - * @param mixed $default Default value to return if parameter does not exist - * @return mixed - */ - public function getParam($name, $default = null) - { - return (isset($this->params[$name]) ? $this->params[$name] : $default); - } - - /** - * Set the event name - * - * @param string $name - * @return void - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Set the event target/context - * - * @param null|string|object $target - * @return void - */ - public function setTarget($target) - { - $this->target = $target; - } - - /** - * Set event parameters - * - * @param string $params - * @return void - */ - public function setParams($params) - { - $this->params = $params; - } - - /** - * Set a single parameter by key - * - * @param string $name - * @param mixed $value - * @return void - */ - public function setParam($name, $value) - { - $this->params[$name] = $value; - } - - /** - * Indicate whether or not the parent EventManagerInterface should stop propagating events - * - * @param bool $flag - * @return void - */ - public function stopPropagation($flag = true) - { - return; - } - - /** - * Has this event indicated event propagation should stop? - * - * @return bool - */ - public function propagationIsStopped() - { - return false; - } -} diff --git a/library/Zend/Db/TableGateway/Feature/FeatureSet.php b/library/Zend/Db/TableGateway/Feature/FeatureSet.php deleted file mode 100755 index 498db1ad7..000000000 --- a/library/Zend/Db/TableGateway/Feature/FeatureSet.php +++ /dev/null @@ -1,146 +0,0 @@ -addFeatures($features); - } - } - - public function setTableGateway(AbstractTableGateway $tableGateway) - { - $this->tableGateway = $tableGateway; - foreach ($this->features as $feature) { - $feature->setTableGateway($this->tableGateway); - } - return $this; - } - - public function getFeatureByClassName($featureClassName) - { - $feature = false; - foreach ($this->features as $potentialFeature) { - if ($potentialFeature instanceof $featureClassName) { - $feature = $potentialFeature; - break; - } - } - return $feature; - } - - public function addFeatures(array $features) - { - foreach ($features as $feature) { - $this->addFeature($feature); - } - return $this; - } - - public function addFeature(AbstractFeature $feature) - { - if ($this->tableGateway instanceof TableGatewayInterface) { - $feature->setTableGateway($this->tableGateway); - } - $this->features[] = $feature; - return $this; - } - - public function apply($method, $args) - { - foreach ($this->features as $feature) { - if (method_exists($feature, $method)) { - $return = call_user_func_array(array($feature, $method), $args); - if ($return === self::APPLY_HALT) { - break; - } - } - } - } - - /** - * @param string $property - * @return bool - */ - public function canCallMagicGet($property) - { - return false; - } - - /** - * @param string $property - * @return mixed - */ - public function callMagicGet($property) - { - $return = null; - return $return; - } - - /** - * @param string $property - * @return bool - */ - public function canCallMagicSet($property) - { - return false; - } - - /** - * @param $property - * @param $value - * @return mixed - */ - public function callMagicSet($property, $value) - { - $return = null; - return $return; - } - - /** - * @param string $method - * @return bool - */ - public function canCallMagicCall($method) - { - return false; - } - - /** - * @param string $method - * @param array $arguments - * @return mixed - */ - public function callMagicCall($method, $arguments) - { - $return = null; - return $return; - } -} diff --git a/library/Zend/Db/TableGateway/Feature/GlobalAdapterFeature.php b/library/Zend/Db/TableGateway/Feature/GlobalAdapterFeature.php deleted file mode 100755 index bb8c6d60b..000000000 --- a/library/Zend/Db/TableGateway/Feature/GlobalAdapterFeature.php +++ /dev/null @@ -1,67 +0,0 @@ -tableGateway->adapter = self::getStaticAdapter(); - } -} diff --git a/library/Zend/Db/TableGateway/Feature/MasterSlaveFeature.php b/library/Zend/Db/TableGateway/Feature/MasterSlaveFeature.php deleted file mode 100755 index 255735de8..000000000 --- a/library/Zend/Db/TableGateway/Feature/MasterSlaveFeature.php +++ /dev/null @@ -1,91 +0,0 @@ -slaveAdapter = $slaveAdapter; - if ($slaveSql) { - $this->slaveSql = $slaveSql; - } - } - - public function getSlaveAdapter() - { - return $this->slaveAdapter; - } - - /** - * @return Sql - */ - public function getSlaveSql() - { - return $this->slaveSql; - } - - /** - * after initialization, retrieve the original adapter as "master" - */ - public function postInitialize() - { - $this->masterSql = $this->tableGateway->sql; - if ($this->slaveSql == null) { - $this->slaveSql = new Sql( - $this->slaveAdapter, - $this->tableGateway->sql->getTable(), - $this->tableGateway->sql->getSqlPlatform() - ); - } - } - - /** - * preSelect() - * Replace adapter with slave temporarily - */ - public function preSelect() - { - $this->tableGateway->sql = $this->slaveSql; - } - - /** - * postSelect() - * Ensure to return to the master adapter - */ - public function postSelect() - { - $this->tableGateway->sql = $this->masterSql; - } -} diff --git a/library/Zend/Db/TableGateway/Feature/MetadataFeature.php b/library/Zend/Db/TableGateway/Feature/MetadataFeature.php deleted file mode 100755 index 59393bec2..000000000 --- a/library/Zend/Db/TableGateway/Feature/MetadataFeature.php +++ /dev/null @@ -1,85 +0,0 @@ -metadata = $metadata; - } - $this->sharedData['metadata'] = array( - 'primaryKey' => null, - 'columns' => array() - ); - } - - public function postInitialize() - { - if ($this->metadata == null) { - $this->metadata = new Metadata($this->tableGateway->adapter); - } - - // localize variable for brevity - $t = $this->tableGateway; - $m = $this->metadata; - - // get column named - $columns = $m->getColumnNames($t->table); - $t->columns = $columns; - - // set locally - $this->sharedData['metadata']['columns'] = $columns; - - // process primary key only if table is a table; there are no PK constraints on views - if (!($m->getTable($t->table) instanceof TableObject)) { - return; - } - - $pkc = null; - - foreach ($m->getConstraints($t->table) as $constraint) { - /** @var $constraint \Zend\Db\Metadata\Object\ConstraintObject */ - if ($constraint->getType() == 'PRIMARY KEY') { - $pkc = $constraint; - break; - } - } - - if ($pkc === null) { - throw new Exception\RuntimeException('A primary key for this column could not be found in the metadata.'); - } - - if (count($pkc->getColumns()) == 1) { - $pkck = $pkc->getColumns(); - $primaryKey = $pkck[0]; - } else { - $primaryKey = $pkc->getColumns(); - } - - $this->sharedData['metadata']['primaryKey'] = $primaryKey; - } -} diff --git a/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php b/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php deleted file mode 100755 index 18c4fd9df..000000000 --- a/library/Zend/Db/TableGateway/Feature/RowGatewayFeature.php +++ /dev/null @@ -1,67 +0,0 @@ -constructorArguments = func_get_args(); - } - - public function postInitialize() - { - $args = $this->constructorArguments; - - /** @var $resultSetPrototype ResultSet */ - $resultSetPrototype = $this->tableGateway->resultSetPrototype; - - if (!$this->tableGateway->resultSetPrototype instanceof ResultSet) { - throw new Exception\RuntimeException( - 'This feature ' . __CLASS__ . ' expects the ResultSet to be an instance of Zend\Db\ResultSet\ResultSet' - ); - } - - if (isset($args[0])) { - if (is_string($args[0])) { - $primaryKey = $args[0]; - $rowGatewayPrototype = new RowGateway($primaryKey, $this->tableGateway->table, $this->tableGateway->adapter, $this->tableGateway->sql); - $resultSetPrototype->setArrayObjectPrototype($rowGatewayPrototype); - } elseif ($args[0] instanceof RowGatewayInterface) { - $rowGatewayPrototype = $args[0]; - $resultSetPrototype->setArrayObjectPrototype($rowGatewayPrototype); - } - } else { - // get from metadata feature - $metadata = $this->tableGateway->featureSet->getFeatureByClassName('Zend\Db\TableGateway\Feature\MetadataFeature'); - if ($metadata === false || !isset($metadata->sharedData['metadata'])) { - throw new Exception\RuntimeException( - 'No information was provided to the RowGatewayFeature and/or no MetadataFeature could be consulted to find the primary key necessary for RowGateway object creation.' - ); - } - $primaryKey = $metadata->sharedData['metadata']['primaryKey']; - $rowGatewayPrototype = new RowGateway($primaryKey, $this->tableGateway->table, $this->tableGateway->adapter, $this->tableGateway->sql); - $resultSetPrototype->setArrayObjectPrototype($rowGatewayPrototype); - } - } -} diff --git a/library/Zend/Db/TableGateway/Feature/SequenceFeature.php b/library/Zend/Db/TableGateway/Feature/SequenceFeature.php deleted file mode 100755 index 9f58d1a56..000000000 --- a/library/Zend/Db/TableGateway/Feature/SequenceFeature.php +++ /dev/null @@ -1,133 +0,0 @@ -primaryKeyField = $primaryKeyField; - $this->sequenceName = $sequenceName; - } - - /** - * @param Insert $insert - * @return Insert - */ - public function preInsert(Insert $insert) - { - $columns = $insert->getRawState('columns'); - $values = $insert->getRawState('values'); - $key = array_search($this->primaryKeyField, $columns); - if ($key !== false) { - $this->sequenceValue = $values[$key]; - return $insert; - } - - $this->sequenceValue = $this->nextSequenceId(); - if ($this->sequenceValue === null) { - return $insert; - } - - $insert->values(array($this->primaryKeyField => $this->sequenceValue), Insert::VALUES_MERGE); - return $insert; - } - - /** - * @param StatementInterface $statement - * @param ResultInterface $result - */ - public function postInsert(StatementInterface $statement, ResultInterface $result) - { - if ($this->sequenceValue !== null) { - $this->tableGateway->lastInsertValue = $this->sequenceValue; - } - } - - /** - * Generate a new value from the specified sequence in the database, and return it. - * @return int - */ - public function nextSequenceId() - { - $platform = $this->tableGateway->adapter->getPlatform(); - $platformName = $platform->getName(); - - switch ($platformName) { - case 'Oracle': - $sql = 'SELECT ' . $platform->quoteIdentifier($this->sequenceName) . '.NEXTVAL as "nextval" FROM dual'; - break; - case 'PostgreSQL': - $sql = 'SELECT NEXTVAL(\'"' . $this->sequenceName . '"\')'; - break; - default : - return null; - } - - $statement = $this->tableGateway->adapter->createStatement(); - $statement->prepare($sql); - $result = $statement->execute(); - $sequence = $result->current(); - unset($statement, $result); - return $sequence['nextval']; - } - - /** - * Return the most recent value from the specified sequence in the database. - * @return int - */ - public function lastSequenceId() - { - $platform = $this->tableGateway->adapter->getPlatform(); - $platformName = $platform->getName(); - - switch ($platformName) { - case 'Oracle': - $sql = 'SELECT ' . $platform->quoteIdentifier($this->sequenceName) . '.CURRVAL as "currval" FROM dual'; - break; - case 'PostgreSQL': - $sql = 'SELECT CURRVAL(\'' . $this->sequenceName . '\')'; - break; - default : - return null; - } - - $statement = $this->tableGateway->adapter->createStatement(); - $statement->prepare($sql); - $result = $statement->execute(); - $sequence = $result->current(); - unset($statement, $result); - return $sequence['currval']; - } -} diff --git a/library/Zend/Db/TableGateway/TableGateway.php b/library/Zend/Db/TableGateway/TableGateway.php deleted file mode 100755 index 0defd8a4d..000000000 --- a/library/Zend/Db/TableGateway/TableGateway.php +++ /dev/null @@ -1,72 +0,0 @@ -table = $table; - - // adapter - $this->adapter = $adapter; - - // process features - if ($features !== null) { - if ($features instanceof Feature\AbstractFeature) { - $features = array($features); - } - if (is_array($features)) { - $this->featureSet = new Feature\FeatureSet($features); - } elseif ($features instanceof Feature\FeatureSet) { - $this->featureSet = $features; - } else { - throw new Exception\InvalidArgumentException( - 'TableGateway expects $feature to be an instance of an AbstractFeature or a FeatureSet, or an array of AbstractFeatures' - ); - } - } else { - $this->featureSet = new Feature\FeatureSet(); - } - - // result prototype - $this->resultSetPrototype = ($resultSetPrototype) ?: new ResultSet; - - // Sql object (factory for select, insert, update, delete) - $this->sql = ($sql) ?: new Sql($this->adapter, $this->table); - - // check sql object bound to same table - if ($this->sql->getTable() != $this->table) { - throw new Exception\InvalidArgumentException('The table inside the provided Sql object must match the table of this TableGateway'); - } - - $this->initialize(); - } -} diff --git a/library/Zend/Db/TableGateway/TableGatewayInterface.php b/library/Zend/Db/TableGateway/TableGatewayInterface.php deleted file mode 100755 index 0a77e0f1d..000000000 --- a/library/Zend/Db/TableGateway/TableGatewayInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -=5.3.23" - }, - "require-dev": { - "zendframework/zend-eventmanager": "self.version", - "zendframework/zend-servicemanager": "self.version", - "zendframework/zend-stdlib": "self.version" - }, - "suggest": { - "zendframework/zend-eventmanager": "Zend\\EventManager component", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component", - "zendframework/zend-stdlib": "Zend\\Stdlib component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Debug/CONTRIBUTING.md b/library/Zend/Debug/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Debug/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Debug/Debug.php b/library/Zend/Debug/Debug.php deleted file mode 100755 index f240935c8..000000000 --- a/library/Zend/Debug/Debug.php +++ /dev/null @@ -1,124 +0,0 @@ - tags, cleans up newlines and indents, and runs - * htmlentities() before output. - * - * @param mixed $var The variable to dump. - * @param string $label OPTIONAL Label to prepend to output. - * @param bool $echo OPTIONAL Echo output if true. - * @return string - */ - public static function dump($var, $label = null, $echo = true) - { - // format the label - $label = ($label===null) ? '' : rtrim($label) . ' '; - - // var_dump the variable into a buffer and keep the output - ob_start(); - var_dump($var); - $output = ob_get_clean(); - - // neaten the newlines and indents - $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output); - if (static::getSapi() == 'cli') { - $output = PHP_EOL . $label - . PHP_EOL . $output - . PHP_EOL; - } else { - if (null !== static::$escaper) { - $output = static::$escaper->escapeHtml($output); - } elseif (!extension_loaded('xdebug')) { - $output = static::getEscaper()->escapeHtml($output); - } - - $output = '

        '
        -                    . $label
        -                    . $output
        -                    . '
        '; - } - - if ($echo) { - echo $output; - } - return $output; - } -} diff --git a/library/Zend/Debug/README.md b/library/Zend/Debug/README.md deleted file mode 100755 index 8797b8e21..000000000 --- a/library/Zend/Debug/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Debug Component from ZF2 -======================== - -This is the Debug component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Debug/composer.json b/library/Zend/Debug/composer.json deleted file mode 100755 index b6c18c7bf..000000000 --- a/library/Zend/Debug/composer.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "zendframework/zend-debug", - "description": " ", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "debug" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Debug\\": "" - } - }, - "target-dir": "Zend/Debug", - "require": { - "php": ">=5.3.23" - }, - "require-dev": { - "zendframework/zend-escaper": "*" - }, - "suggest": { - "ext/xdebug": "XDebug, for better backtrace output", - "zendframework/zend-escaper": "To support escaped output" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Di/CONTRIBUTING.md b/library/Zend/Di/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Di/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Di/Config.php b/library/Zend/Di/Config.php deleted file mode 100755 index b17730504..000000000 --- a/library/Zend/Di/Config.php +++ /dev/null @@ -1,196 +0,0 @@ -data = $options; - } - - /** - * Configure - * - * @param Di $di - * @return void - */ - public function configure(Di $di) - { - if (isset($this->data['definition'])) { - $this->configureDefinition($di, $this->data['definition']); - } - if (isset($this->data['instance'])) { - $this->configureInstance($di, $this->data['instance']); - } - } - - /** - * @param Di $di - * @param array $definition - */ - public function configureDefinition(Di $di, $definition) - { - foreach ($definition as $definitionType => $definitionData) { - switch ($definitionType) { - case 'compiler': - foreach ($definitionData as $filename) { - if (is_readable($filename)) { - $di->definitions()->addDefinition(new ArrayDefinition(include $filename), false); - } - } - break; - case 'runtime': - if (isset($definitionData['enabled']) && !$definitionData['enabled']) { - // Remove runtime from definition list if not enabled - $definitions = array(); - foreach ($di->definitions() as $definition) { - if (!$definition instanceof RuntimeDefinition) { - $definitions[] = $definition; - } - } - $definitionList = new DefinitionList($definitions); - $di->setDefinitionList($definitionList); - } elseif (isset($definitionData['use_annotations']) && $definitionData['use_annotations']) { - /* @var $runtimeDefinition Definition\RuntimeDefinition */ - $runtimeDefinition = $di - ->definitions() - ->getDefinitionByType('\Zend\Di\Definition\RuntimeDefinition'); - $runtimeDefinition->getIntrospectionStrategy()->setUseAnnotations(true); - } - break; - case 'class': - foreach ($definitionData as $className => $classData) { - $classDefinitions = $di->definitions()->getDefinitionsByType('Zend\Di\Definition\ClassDefinition'); - foreach ($classDefinitions as $classDefinition) { - if (!$classDefinition->hasClass($className)) { - unset($classDefinition); - } - } - if (!isset($classDefinition)) { - $classDefinition = new Definition\ClassDefinition($className); - $di->definitions()->addDefinition($classDefinition, false); - } - foreach ($classData as $classDefKey => $classDefData) { - switch ($classDefKey) { - case 'instantiator': - $classDefinition->setInstantiator($classDefData); - break; - case 'supertypes': - $classDefinition->setSupertypes($classDefData); - break; - case 'methods': - case 'method': - foreach ($classDefData as $methodName => $methodInfo) { - if (isset($methodInfo['required'])) { - $classDefinition->addMethod($methodName, $methodInfo['required']); - unset($methodInfo['required']); - } - foreach ($methodInfo as $paramName => $paramInfo) { - $classDefinition->addMethodParameter($methodName, $paramName, $paramInfo); - } - } - break; - default: - $methodName = $classDefKey; - $methodInfo = $classDefData; - if (isset($classDefData['required'])) { - $classDefinition->addMethod($methodName, $methodInfo['required']); - unset($methodInfo['required']); - } - foreach ($methodInfo as $paramName => $paramInfo) { - $classDefinition->addMethodParameter($methodName, $paramName, $paramInfo); - } - } - } - } - } - } - } - - /** - * Configures a given Di instance - * - * @param Di $di - * @param $instanceData - */ - public function configureInstance(Di $di, $instanceData) - { - $im = $di->instanceManager(); - - foreach ($instanceData as $target => $data) { - switch (strtolower($target)) { - case 'aliases': - case 'alias': - foreach ($data as $n => $v) { - $im->addAlias($n, $v); - } - break; - case 'preferences': - case 'preference': - foreach ($data as $n => $v) { - if (is_array($v)) { - foreach ($v as $v2) { - $im->addTypePreference($n, $v2); - } - } else { - $im->addTypePreference($n, $v); - } - } - break; - default: - foreach ($data as $n => $v) { - switch ($n) { - case 'parameters': - case 'parameter': - $im->setParameters($target, $v); - break; - case 'injections': - case 'injection': - $im->setInjections($target, $v); - break; - case 'shared': - case 'share': - $im->setShared($target, $v); - break; - } - } - } - } - } -} diff --git a/library/Zend/Di/Definition/Annotation/Inject.php b/library/Zend/Di/Definition/Annotation/Inject.php deleted file mode 100755 index 8534c0215..000000000 --- a/library/Zend/Di/Definition/Annotation/Inject.php +++ /dev/null @@ -1,31 +0,0 @@ -content = $content; - } -} diff --git a/library/Zend/Di/Definition/Annotation/Instantiator.php b/library/Zend/Di/Definition/Annotation/Instantiator.php deleted file mode 100755 index d0aed5310..000000000 --- a/library/Zend/Di/Definition/Annotation/Instantiator.php +++ /dev/null @@ -1,31 +0,0 @@ -content = $content; - } -} diff --git a/library/Zend/Di/Definition/ArrayDefinition.php b/library/Zend/Di/Definition/ArrayDefinition.php deleted file mode 100755 index 5e64f5b38..000000000 --- a/library/Zend/Di/Definition/ArrayDefinition.php +++ /dev/null @@ -1,176 +0,0 @@ - $value) { - // force lower names - $dataArray[$class] = array_change_key_case($dataArray[$class], CASE_LOWER); - } - foreach ($dataArray as $class => $definition) { - if (isset($definition['methods']) && is_array($definition['methods'])) { - foreach ($definition['methods'] as $type => $requirement) { - if (!is_int($requirement)) { - $dataArray[$class]['methods'][$type] = InjectionMethod::detectMethodRequirement($requirement); - } - } - } - } - $this->dataArray = $dataArray; - } - - /** - * {@inheritDoc} - */ - public function getClasses() - { - return array_keys($this->dataArray); - } - - /** - * {@inheritDoc} - */ - public function hasClass($class) - { - return array_key_exists($class, $this->dataArray); - } - - /** - * {@inheritDoc} - */ - public function getClassSupertypes($class) - { - if (!isset($this->dataArray[$class])) { - return array(); - } - - if (!isset($this->dataArray[$class]['supertypes'])) { - return array(); - } - - return $this->dataArray[$class]['supertypes']; - } - - /** - * {@inheritDoc} - */ - public function getInstantiator($class) - { - if (!isset($this->dataArray[$class])) { - return null; - } - - if (!isset($this->dataArray[$class]['instantiator'])) { - return '__construct'; - } - - return $this->dataArray[$class]['instantiator']; - } - - /** - * {@inheritDoc} - */ - public function hasMethods($class) - { - if (!isset($this->dataArray[$class])) { - return false; - } - - if (!isset($this->dataArray[$class]['methods'])) { - return false; - } - - return (count($this->dataArray[$class]['methods']) > 0); - } - - /** - * {@inheritDoc} - */ - public function hasMethod($class, $method) - { - if (!isset($this->dataArray[$class])) { - return false; - } - - if (!isset($this->dataArray[$class]['methods'])) { - return false; - } - - return array_key_exists($method, $this->dataArray[$class]['methods']); - } - - /** - * {@inheritDoc} - */ - public function getMethods($class) - { - if (!isset($this->dataArray[$class])) { - return array(); - } - - if (!isset($this->dataArray[$class]['methods'])) { - return array(); - } - - return $this->dataArray[$class]['methods']; - } - - /** - * {@inheritDoc} - */ - public function hasMethodParameters($class, $method) - { - return isset($this->dataArray[$class]['parameters'][$method]); - } - - /** - * {@inheritDoc} - */ - public function getMethodParameters($class, $method) - { - if (!isset($this->dataArray[$class])) { - return array(); - } - - if (!isset($this->dataArray[$class]['parameters'])) { - return array(); - } - - if (!isset($this->dataArray[$class]['parameters'][$method])) { - return array(); - } - - return $this->dataArray[$class]['parameters'][$method]; - } - - /** - * @return array - */ - public function toArray() - { - return $this->dataArray; - } -} diff --git a/library/Zend/Di/Definition/Builder/InjectionMethod.php b/library/Zend/Di/Definition/Builder/InjectionMethod.php deleted file mode 100755 index a27f7b192..000000000 --- a/library/Zend/Di/Definition/Builder/InjectionMethod.php +++ /dev/null @@ -1,121 +0,0 @@ -name = $name; - - return $this; - } - - /** - * @return null|string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - * @param string|null $class - * @param mixed|null $isRequired - * @param mixed|null $default - * @return InjectionMethod - */ - public function addParameter($name, $class = null, $isRequired = null, $default = null) - { - $this->parameters[] = array( - $name, - $class, - self::detectMethodRequirement($isRequired), - $default, - ); - - return $this; - } - - /** - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * - * @param mixed $requirement - * @return int - */ - public static function detectMethodRequirement($requirement) - { - if (is_bool($requirement)) { - return $requirement ? Di::METHOD_IS_REQUIRED : Di::METHOD_IS_OPTIONAL; - } - - if (null === $requirement) { - //This is mismatch to ClassDefinition::addMethod is it ok ? is optional? - return Di::METHOD_IS_REQUIRED; - } - - if (is_int($requirement)) { - return $requirement; - } - - if (is_string($requirement)) { - switch (strtolower($requirement)) { - default: - case "require": - case "required": - return Di::METHOD_IS_REQUIRED; - break; - case "aware": - return Di::METHOD_IS_AWARE; - break; - case "optional": - return Di::METHOD_IS_OPTIONAL; - break; - case "constructor": - return Di::METHOD_IS_CONSTRUCTOR; - break; - case "instantiator": - return Di::METHOD_IS_INSTANTIATOR; - break; - case "eager": - return Di::METHOD_IS_EAGER; - break; - } - } - return 0; - } -} diff --git a/library/Zend/Di/Definition/Builder/PhpClass.php b/library/Zend/Di/Definition/Builder/PhpClass.php deleted file mode 100755 index 80d4197a2..000000000 --- a/library/Zend/Di/Definition/Builder/PhpClass.php +++ /dev/null @@ -1,175 +0,0 @@ -name = $name; - - return $this; - } - - /** - * Get name - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string|\Callable|array $instantiator - * @return PhpClass - */ - public function setInstantiator($instantiator) - { - $this->instantiator = $instantiator; - - return $this; - } - - /** - * @return array|\Callable|string - */ - public function getInstantiator() - { - return $this->instantiator; - } - - /** - * @param string $superType - * @return PhpClass - */ - public function addSuperType($superType) - { - $this->superTypes[] = $superType; - - return $this; - } - - /** - * Get super types - * - * @return array - */ - public function getSuperTypes() - { - return $this->superTypes; - } - - /** - * Add injection method - * - * @param InjectionMethod $injectionMethod - * @return PhpClass - */ - public function addInjectionMethod(InjectionMethod $injectionMethod) - { - $this->injectionMethods[] = $injectionMethod; - - return $this; - } - - /** - * Create and register an injection method - * - * Optionally takes the method name. - * - * This method may be used in lieu of addInjectionMethod() in - * order to provide a more fluent interface for building classes with - * injection methods. - * - * @param null|string $name - * @return InjectionMethod - */ - public function createInjectionMethod($name = null) - { - $builder = $this->defaultMethodBuilder; - /* @var $method InjectionMethod */ - $method = new $builder(); - if (null !== $name) { - $method->setName($name); - } - $this->addInjectionMethod($method); - - return $method; - } - - /** - * Override which class will be used by {@link createInjectionMethod()} - * - * @param string $class - * @return PhpClass - */ - public function setMethodBuilder($class) - { - $this->defaultMethodBuilder = $class; - - return $this; - } - - /** - * Determine what class will be used by {@link createInjectionMethod()} - * - * Mainly to provide the ability to temporarily override the class used. - * - * @return string - */ - public function getMethodBuilder() - { - return $this->defaultMethodBuilder; - } - - /** - * @return InjectionMethod[] - */ - public function getInjectionMethods() - { - return $this->injectionMethods; - } -} diff --git a/library/Zend/Di/Definition/BuilderDefinition.php b/library/Zend/Di/Definition/BuilderDefinition.php deleted file mode 100755 index 6ad935a07..000000000 --- a/library/Zend/Di/Definition/BuilderDefinition.php +++ /dev/null @@ -1,321 +0,0 @@ - $classInfo) { - $class = new Builder\PhpClass(); - $class->setName($className); - foreach ($classInfo as $type => $typeData) { - switch (strtolower($type)) { - case 'supertypes': - foreach ($typeData as $superType) { - $class->addSuperType($superType); - } - break; - case 'instantiator': - $class->setInstantiator($typeData); - break; - case 'methods': - case 'method': - foreach ($typeData as $injectionMethodName => $injectionMethodData) { - $injectionMethod = new Builder\InjectionMethod(); - $injectionMethod->setName($injectionMethodName); - foreach ($injectionMethodData as $parameterName => $parameterType) { - $parameterType = ($parameterType) ?: null; // force empty string to null - $injectionMethod->addParameter($parameterName, $parameterType); - } - $class->addInjectionMethod($injectionMethod); - } - break; - - } - } - $this->addClass($class); - } - } - - /** - * Add class - * - * @param Builder\PhpClass $phpClass - * @return BuilderDefinition - */ - public function addClass(Builder\PhpClass $phpClass) - { - $this->classes[] = $phpClass; - - return $this; - } - - /** - * Create a class builder object using default class builder class - * - * This method is a factory that can be used in place of addClass(). - * - * @param null|string $name Optional name of class to assign - * @return Builder\PhpClass - */ - public function createClass($name = null) - { - $builderClass = $this->defaultClassBuilder; - /* @var $class Builder\PhpClass */ - $class = new $builderClass(); - - if (null !== $name) { - $class->setName($name); - } - - $this->addClass($class); - - return $class; - } - - /** - * Set the class to use with {@link createClass()} - * - * @param string $class - * @return BuilderDefinition - */ - public function setClassBuilder($class) - { - $this->defaultClassBuilder = $class; - - return $this; - } - - /** - * Get the class used for {@link createClass()} - * - * This is primarily to allow developers to temporarily override - * the builder strategy. - * - * @return string - */ - public function getClassBuilder() - { - return $this->defaultClassBuilder; - } - - /** - * {@inheritDoc} - */ - public function getClasses() - { - $classNames = array(); - - /* @var $class Builder\PhpClass */ - foreach ($this->classes as $class) { - $classNames[] = $class->getName(); - } - - return $classNames; - } - - /** - * {@inheritDoc} - */ - public function hasClass($class) - { - foreach ($this->classes as $classObj) { - if ($classObj->getName() === $class) { - return true; - } - } - - return false; - } - - /** - * @param string $name - * @return bool|Builder\PhpClass - */ - protected function getClass($name) - { - foreach ($this->classes as $classObj) { - if ($classObj->getName() === $name) { - return $classObj; - } - } - - return false; - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\RuntimeException - */ - public function getClassSupertypes($class) - { - $class = $this->getClass($class); - - if ($class === false) { - throw new Exception\RuntimeException('Cannot find class object in this builder definition.'); - } - - return $class->getSuperTypes(); - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\RuntimeException - */ - public function getInstantiator($class) - { - $class = $this->getClass($class); - if ($class === false) { - throw new Exception\RuntimeException('Cannot find class object in this builder definition.'); - } - - return $class->getInstantiator(); - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\RuntimeException - */ - public function hasMethods($class) - { - /* @var $class \Zend\Di\Definition\Builder\PhpClass */ - $class = $this->getClass($class); - if ($class === false) { - throw new Exception\RuntimeException('Cannot find class object in this builder definition.'); - } - - return (count($class->getInjectionMethods()) > 0); - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\RuntimeException - */ - public function getMethods($class) - { - $class = $this->getClass($class); - if ($class === false) { - throw new Exception\RuntimeException('Cannot find class object in this builder definition.'); - } - $methods = $class->getInjectionMethods(); - $methodNames = array(); - - /* @var $methodObj Builder\InjectionMethod */ - foreach ($methods as $methodObj) { - $methodNames[] = $methodObj->getName(); - } - - return $methodNames; - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\RuntimeException - */ - public function hasMethod($class, $method) - { - $class = $this->getClass($class); - if ($class === false) { - throw new Exception\RuntimeException('Cannot find class object in this builder definition.'); - } - $methods = $class->getInjectionMethods(); - - /* @var $methodObj Builder\InjectionMethod */ - foreach ($methods as $methodObj) { - if ($methodObj->getName() === $method) { - return true; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - public function hasMethodParameters($class, $method) - { - $class = $this->getClass($class); - if ($class === false) { - return false; - } - $methods = $class->getInjectionMethods(); - /* @var $methodObj Builder\InjectionMethod */ - foreach ($methods as $methodObj) { - if ($methodObj->getName() === $method) { - $method = $methodObj; - } - } - if (!$method instanceof Builder\InjectionMethod) { - return false; - } - - /* @var $method Builder\InjectionMethod */ - - return (count($method->getParameters()) > 0); - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\RuntimeException - */ - public function getMethodParameters($class, $method) - { - $class = $this->getClass($class); - - if ($class === false) { - throw new Exception\RuntimeException('Cannot find class object in this builder definition.'); - } - - $methods = $class->getInjectionMethods(); - - /* @var $methodObj Builder\InjectionMethod */ - foreach ($methods as $methodObj) { - if ($methodObj->getName() === $method) { - $method = $methodObj; - } - } - - if (!$method instanceof Builder\InjectionMethod) { - throw new Exception\RuntimeException('Cannot find method object for method ' . $method . ' in this builder definition.'); - } - - $methodParameters = array(); - - /* @var $method Builder\InjectionMethod */ - foreach ($method->getParameters() as $name => $info) { - $methodParameters[$class->getName() . '::' . $method->getName() . ':' . $name] = $info; - } - - return $methodParameters; - } -} diff --git a/library/Zend/Di/Definition/ClassDefinition.php b/library/Zend/Di/Definition/ClassDefinition.php deleted file mode 100755 index 2b110659d..000000000 --- a/library/Zend/Di/Definition/ClassDefinition.php +++ /dev/null @@ -1,231 +0,0 @@ -class = $class; - } - - /** - * @param null|\Callable|array|string $instantiator - * @return self - */ - public function setInstantiator($instantiator) - { - $this->instantiator = $instantiator; - - return $this; - } - - /** - * @param string[] $supertypes - * @return self - */ - public function setSupertypes(array $supertypes) - { - $this->supertypes = $supertypes; - - return $this; - } - - /** - * @param string $method - * @param mixed|bool|null $isRequired - * @return self - */ - public function addMethod($method, $isRequired = null) - { - if ($isRequired === null) { - if ($method === '__construct') { - $methodRequirementType = Di::METHOD_IS_CONSTRUCTOR; - } else { - $methodRequirementType = Di::METHOD_IS_OPTIONAL; - } - } else { - $methodRequirementType = InjectionMethod::detectMethodRequirement($isRequired); - } - - $this->methods[$method] = $methodRequirementType; - - return $this; - } - - /** - * @param $method - * @param $parameterName - * @param array $parameterInfo (keys: required, type) - * @return ClassDefinition - */ - public function addMethodParameter($method, $parameterName, array $parameterInfo) - { - if (!array_key_exists($method, $this->methods)) { - if ($method === '__construct') { - $this->methods[$method] = Di::METHOD_IS_CONSTRUCTOR; - } else { - $this->methods[$method] = Di::METHOD_IS_OPTIONAL; - } - } - - if (!array_key_exists($method, $this->methodParameters)) { - $this->methodParameters[$method] = array(); - } - - $type = (isset($parameterInfo['type'])) ? $parameterInfo['type'] : null; - $required = (isset($parameterInfo['required'])) ? (bool) $parameterInfo['required'] : false; - $default = (isset($parameterInfo['default'])) ? $parameterInfo['default'] : null; - - $fqName = $this->class . '::' . $method . ':' . $parameterName; - $this->methodParameters[$method][$fqName] = array( - $parameterName, - $type, - $required, - $default - ); - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getClasses() - { - return array($this->class); - } - - /** - * {@inheritDoc} - */ - public function hasClass($class) - { - return ($class === $this->class); - } - - /** - * {@inheritDoc} - */ - public function getClassSupertypes($class) - { - if ($this->class !== $class) { - return array(); - } - return $this->supertypes; - } - - /** - * {@inheritDoc} - */ - public function getInstantiator($class) - { - if ($this->class !== $class) { - return null; - } - return $this->instantiator; - } - - /** - * {@inheritDoc} - */ - public function hasMethods($class) - { - return (count($this->methods) > 0); - } - - /** - * {@inheritDoc} - */ - public function getMethods($class) - { - if ($this->class !== $class) { - return array(); - } - return $this->methods; - } - - /** - * {@inheritDoc} - */ - public function hasMethod($class, $method) - { - if ($this->class !== $class) { - return null; - } - - if (is_array($this->methods)) { - return array_key_exists($method, $this->methods); - } - - return null; - } - - /** - * {@inheritDoc} - */ - public function hasMethodParameters($class, $method) - { - if ($this->class !== $class) { - return false; - } - return (array_key_exists($method, $this->methodParameters)); - } - - /** - * {@inheritDoc} - */ - public function getMethodParameters($class, $method) - { - if ($this->class !== $class) { - return null; - } - - if (array_key_exists($method, $this->methodParameters)) { - return $this->methodParameters[$method]; - } - - return null; - } -} diff --git a/library/Zend/Di/Definition/CompilerDefinition.php b/library/Zend/Di/Definition/CompilerDefinition.php deleted file mode 100755 index dcecde10f..000000000 --- a/library/Zend/Di/Definition/CompilerDefinition.php +++ /dev/null @@ -1,397 +0,0 @@ -introspectionStrategy = ($introspectionStrategy) ?: new IntrospectionStrategy(); - $this->directoryScanner = new AggregateDirectoryScanner(); - } - - /** - * Set introspection strategy - * - * @param IntrospectionStrategy $introspectionStrategy - */ - public function setIntrospectionStrategy(IntrospectionStrategy $introspectionStrategy) - { - $this->introspectionStrategy = $introspectionStrategy; - } - - /** - * @param bool $allowReflectionExceptions - */ - public function setAllowReflectionExceptions($allowReflectionExceptions = true) - { - $this->allowReflectionExceptions = (bool) $allowReflectionExceptions; - } - - /** - * Get introspection strategy - * - * @return IntrospectionStrategy - */ - public function getIntrospectionStrategy() - { - return $this->introspectionStrategy; - } - - /** - * Add directory - * - * @param string $directory - */ - public function addDirectory($directory) - { - $this->addDirectoryScanner(new DirectoryScanner($directory)); - } - - /** - * Add directory scanner - * - * @param DirectoryScanner $directoryScanner - */ - public function addDirectoryScanner(DirectoryScanner $directoryScanner) - { - $this->directoryScanner->addDirectoryScanner($directoryScanner); - } - - /** - * Add code scanner file - * - * @param FileScanner $fileScanner - */ - public function addCodeScannerFile(FileScanner $fileScanner) - { - if ($this->directoryScanner == null) { - $this->directoryScanner = new DirectoryScanner(); - } - - $this->directoryScanner->addFileScanner($fileScanner); - } - - /** - * Compile - * - * @return void - */ - public function compile() - { - /* @var $classScanner DerivedClassScanner */ - foreach ($this->directoryScanner->getClassNames() as $class) { - $this->processClass($class); - } - } - - /** - * @return ArrayDefinition - */ - public function toArrayDefinition() - { - return new ArrayDefinition( - $this->classes - ); - } - - /** - * @param string $class - * @throws \ReflectionException - */ - protected function processClass($class) - { - $strategy = $this->introspectionStrategy; // localize for readability - - try { - $rClass = new Reflection\ClassReflection($class); - } catch (\ReflectionException $e) { - if (!$this->allowReflectionExceptions) { - throw $e; - } - - return; - } - $className = $rClass->getName(); - $matches = null; // used for regex below - - // setup the key in classes - $this->classes[$className] = array( - 'supertypes' => array(), - 'instantiator' => null, - 'methods' => array(), - 'parameters' => array() - ); - - $def = &$this->classes[$className]; // localize for brevity - - // class annotations? - if ($strategy->getUseAnnotations() == true) { - $annotations = $rClass->getAnnotations($strategy->getAnnotationManager()); - - if (($annotations instanceof AnnotationCollection) - && $annotations->hasAnnotation('Zend\Di\Definition\Annotation\Instantiator') - ) { - // @todo Instantiator support in annotations - } - } - - /* @var $rTarget \Zend\Code\Reflection\ClassReflection */ - $rTarget = $rClass; - $supertypes = array(); - do { - $supertypes = array_merge($supertypes, $rTarget->getInterfaceNames()); - if (!($rTargetParent = $rTarget->getParentClass())) { - break; - } - $supertypes[] = $rTargetParent->getName(); - $rTarget = $rTargetParent; - } while (true); - - $def['supertypes'] = $supertypes; - - if ($def['instantiator'] == null) { - if ($rClass->isInstantiable()) { - $def['instantiator'] = '__construct'; - } - } - - if ($rClass->hasMethod('__construct')) { - $def['methods']['__construct'] = true; // required - try { - $this->processParams($def, $rClass, $rClass->getMethod('__construct')); - } catch (\ReflectionException $e) { - if (!$this->allowReflectionExceptions) { - throw $e; - } - - return; - } - } - - foreach ($rClass->getMethods(Reflection\MethodReflection::IS_PUBLIC) as $rMethod) { - $methodName = $rMethod->getName(); - - if ($rMethod->getName() === '__construct' || $rMethod->isStatic()) { - continue; - } - - if ($strategy->getUseAnnotations() == true) { - $annotations = $rMethod->getAnnotations($strategy->getAnnotationManager()); - - if (($annotations instanceof AnnotationCollection) - && $annotations->hasAnnotation('Zend\Di\Definition\Annotation\Inject') - ) { - $def['methods'][$methodName] = true; - $this->processParams($def, $rClass, $rMethod); - continue; - } - } - - $methodPatterns = $this->introspectionStrategy->getMethodNameInclusionPatterns(); - - // matches a method injection pattern? - foreach ($methodPatterns as $methodInjectorPattern) { - preg_match($methodInjectorPattern, $methodName, $matches); - if ($matches) { - $def['methods'][$methodName] = false; // check ot see if this is required? - $this->processParams($def, $rClass, $rMethod); - continue 2; - } - } - - // method - // by annotation - // by setter pattern, - // by interface - } - - $interfaceInjectorPatterns = $this->introspectionStrategy->getInterfaceInjectionInclusionPatterns(); - - // matches the interface injection pattern - /** @var $rIface \ReflectionClass */ - foreach ($rClass->getInterfaces() as $rIface) { - foreach ($interfaceInjectorPatterns as $interfaceInjectorPattern) { - preg_match($interfaceInjectorPattern, $rIface->getName(), $matches); - if ($matches) { - foreach ($rIface->getMethods() as $rMethod) { - if (($rMethod->getName() === '__construct') || !count($rMethod->getParameters())) { - // constructor not allowed in interfaces - // ignore methods without parameters - continue; - } - $def['methods'][$rMethod->getName()] = true; - $this->processParams($def, $rClass, $rMethod); - } - continue 2; - } - } - } - } - - /** - * @param array $def - * @param \Zend\Code\Reflection\ClassReflection $rClass - * @param \Zend\Code\Reflection\MethodReflection $rMethod - */ - protected function processParams(&$def, Reflection\ClassReflection $rClass, Reflection\MethodReflection $rMethod) - { - if (count($rMethod->getParameters()) === 0) { - return; - } - - $methodName = $rMethod->getName(); - - // @todo annotations here for alternate names? - - $def['parameters'][$methodName] = array(); - - foreach ($rMethod->getParameters() as $p) { - /** @var $p \ReflectionParameter */ - $actualParamName = $p->getName(); - $fqName = $rClass->getName() . '::' . $rMethod->getName() . ':' . $p->getPosition(); - $def['parameters'][$methodName][$fqName] = array(); - - // set the class name, if it exists - $def['parameters'][$methodName][$fqName][] = $actualParamName; - $def['parameters'][$methodName][$fqName][] = ($p->getClass() !== null) ? $p->getClass()->getName() : null; - $def['parameters'][$methodName][$fqName][] = !($optional =$p->isOptional()); - $def['parameters'][$methodName][$fqName][] = $optional && $p->isDefaultValueAvailable() ? $p->getDefaultValue() : null; - } - } - - /** - * {@inheritDoc} - */ - public function getClasses() - { - return array_keys($this->classes); - } - - /** - * {@inheritDoc} - */ - public function hasClass($class) - { - return (array_key_exists($class, $this->classes)); - } - - /** - * {@inheritDoc} - */ - public function getClassSupertypes($class) - { - if (!array_key_exists($class, $this->classes)) { - $this->processClass($class); - } - - return $this->classes[$class]['supertypes']; - } - - /** - * {@inheritDoc} - */ - public function getInstantiator($class) - { - if (!array_key_exists($class, $this->classes)) { - $this->processClass($class); - } - - return $this->classes[$class]['instantiator']; - } - - /** - * {@inheritDoc} - */ - public function hasMethods($class) - { - if (!array_key_exists($class, $this->classes)) { - $this->processClass($class); - } - - return (count($this->classes[$class]['methods']) > 0); - } - - /** - * {@inheritDoc} - */ - public function hasMethod($class, $method) - { - if (!array_key_exists($class, $this->classes)) { - $this->processClass($class); - } - - return isset($this->classes[$class]['methods'][$method]); - } - - /** - * {@inheritDoc} - */ - public function getMethods($class) - { - if (!array_key_exists($class, $this->classes)) { - $this->processClass($class); - } - - return $this->classes[$class]['methods']; - } - - /** - * {@inheritDoc} - */ - public function hasMethodParameters($class, $method) - { - if (!isset($this->classes[$class])) { - return false; - } - - return (array_key_exists($method, $this->classes[$class]['parameters'])); - } - - /** - * {@inheritDoc} - */ - public function getMethodParameters($class, $method) - { - if (!is_array($this->classes[$class])) { - $this->processClass($class); - } - - return $this->classes[$class]['parameters'][$method]; - } -} diff --git a/library/Zend/Di/Definition/DefinitionInterface.php b/library/Zend/Di/Definition/DefinitionInterface.php deleted file mode 100755 index 420bb459d..000000000 --- a/library/Zend/Di/Definition/DefinitionInterface.php +++ /dev/null @@ -1,101 +0,0 @@ -annotationManager = ($annotationManager) ?: $this->createDefaultAnnotationManager(); - } - - /** - * Get annotation manager - * - * @return null|AnnotationManager - */ - public function getAnnotationManager() - { - return $this->annotationManager; - } - - /** - * Create default annotation manager - * - * @return AnnotationManager - */ - public function createDefaultAnnotationManager() - { - $annotationManager = new AnnotationManager; - $parser = new GenericAnnotationParser(); - $parser->registerAnnotation(new Annotation\Inject()); - $annotationManager->attach($parser); - - return $annotationManager; - } - - /** - * set use annotations - * - * @param bool $useAnnotations - */ - public function setUseAnnotations($useAnnotations) - { - $this->useAnnotations = (bool) $useAnnotations; - } - - /** - * Get use annotations - * - * @return bool - */ - public function getUseAnnotations() - { - return $this->useAnnotations; - } - - /** - * Set method name inclusion pattern - * - * @param array $methodNameInclusionPatterns - */ - public function setMethodNameInclusionPatterns(array $methodNameInclusionPatterns) - { - $this->methodNameInclusionPatterns = $methodNameInclusionPatterns; - } - - /** - * Get method name inclusion pattern - * - * @return array - */ - public function getMethodNameInclusionPatterns() - { - return $this->methodNameInclusionPatterns; - } - - /** - * Set interface injection inclusion patterns - * - * @param array $interfaceInjectionInclusionPatterns - */ - public function setInterfaceInjectionInclusionPatterns(array $interfaceInjectionInclusionPatterns) - { - $this->interfaceInjectionInclusionPatterns = $interfaceInjectionInclusionPatterns; - } - - /** - * Get interface injection inclusion patterns - * - * @return array - */ - public function getInterfaceInjectionInclusionPatterns() - { - return $this->interfaceInjectionInclusionPatterns; - } -} diff --git a/library/Zend/Di/Definition/PartialMarker.php b/library/Zend/Di/Definition/PartialMarker.php deleted file mode 100755 index 4a40728f0..000000000 --- a/library/Zend/Di/Definition/PartialMarker.php +++ /dev/null @@ -1,14 +0,0 @@ -introspectionStrategy = ($introspectionStrategy) ?: new IntrospectionStrategy(); - if ($explicitClasses) { - $this->setExplicitClasses($explicitClasses); - } - } - - /** - * @param IntrospectionStrategy $introspectionStrategy - * @return void - */ - public function setIntrospectionStrategy(IntrospectionStrategy $introspectionStrategy) - { - $this->introspectionStrategy = $introspectionStrategy; - } - - /** - * @return IntrospectionStrategy - */ - public function getIntrospectionStrategy() - { - return $this->introspectionStrategy; - } - - /** - * Set explicit classes - * - * @param array $explicitClasses - */ - public function setExplicitClasses(array $explicitClasses) - { - $this->explicitLookups = true; - foreach ($explicitClasses as $eClass) { - $this->classes[$eClass] = true; - } - $this->classes = $explicitClasses; - } - - /** - * @param string $class - */ - public function forceLoadClass($class) - { - $this->processClass($class, true); - } - - /** - * {@inheritDoc} - */ - public function getClasses() - { - return array_keys($this->classes); - } - - /** - * {@inheritDoc} - */ - public function hasClass($class) - { - if ($this->explicitLookups === true) { - return (array_key_exists($class, $this->classes)); - } - - return class_exists($class) || interface_exists($class); - } - - /** - * {@inheritDoc} - */ - public function getClassSupertypes($class) - { - $this->processClass($class); - return $this->classes[$class]['supertypes']; - } - - /** - * {@inheritDoc} - */ - public function getInstantiator($class) - { - $this->processClass($class); - return $this->classes[$class]['instantiator']; - } - - /** - * {@inheritDoc} - */ - public function hasMethods($class) - { - $this->processClass($class); - return (count($this->classes[$class]['methods']) > 0); - } - - /** - * {@inheritDoc} - */ - public function hasMethod($class, $method) - { - $this->processClass($class); - return isset($this->classes[$class]['methods'][$method]); - } - - /** - * {@inheritDoc} - */ - public function getMethods($class) - { - $this->processClass($class); - return $this->classes[$class]['methods']; - } - - /** - * {@inheritDoc} - */ - public function hasMethodParameters($class, $method) - { - $this->processClass($class); - return (array_key_exists($method, $this->classes[$class]['parameters'])); - } - - /** - * {@inheritDoc} - */ - public function getMethodParameters($class, $method) - { - $this->processClass($class); - return $this->classes[$class]['parameters'][$method]; - } - - /** - * @param string $class - * - * @return bool - */ - protected function hasProcessedClass($class) - { - return array_key_exists($class, $this->classes) && is_array($this->classes[$class]); - } - - /** - * @param string $class - * @param bool $forceLoad - */ - protected function processClass($class, $forceLoad = false) - { - if (!$forceLoad && $this->hasProcessedClass($class)) { - return; - } - $strategy = $this->introspectionStrategy; // localize for readability - - /** @var $rClass \Zend\Code\Reflection\ClassReflection */ - $rClass = new Reflection\ClassReflection($class); - $className = $rClass->getName(); - $matches = null; // used for regex below - - // setup the key in classes - $this->classes[$className] = array( - 'supertypes' => array(), - 'instantiator' => null, - 'methods' => array(), - 'parameters' => array() - ); - - $def = &$this->classes[$className]; // localize for brevity - - // class annotations? - if ($strategy->getUseAnnotations() == true) { - $annotations = $rClass->getAnnotations($strategy->getAnnotationManager()); - - if (($annotations instanceof AnnotationCollection) - && $annotations->hasAnnotation('Zend\Di\Definition\Annotation\Instantiator')) { - // @todo Instantiator support in annotations - } - } - - $rTarget = $rClass; - $supertypes = array(); - do { - $supertypes = array_merge($supertypes, $rTarget->getInterfaceNames()); - if (!($rTargetParent = $rTarget->getParentClass())) { - break; - } - $supertypes[] = $rTargetParent->getName(); - $rTarget = $rTargetParent; - } while (true); - - $def['supertypes'] = $supertypes; - - if ($def['instantiator'] == null) { - if ($rClass->isInstantiable()) { - $def['instantiator'] = '__construct'; - } - } - - if ($rClass->hasMethod('__construct')) { - $def['methods']['__construct'] = Di::METHOD_IS_CONSTRUCTOR; // required - $this->processParams($def, $rClass, $rClass->getMethod('__construct')); - } - - foreach ($rClass->getMethods(Reflection\MethodReflection::IS_PUBLIC) as $rMethod) { - $methodName = $rMethod->getName(); - - if ($rMethod->getName() === '__construct' || $rMethod->isStatic()) { - continue; - } - - if ($strategy->getUseAnnotations() == true) { - $annotations = $rMethod->getAnnotations($strategy->getAnnotationManager()); - - if (($annotations instanceof AnnotationCollection) - && $annotations->hasAnnotation('Zend\Di\Definition\Annotation\Inject')) { - // use '@inject' and search for parameters - $def['methods'][$methodName] = Di::METHOD_IS_EAGER; - $this->processParams($def, $rClass, $rMethod); - continue; - } - } - - $methodPatterns = $this->introspectionStrategy->getMethodNameInclusionPatterns(); - - // matches a method injection pattern? - foreach ($methodPatterns as $methodInjectorPattern) { - preg_match($methodInjectorPattern, $methodName, $matches); - if ($matches) { - $def['methods'][$methodName] = Di::METHOD_IS_OPTIONAL; // check ot see if this is required? - $this->processParams($def, $rClass, $rMethod); - continue 2; - } - } - - // method - // by annotation - // by setter pattern, - // by interface - } - - $interfaceInjectorPatterns = $this->introspectionStrategy->getInterfaceInjectionInclusionPatterns(); - - // matches the interface injection pattern - /** @var $rIface \ReflectionClass */ - foreach ($rClass->getInterfaces() as $rIface) { - foreach ($interfaceInjectorPatterns as $interfaceInjectorPattern) { - preg_match($interfaceInjectorPattern, $rIface->getName(), $matches); - if ($matches) { - foreach ($rIface->getMethods() as $rMethod) { - if (($rMethod->getName() === '__construct') || !count($rMethod->getParameters())) { - // constructor not allowed in interfaces - // Don't call interface methods without a parameter (Some aware interfaces define setters in ZF2) - continue; - } - $def['methods'][$rMethod->getName()] = Di::METHOD_IS_AWARE; - $this->processParams($def, $rClass, $rMethod); - } - continue 2; - } - } - } - } - - /** - * @param array $def - * @param \Zend\Code\Reflection\ClassReflection $rClass - * @param \Zend\Code\Reflection\MethodReflection $rMethod - */ - protected function processParams(&$def, Reflection\ClassReflection $rClass, Reflection\MethodReflection $rMethod) - { - if (count($rMethod->getParameters()) === 0) { - return; - } - - $methodName = $rMethod->getName(); - - // @todo annotations here for alternate names? - - $def['parameters'][$methodName] = array(); - - foreach ($rMethod->getParameters() as $p) { - /** @var $p \ReflectionParameter */ - $actualParamName = $p->getName(); - - $fqName = $rClass->getName() . '::' . $rMethod->getName() . ':' . $p->getPosition(); - - $def['parameters'][$methodName][$fqName] = array(); - - // set the class name, if it exists - $def['parameters'][$methodName][$fqName][] = $actualParamName; - $def['parameters'][$methodName][$fqName][] = ($p->getClass() !== null) ? $p->getClass()->getName() : null; - $def['parameters'][$methodName][$fqName][] = !($optional = $p->isOptional() && $p->isDefaultValueAvailable()); - $def['parameters'][$methodName][$fqName][] = $optional ? $p->getDefaultValue() : null; - } - } -} diff --git a/library/Zend/Di/DefinitionList.php b/library/Zend/Di/DefinitionList.php deleted file mode 100755 index efe190e57..000000000 --- a/library/Zend/Di/DefinitionList.php +++ /dev/null @@ -1,257 +0,0 @@ -push($definition); - } - } - - /** - * Add definitions - * - * @param Definition\DefinitionInterface $definition - * @param bool $addToBackOfList - * @return void - */ - public function addDefinition(Definition\DefinitionInterface $definition, $addToBackOfList = true) - { - if ($addToBackOfList) { - $this->push($definition); - } else { - $this->unshift($definition); - } - } - - /** - * @param string $type - * @return Definition\DefinitionInterface[] - */ - public function getDefinitionsByType($type) - { - $definitions = array(); - foreach ($this as $definition) { - if ($definition instanceof $type) { - $definitions[] = $definition; - } - } - - return $definitions; - } - - /** - * Get definition by type - * - * @param string $type - * @return Definition\DefinitionInterface - */ - public function getDefinitionByType($type) - { - foreach ($this as $definition) { - if ($definition instanceof $type) { - return $definition; - } - } - - return false; - } - - /** - * @param string $class - * @return bool|Definition\DefinitionInterface - */ - public function getDefinitionForClass($class) - { - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class)) { - return $definition; - } - } - - return false; - } - - /** - * @param string $class - * @return bool|Definition\DefinitionInterface - */ - public function forClass($class) - { - return $this->getDefinitionForClass($class); - } - - /** - * {@inheritDoc} - */ - public function getClasses() - { - $classes = array(); - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - $classes = array_merge($classes, $definition->getClasses()); - } - - return $classes; - } - - /** - * {@inheritDoc} - */ - public function hasClass($class) - { - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class)) { - return true; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - public function getClassSupertypes($class) - { - $supertypes = array(); - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class)) { - $supertypes = array_merge($supertypes, $definition->getClassSupertypes($class)); - if ($definition instanceof Definition\PartialMarker) { - continue; - } - - return $supertypes; - } - } - return $supertypes; - } - - /** - * {@inheritDoc} - */ - public function getInstantiator($class) - { - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class)) { - $value = $definition->getInstantiator($class); - if ($value === null && $definition instanceof Definition\PartialMarker) { - continue; - } - - return $value; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - public function hasMethods($class) - { - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class)) { - if ($definition->hasMethods($class) === false && $definition instanceof Definition\PartialMarker) { - continue; - } - - return $definition->hasMethods($class); - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - public function hasMethod($class, $method) - { - if (!$this->hasMethods($class)) { - return false; - } - - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class) && $definition->hasMethod($class, $method)) { - return true; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - public function getMethods($class) - { - /** @var $definition Definition\DefinitionInterface */ - $methods = array(); - foreach ($this as $definition) { - if ($definition->hasClass($class)) { - if (!$definition instanceof Definition\PartialMarker) { - return array_merge($definition->getMethods($class), $methods); - } - - $methods = array_merge($definition->getMethods($class), $methods); - } - } - - return $methods; - } - - /** - * {@inheritDoc} - */ - public function hasMethodParameters($class, $method) - { - $methodParameters = $this->getMethodParameters($class, $method); - - return ($methodParameters !== array()); - } - - /** - * {@inheritDoc} - */ - public function getMethodParameters($class, $method) - { - /** @var $definition Definition\DefinitionInterface */ - foreach ($this as $definition) { - if ($definition->hasClass($class) && $definition->hasMethod($class, $method) && $definition->hasMethodParameters($class, $method)) { - return $definition->getMethodParameters($class, $method); - } - } - - return array(); - } -} diff --git a/library/Zend/Di/DependencyInjectionInterface.php b/library/Zend/Di/DependencyInjectionInterface.php deleted file mode 100755 index b82187613..000000000 --- a/library/Zend/Di/DependencyInjectionInterface.php +++ /dev/null @@ -1,25 +0,0 @@ -definitions = ($definitions) ?: new DefinitionList(new Definition\RuntimeDefinition()); - $this->instanceManager = ($instanceManager) ?: new InstanceManager(); - - if ($config) { - $this->configure($config); - } - } - - /** - * Provide a configuration object to configure this instance - * - * @param Config $config - * @return void - */ - public function configure(Config $config) - { - $config->configure($this); - } - - /** - * @param DefinitionList $definitions - * @return self - */ - public function setDefinitionList(DefinitionList $definitions) - { - $this->definitions = $definitions; - - return $this; - } - - /** - * @return DefinitionList - */ - public function definitions() - { - return $this->definitions; - } - - /** - * Set the instance manager - * - * @param InstanceManager $instanceManager - * @return Di - */ - public function setInstanceManager(InstanceManager $instanceManager) - { - $this->instanceManager = $instanceManager; - - return $this; - } - - /** - * - * @return InstanceManager - */ - public function instanceManager() - { - return $this->instanceManager; - } - - /** - * Utility method used to retrieve the class of a particular instance. This is here to allow extending classes to - * override how class names are resolved - * - * @internal this method is used by the ServiceLocator\DependencyInjectorProxy class to interact with instances - * and is a hack to be used internally until a major refactor does not split the `resolveMethodParameters`. Do not - * rely on its functionality. - * @param object $instance - * @return string - */ - protected function getClass($instance) - { - return get_class($instance); - } - - /** - * @param $name - * @param array $params - * @param string $method - * @return array - */ - protected function getCallParameters($name, array $params, $method = "__construct") - { - $im = $this->instanceManager; - $class = $im->hasAlias($name) ? $im->getClassFromAlias($name) : $name; - if ($this->definitions->hasClass($class)) { - $callParameters = array(); - if ($this->definitions->hasMethod($class, $method)) { - foreach ($this->definitions->getMethodParameters($class, $method) as $param) { - if (isset($params[$param[0]])) { - $callParameters[$param[0]] = $params[$param[0]]; - } - } - } - return $callParameters; - } - return $params; - } - - /** - * Lazy-load a class - * - * Attempts to load the class (or service alias) provided. If it has been - * loaded before, the previous instance will be returned (unless the service - * definition indicates shared instances should not be used). - * - * @param string $name Class name or service alias - * @param null|array $params Parameters to pass to the constructor - * @return object|null - */ - public function get($name, array $params = array()) - { - array_push($this->instanceContext, array('GET', $name, null)); - - $im = $this->instanceManager; - - $callParameters = $this->getCallParameters($name, $params); - if ($callParameters) { - $fastHash = $im->hasSharedInstanceWithParameters($name, $callParameters, true); - if ($fastHash) { - array_pop($this->instanceContext); - return $im->getSharedInstanceWithParameters(null, array(), $fastHash); - } - } - - if ($im->hasSharedInstance($name, $callParameters)) { - array_pop($this->instanceContext); - return $im->getSharedInstance($name, $callParameters); - } - - - $config = $im->getConfig($name); - $instance = $this->newInstance($name, $params, $config['shared']); - array_pop($this->instanceContext); - - return $instance; - } - - /** - * Retrieve a new instance of a class - * - * Forces retrieval of a discrete instance of the given class, using the - * constructor parameters provided. - * - * @param mixed $name Class name or service alias - * @param array $params Parameters to pass to the constructor - * @param bool $isShared - * @return object|null - * @throws Exception\ClassNotFoundException - * @throws Exception\RuntimeException - */ - public function newInstance($name, array $params = array(), $isShared = true) - { - // localize dependencies - $definitions = $this->definitions; - $instanceManager = $this->instanceManager(); - - if ($instanceManager->hasAlias($name)) { - $class = $instanceManager->getClassFromAlias($name); - $alias = $name; - } else { - $class = $name; - $alias = null; - } - - array_push($this->instanceContext, array('NEW', $class, $alias)); - - if (!$definitions->hasClass($class)) { - $aliasMsg = ($alias) ? '(specified by alias ' . $alias . ') ' : ''; - throw new Exception\ClassNotFoundException( - 'Class ' . $aliasMsg . $class . ' could not be located in provided definitions.' - ); - } - - $instantiator = $definitions->getInstantiator($class); - $injectionMethods = array(); - $injectionMethods[$class] = $definitions->getMethods($class); - - foreach ($definitions->getClassSupertypes($class) as $supertype) { - $injectionMethods[$supertype] = $definitions->getMethods($supertype); - } - - if ($instantiator === '__construct') { - $instance = $this->createInstanceViaConstructor($class, $params, $alias); - if (array_key_exists('__construct', $injectionMethods)) { - unset($injectionMethods['__construct']); - } - } elseif (is_callable($instantiator, false)) { - $instance = $this->createInstanceViaCallback($instantiator, $params, $alias); - } else { - if (is_array($instantiator)) { - $msg = sprintf( - 'Invalid instantiator: %s::%s() is not callable.', - isset($instantiator[0]) ? $instantiator[0] : 'NoClassGiven', - isset($instantiator[1]) ? $instantiator[1] : 'NoMethodGiven' - ); - } else { - $msg = sprintf( - 'Invalid instantiator of type "%s" for "%s".', - gettype($instantiator), - $name - ); - } - throw new Exception\RuntimeException($msg); - } - - if ($isShared) { - if ($callParameters = $this->getCallParameters($name, $params)) { - $this->instanceManager->addSharedInstanceWithParameters($instance, $name, $callParameters); - } else { - $this->instanceManager->addSharedInstance($instance, $name); - } - } - - $this->handleInjectDependencies($instance, $injectionMethods, $params, $class, $alias, $name); - - array_pop($this->instanceContext); - - return $instance; - } - - /** - * Inject dependencies - * - * @param object $instance - * @param array $params - * @return void - */ - public function injectDependencies($instance, array $params = array()) - { - $definitions = $this->definitions(); - $class = $this->getClass($instance); - $injectionMethods = array( - $class => ($definitions->hasClass($class)) ? $definitions->getMethods($class) : array() - ); - $parent = $class; - while ($parent = get_parent_class($parent)) { - if ($definitions->hasClass($parent)) { - $injectionMethods[$parent] = $definitions->getMethods($parent); - } - } - foreach (class_implements($class) as $interface) { - if ($definitions->hasClass($interface)) { - $injectionMethods[$interface] = $definitions->getMethods($interface); - } - } - $this->handleInjectDependencies($instance, $injectionMethods, $params, $class, null, null); - } - - /** - * @param object $instance - * @param array $injectionMethods - * @param array $params - * @param string|null $instanceClass - * @param string|null$instanceAlias - * @param string $requestedName - * @throws Exception\RuntimeException - */ - protected function handleInjectDependencies($instance, $injectionMethods, $params, $instanceClass, $instanceAlias, $requestedName) - { - // localize dependencies - $definitions = $this->definitions; - $instanceManager = $this->instanceManager(); - - $calledMethods = array('__construct' => true); - - if ($injectionMethods) { - foreach ($injectionMethods as $type => $typeInjectionMethods) { - foreach ($typeInjectionMethods as $typeInjectionMethod => $methodRequirementType) { - if (!isset($calledMethods[$typeInjectionMethod])) { - if ($this->resolveAndCallInjectionMethodForInstance($instance, $typeInjectionMethod, $params, $instanceAlias, $methodRequirementType, $type)) { - $calledMethods[$typeInjectionMethod] = true; - } - } - } - } - - if ($requestedName) { - $instanceConfig = $instanceManager->getConfig($requestedName); - - if ($instanceConfig['injections']) { - $objectsToInject = $methodsToCall = array(); - foreach ($instanceConfig['injections'] as $injectName => $injectValue) { - if (is_int($injectName) && is_string($injectValue)) { - $objectsToInject[] = $this->get($injectValue, $params); - } elseif (is_string($injectName) && is_array($injectValue)) { - if (is_string(key($injectValue))) { - $methodsToCall[] = array('method' => $injectName, 'args' => $injectValue); - } else { - foreach ($injectValue as $methodCallArgs) { - $methodsToCall[] = array('method' => $injectName, 'args' => $methodCallArgs); - } - } - } elseif (is_object($injectValue)) { - $objectsToInject[] = $injectValue; - } elseif (is_int($injectName) && is_array($injectValue)) { - throw new Exception\RuntimeException( - 'An injection was provided with a keyed index and an array of data, try using' - . ' the name of a particular method as a key for your injection data.' - ); - } - } - if ($objectsToInject) { - foreach ($objectsToInject as $objectToInject) { - $calledMethods = array('__construct' => true); - foreach ($injectionMethods as $type => $typeInjectionMethods) { - foreach ($typeInjectionMethods as $typeInjectionMethod => $methodRequirementType) { - if (!isset($calledMethods[$typeInjectionMethod])) { - $methodParams = $definitions->getMethodParameters($type, $typeInjectionMethod); - if ($methodParams) { - foreach ($methodParams as $methodParam) { - $objectToInjectClass = $this->getClass($objectToInject); - if ($objectToInjectClass == $methodParam[1] || self::isSubclassOf($objectToInjectClass, $methodParam[1])) { - if ($this->resolveAndCallInjectionMethodForInstance($instance, $typeInjectionMethod, array($methodParam[0] => $objectToInject), $instanceAlias, self::METHOD_IS_REQUIRED, $type)) { - $calledMethods[$typeInjectionMethod] = true; - } - continue 3; - } - } - } - } - } - } - } - } - if ($methodsToCall) { - foreach ($methodsToCall as $methodInfo) { - $this->resolveAndCallInjectionMethodForInstance($instance, $methodInfo['method'], $methodInfo['args'], $instanceAlias, self::METHOD_IS_REQUIRED, $instanceClass); - } - } - } - } - } - } - - /** - * Retrieve a class instance based on class name - * - * Any parameters provided will be used as constructor arguments. If any - * given parameter is a DependencyReference object, it will be fetched - * from the container so that the instance may be injected. - * - * @param string $class - * @param array $params - * @param string|null $alias - * @return object - */ - protected function createInstanceViaConstructor($class, $params, $alias = null) - { - $callParameters = array(); - if ($this->definitions->hasMethod($class, '__construct')) { - $callParameters = $this->resolveMethodParameters($class, '__construct', $params, $alias, self::METHOD_IS_CONSTRUCTOR, true); - } - - if (!class_exists($class)) { - if (interface_exists($class)) { - throw new Exception\ClassNotFoundException(sprintf( - 'Cannot instantiate interface "%s"', - $class - )); - } - throw new Exception\ClassNotFoundException(sprintf( - 'Class "%s" does not exist; cannot instantiate', - $class - )); - } - - // Hack to avoid Reflection in most common use cases - switch (count($callParameters)) { - case 0: - return new $class(); - case 1: - return new $class($callParameters[0]); - case 2: - return new $class($callParameters[0], $callParameters[1]); - case 3: - return new $class($callParameters[0], $callParameters[1], $callParameters[2]); - default: - $r = new \ReflectionClass($class); - - return $r->newInstanceArgs($callParameters); - } - } - - /** - * Get an object instance from the defined callback - * - * @param callable $callback - * @param array $params - * @param string $alias - * @return object - * @throws Exception\InvalidCallbackException - * @throws Exception\RuntimeException - */ - protected function createInstanceViaCallback($callback, $params, $alias) - { - if (!is_callable($callback)) { - throw new Exception\InvalidCallbackException('An invalid constructor callback was provided'); - } - - if (is_array($callback)) { - $class = (is_object($callback[0])) ? $this->getClass($callback[0]) : $callback[0]; - $method = $callback[1]; - } elseif (is_string($callback) && strpos($callback, '::') !== false) { - list($class, $method) = explode('::', $callback, 2); - } else { - throw new Exception\RuntimeException('Invalid callback type provided to ' . __METHOD__); - } - - $callParameters = array(); - if ($this->definitions->hasMethod($class, $method)) { - $callParameters = $this->resolveMethodParameters($class, $method, $params, $alias, self::METHOD_IS_INSTANTIATOR, true); - } - - return call_user_func_array($callback, $callParameters); - } - - /** - * This parameter will handle any injection methods and resolution of - * dependencies for such methods - * - * @param object $instance - * @param string $method - * @param array $params - * @param string $alias - * @param bool $methodRequirementType - * @param string|null $methodClass - * @return bool - */ - protected function resolveAndCallInjectionMethodForInstance($instance, $method, $params, $alias, $methodRequirementType, $methodClass = null) - { - $methodClass = ($methodClass) ?: $this->getClass($instance); - $callParameters = $this->resolveMethodParameters($methodClass, $method, $params, $alias, $methodRequirementType); - if ($callParameters == false) { - return false; - } - if ($callParameters !== array_fill(0, count($callParameters), null)) { - call_user_func_array(array($instance, $method), $callParameters); - - return true; - } - - return false; - } - - /** - * Resolve parameters referencing other services - * - * @param string $class - * @param string $method - * @param array $callTimeUserParams - * @param string $alias - * @param int|bool $methodRequirementType - * @param bool $isInstantiator - * @throws Exception\MissingPropertyException - * @throws Exception\CircularDependencyException - * @return array - */ - protected function resolveMethodParameters($class, $method, array $callTimeUserParams, $alias, $methodRequirementType, $isInstantiator = false) - { - //for BC - if (is_bool($methodRequirementType)) { - if ($isInstantiator) { - $methodRequirementType = Di::METHOD_IS_INSTANTIATOR; - } elseif ($methodRequirementType) { - $methodRequirementType = Di::METHOD_IS_REQUIRED; - } else { - $methodRequirementType = Di::METHOD_IS_OPTIONAL; - } - } - // parameters for this method, in proper order, to be returned - $resolvedParams = array(); - - // parameter requirements from the definition - $injectionMethodParameters = $this->definitions->getMethodParameters($class, $method); - - // computed parameters array - $computedParams = array( - 'value' => array(), - 'retrieval' => array(), - 'optional' => array() - ); - - // retrieve instance configurations for all contexts - $iConfig = array(); - $aliases = $this->instanceManager->getAliases(); - - // for the alias in the dependency tree - if ($alias && $this->instanceManager->hasConfig($alias)) { - $iConfig['thisAlias'] = $this->instanceManager->getConfig($alias); - } - - // for the current class in the dependency tree - if ($this->instanceManager->hasConfig($class)) { - $iConfig['thisClass'] = $this->instanceManager->getConfig($class); - } - - // for the parent class, provided we are deeper than one node - if (isset($this->instanceContext[0])) { - list($requestedClass, $requestedAlias) = ($this->instanceContext[0][0] == 'NEW') - ? array($this->instanceContext[0][1], $this->instanceContext[0][2]) - : array($this->instanceContext[1][1], $this->instanceContext[1][2]); - } else { - $requestedClass = $requestedAlias = null; - } - - if ($requestedClass != $class && $this->instanceManager->hasConfig($requestedClass)) { - $iConfig['requestedClass'] = $this->instanceManager->getConfig($requestedClass); - - if (array_key_exists('parameters', $iConfig['requestedClass'])) { - $newParameters = array(); - - foreach ($iConfig['requestedClass']['parameters'] as $name=>$parameter) { - $newParameters[$requestedClass.'::'.$method.'::'.$name] = $parameter; - } - - $iConfig['requestedClass']['parameters'] = $newParameters; - } - - if ($requestedAlias) { - $iConfig['requestedAlias'] = $this->instanceManager->getConfig($requestedAlias); - } - } - - // This is a 2 pass system for resolving parameters - // first pass will find the sources, the second pass will order them and resolve lookups if they exist - // MOST methods will only have a single parameters to resolve, so this should be fast - - foreach ($injectionMethodParameters as $fqParamPos => $info) { - list($name, $type, $isRequired) = $info; - - $fqParamName = substr_replace($fqParamPos, ':' . $info[0], strrpos($fqParamPos, ':')); - - // PRIORITY 1 - consult user provided parameters - if (isset($callTimeUserParams[$fqParamPos]) || isset($callTimeUserParams[$name])) { - if (isset($callTimeUserParams[$fqParamPos])) { - $callTimeCurValue =& $callTimeUserParams[$fqParamPos]; - } elseif (isset($callTimeUserParams[$fqParamName])) { - $callTimeCurValue =& $callTimeUserParams[$fqParamName]; - } else { - $callTimeCurValue =& $callTimeUserParams[$name]; - } - - if ($type !== false && is_string($callTimeCurValue)) { - if ($this->instanceManager->hasAlias($callTimeCurValue)) { - // was an alias provided? - $computedParams['retrieval'][$fqParamPos] = array( - $callTimeUserParams[$name], - $this->instanceManager->getClassFromAlias($callTimeCurValue) - ); - } elseif ($this->definitions->hasClass($callTimeUserParams[$name])) { - // was a known class provided? - $computedParams['retrieval'][$fqParamPos] = array( - $callTimeCurValue, - $callTimeCurValue - ); - } else { - // must be a value - $computedParams['value'][$fqParamPos] = $callTimeCurValue; - } - } else { - // int, float, null, object, etc - $computedParams['value'][$fqParamPos] = $callTimeCurValue; - } - unset($callTimeCurValue); - continue; - } - - // PRIORITY 2 -specific instance configuration (thisAlias) - this alias - // PRIORITY 3 -THEN specific instance configuration (thisClass) - this class - // PRIORITY 4 -THEN specific instance configuration (requestedAlias) - requested alias - // PRIORITY 5 -THEN specific instance configuration (requestedClass) - requested class - - foreach (array('thisAlias', 'thisClass', 'requestedAlias', 'requestedClass') as $thisIndex) { - // check the provided parameters config - if (isset($iConfig[$thisIndex]['parameters'][$fqParamPos]) - || isset($iConfig[$thisIndex]['parameters'][$fqParamName]) - || isset($iConfig[$thisIndex]['parameters'][$name])) { - if (isset($iConfig[$thisIndex]['parameters'][$fqParamPos])) { - $iConfigCurValue =& $iConfig[$thisIndex]['parameters'][$fqParamPos]; - } elseif (isset($iConfig[$thisIndex]['parameters'][$fqParamName])) { - $iConfigCurValue =& $iConfig[$thisIndex]['parameters'][$fqParamName]; - } else { - $iConfigCurValue =& $iConfig[$thisIndex]['parameters'][$name]; - } - - if ($type === false && is_string($iConfigCurValue)) { - $computedParams['value'][$fqParamPos] = $iConfigCurValue; - } elseif (is_string($iConfigCurValue) - && isset($aliases[$iConfigCurValue])) { - $computedParams['retrieval'][$fqParamPos] = array( - $iConfig[$thisIndex]['parameters'][$name], - $this->instanceManager->getClassFromAlias($iConfigCurValue) - ); - } elseif (is_string($iConfigCurValue) - && $this->definitions->hasClass($iConfigCurValue)) { - $computedParams['retrieval'][$fqParamPos] = array( - $iConfigCurValue, - $iConfigCurValue - ); - } elseif (is_object($iConfigCurValue) - && $iConfigCurValue instanceof Closure - && $type !== 'Closure') { - /* @var $iConfigCurValue Closure */ - $computedParams['value'][$fqParamPos] = $iConfigCurValue(); - } else { - $computedParams['value'][$fqParamPos] = $iConfigCurValue; - } - unset($iConfigCurValue); - continue 2; - } - } - - // PRIORITY 6 - globally preferred implementations - - // next consult alias level preferred instances - // RESOLVE_EAGER wants to inject the cross-cutting concerns. - // If you want to retrieve an instance from TypePreferences, - // use AwareInterface or specify the method requirement option METHOD_IS_EAGER at ClassDefinition - if ($methodRequirementType & self::RESOLVE_EAGER) { - if ($alias && $this->instanceManager->hasTypePreferences($alias)) { - $pInstances = $this->instanceManager->getTypePreferences($alias); - foreach ($pInstances as $pInstance) { - if (is_object($pInstance)) { - $computedParams['value'][$fqParamPos] = $pInstance; - continue 2; - } - $pInstanceClass = ($this->instanceManager->hasAlias($pInstance)) ? - $this->instanceManager->getClassFromAlias($pInstance) : $pInstance; - if ($pInstanceClass === $type || self::isSubclassOf($pInstanceClass, $type)) { - $computedParams['retrieval'][$fqParamPos] = array($pInstance, $pInstanceClass); - continue 2; - } - } - } - - // next consult class level preferred instances - if ($type && $this->instanceManager->hasTypePreferences($type)) { - $pInstances = $this->instanceManager->getTypePreferences($type); - foreach ($pInstances as $pInstance) { - if (is_object($pInstance)) { - $computedParams['value'][$fqParamPos] = $pInstance; - continue 2; - } - $pInstanceClass = ($this->instanceManager->hasAlias($pInstance)) ? - $this->instanceManager->getClassFromAlias($pInstance) : $pInstance; - if ($pInstanceClass === $type || self::isSubclassOf($pInstanceClass, $type)) { - $computedParams['retrieval'][$fqParamPos] = array($pInstance, $pInstanceClass); - continue 2; - } - } - } - } - if (!$isRequired) { - $computedParams['optional'][$fqParamPos] = true; - } - - if ($type && $isRequired && ($methodRequirementType & self::RESOLVE_EAGER)) { - $computedParams['retrieval'][$fqParamPos] = array($type, $type); - } - } - - $index = 0; - foreach ($injectionMethodParameters as $fqParamPos => $value) { - $name = $value[0]; - - if (isset($computedParams['value'][$fqParamPos])) { - // if there is a value supplied, use it - $resolvedParams[$index] = $computedParams['value'][$fqParamPos]; - } elseif (isset($computedParams['retrieval'][$fqParamPos])) { - // detect circular dependencies! (they can only happen in instantiators) - if ($isInstantiator && in_array($computedParams['retrieval'][$fqParamPos][1], $this->currentDependencies) - && (!isset($alias) || in_array($computedParams['retrieval'][$fqParamPos][0], $this->currentAliasDependenencies)) - ) { - $msg = "Circular dependency detected: $class depends on {$value[1]} and viceversa"; - if (isset($alias)) { - $msg .= " (Aliased as $alias)"; - } - throw new Exception\CircularDependencyException($msg); - } - - array_push($this->currentDependencies, $class); - if (isset($alias)) { - array_push($this->currentAliasDependenencies, $alias); - } - - $dConfig = $this->instanceManager->getConfig($computedParams['retrieval'][$fqParamPos][0]); - - try { - if ($dConfig['shared'] === false) { - $resolvedParams[$index] = $this->newInstance($computedParams['retrieval'][$fqParamPos][0], $callTimeUserParams, false); - } else { - $resolvedParams[$index] = $this->get($computedParams['retrieval'][$fqParamPos][0], $callTimeUserParams); - } - } catch (DiRuntimeException $e) { - if ($methodRequirementType & self::RESOLVE_STRICT) { - //finally ( be aware to do at the end of flow) - array_pop($this->currentDependencies); - if (isset($alias)) { - array_pop($this->currentAliasDependenencies); - } - // if this item was marked strict, - // plus it cannot be resolve, and no value exist, bail out - throw new Exception\MissingPropertyException(sprintf( - 'Missing %s for parameter ' . $name . ' for ' . $class . '::' . $method, - (($value[0] === null) ? 'value' : 'instance/object' ) - ), - $e->getCode(), - $e); - } else { - //finally ( be aware to do at the end of flow) - array_pop($this->currentDependencies); - if (isset($alias)) { - array_pop($this->currentAliasDependenencies); - } - return false; - } - } catch (ServiceManagerException $e) { - // Zend\ServiceManager\Exception\ServiceNotCreatedException - if ($methodRequirementType & self::RESOLVE_STRICT) { - //finally ( be aware to do at the end of flow) - array_pop($this->currentDependencies); - if (isset($alias)) { - array_pop($this->currentAliasDependenencies); - } - // if this item was marked strict, - // plus it cannot be resolve, and no value exist, bail out - throw new Exception\MissingPropertyException(sprintf( - 'Missing %s for parameter ' . $name . ' for ' . $class . '::' . $method, - (($value[0] === null) ? 'value' : 'instance/object' ) - ), - $e->getCode(), - $e); - } else { - //finally ( be aware to do at the end of flow) - array_pop($this->currentDependencies); - if (isset($alias)) { - array_pop($this->currentAliasDependenencies); - } - return false; - } - } - array_pop($this->currentDependencies); - if (isset($alias)) { - array_pop($this->currentAliasDependenencies); - } - } elseif (!array_key_exists($fqParamPos, $computedParams['optional'])) { - if ($methodRequirementType & self::RESOLVE_STRICT) { - // if this item was not marked as optional, - // plus it cannot be resolve, and no value exist, bail out - throw new Exception\MissingPropertyException(sprintf( - 'Missing %s for parameter ' . $name . ' for ' . $class . '::' . $method, - (($value[0] === null) ? 'value' : 'instance/object' ) - )); - } else { - return false; - } - } else { - $resolvedParams[$index] = $value[3]; - } - - $index++; - } - - return $resolvedParams; // return ordered list of parameters - } - - /** - * Checks if the object has this class as one of its parents - * - * @see https://bugs.php.net/bug.php?id=53727 - * @see https://github.com/zendframework/zf2/pull/1807 - * - * @param string $className - * @param $type - * @return bool - */ - protected static function isSubclassOf($className, $type) - { - if (is_subclass_of($className, $type)) { - return true; - } - if (PHP_VERSION_ID >= 50307) { - return false; - } - if (!interface_exists($type)) { - return false; - } - $r = new ReflectionClass($className); - - return $r->implementsInterface($type); - } -} diff --git a/library/Zend/Di/Display/Console.php b/library/Zend/Di/Display/Console.php deleted file mode 100755 index 31b861e63..000000000 --- a/library/Zend/Di/Display/Console.php +++ /dev/null @@ -1,176 +0,0 @@ -addRuntimeClasses($runtimeClasses); - $console->render($di); - } - - /** - * Constructor - * - * @param null|Di $di - */ - public function __construct(Di $di = null) - { - $this->di = ($di) ?: new Di; - } - - /** - * @param string[] $runtimeClasses - */ - public function addRuntimeClasses(array $runtimeClasses) - { - foreach ($runtimeClasses as $runtimeClass) { - $this->addRuntimeClass($runtimeClass); - } - } - - /** - * @param string $runtimeClass - */ - public function addRuntimeClass($runtimeClass) - { - $this->runtimeClasses[] = $runtimeClass; - } - - public function render() - { - $knownClasses = array(); - - echo 'Definitions' . PHP_EOL . PHP_EOL; - - foreach ($this->di->definitions() as $definition) { - $this->renderDefinition($definition); - foreach ($definition->getClasses() as $class) { - $knownClasses[] = $class; - $this->renderClassDefinition($definition, $class); - } - if (count($definition->getClasses()) == 0) { - echo PHP_EOL .' No Classes Found' . PHP_EOL . PHP_EOL; - } - } - - if ($this->runtimeClasses) { - echo ' Runtime classes:' . PHP_EOL; - } - - $unknownRuntimeClasses = array_diff($this->runtimeClasses, $knownClasses); - foreach ($unknownRuntimeClasses as $runtimeClass) { - $definition = $this->di->definitions()->getDefinitionForClass($runtimeClass); - $this->renderClassDefinition($definition, $runtimeClass); - } - - echo PHP_EOL . 'Instance Configuration Info:' . PHP_EOL; - - echo PHP_EOL . ' Aliases:' . PHP_EOL; - - $configuredTypes = array(); - foreach ($this->di->instanceManager()->getAliases() as $alias => $class) { - echo ' ' . $alias . ' [type: ' . $class . ']' . PHP_EOL; - $configuredTypes[] = $alias; - } - - echo PHP_EOL . ' Classes:' . PHP_EOL; - - foreach ($this->di->instanceManager()->getClasses() as $class) { - echo ' ' . $class . PHP_EOL; - $configuredTypes[] = $class; - } - - echo PHP_EOL . ' Configurations:' . PHP_EOL; - - foreach ($configuredTypes as $type) { - $info = $this->di->instanceManager()->getConfig($type); - echo ' ' . $type . PHP_EOL; - - if ($info['parameters']) { - echo ' parameters:' . PHP_EOL; - foreach ($info['parameters'] as $param => $value) { - echo ' ' . $param . ' = ' . $value . PHP_EOL; - } - } - - if ($info['injections']) { - echo ' injections:' . PHP_EOL; - foreach ($info['injections'] as $injection => $value) { - var_dump($injection, $value); - } - } - } - } - - /** - * @param object $definition - */ - protected function renderDefinition($definition) - { - echo ' Definition Type: ' . get_class($definition) . PHP_EOL; - $r = new \ReflectionClass($definition); - foreach ($r->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED) as $property) { - $property->setAccessible(true); - echo ' internal property: ' . $property->getName(); - $value = $property->getValue($definition); - if (is_object($value)) { - echo ' instance of ' . get_class($value); - } else { - echo ' = ' . $value; - } - echo PHP_EOL; - } - } - - /** - * @param \Zend\Di\Definition\DefinitionInterface $definition - * @param string $class - */ - protected function renderClassDefinition($definition, $class) - { - echo PHP_EOL . ' Parameters For Class: ' . $class . PHP_EOL; - foreach ($definition->getMethods($class) as $methodName => $methodIsRequired) { - foreach ($definition->getMethodParameters($class, $methodName) as $fqName => $pData) { - echo ' ' . $pData[0] . ' [type: '; - echo ($pData[1]) ? $pData[1] : 'scalar'; - echo ($pData[2] === true && $methodIsRequired) ? ', required' : ', not required'; - echo ', injection-method: ' . $methodName; - echo ' fq-name: ' . $fqName; - echo ']' . PHP_EOL; - } - } - echo PHP_EOL; - } -} diff --git a/library/Zend/Di/Exception/CircularDependencyException.php b/library/Zend/Di/Exception/CircularDependencyException.php deleted file mode 100755 index 8cb9eae3f..000000000 --- a/library/Zend/Di/Exception/CircularDependencyException.php +++ /dev/null @@ -1,16 +0,0 @@ - array(), 'hashLong' => array()); - - /** - * Array of class aliases - * @var array key: alias, value: class - */ - protected $aliases = array(); - - /** - * The template to use for housing configuration information - * @var array - */ - protected $configurationTemplate = array( - /** - * alias|class => alias|class - * interface|abstract => alias|class|object - * name => value - */ - 'parameters' => array(), - /** - * injection type => array of ordered method params - */ - 'injections' => array(), - /** - * alias|class => bool - */ - 'shared' => true - ); - - /** - * An array of instance configuration data - * @var array - */ - protected $configurations = array(); - - /** - * An array of globally preferred implementations for interfaces/abstracts - * @var array - */ - protected $typePreferences = array(); - - /** - * Does this instance manager have this shared instance - * @param string $classOrAlias - * @return bool - */ - public function hasSharedInstance($classOrAlias) - { - return isset($this->sharedInstances[$classOrAlias]); - } - - /** - * getSharedInstance() - */ - public function getSharedInstance($classOrAlias) - { - return $this->sharedInstances[$classOrAlias]; - } - - /** - * Add shared instance - * - * @param object $instance - * @param string $classOrAlias - * @throws Exception\InvalidArgumentException - */ - public function addSharedInstance($instance, $classOrAlias) - { - if (!is_object($instance)) { - throw new Exception\InvalidArgumentException('This method requires an object to be shared. Class or Alias given: ' . $classOrAlias); - } - - $this->sharedInstances[$classOrAlias] = $instance; - } - - /** - * hasSharedInstanceWithParameters() - * - * @param string $classOrAlias - * @param array $params - * @param bool $returnFastHashLookupKey - * @return bool|string - */ - public function hasSharedInstanceWithParameters($classOrAlias, array $params, $returnFastHashLookupKey = false) - { - ksort($params); - $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); - if (isset($this->sharedInstancesWithParams['hashShort'][$hashKey])) { - $hashValue = $this->createHashForValues($classOrAlias, $params); - if (isset($this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue])) { - return ($returnFastHashLookupKey) ? $hashKey . '/' . $hashValue : true; - } - } - - return false; - } - - /** - * addSharedInstanceWithParameters() - * - * @param object $instance - * @param string $classOrAlias - * @param array $params - * @return void - */ - public function addSharedInstanceWithParameters($instance, $classOrAlias, array $params) - { - ksort($params); - $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); - $hashValue = $this->createHashForValues($classOrAlias, $params); - - if (!isset($this->sharedInstancesWithParams[$hashKey]) - || !is_array($this->sharedInstancesWithParams[$hashKey])) { - $this->sharedInstancesWithParams[$hashKey] = array(); - } - - $this->sharedInstancesWithParams['hashShort'][$hashKey] = true; - $this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue] = $instance; - } - - /** - * Retrieves an instance by its name and the parameters stored at its instantiation - * - * @param string $classOrAlias - * @param array $params - * @param bool|null $fastHashFromHasLookup - * @return object|bool false if no instance was found - */ - public function getSharedInstanceWithParameters($classOrAlias, array $params, $fastHashFromHasLookup = null) - { - if ($fastHashFromHasLookup) { - return $this->sharedInstancesWithParams['hashLong'][$fastHashFromHasLookup]; - } - - ksort($params); - $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); - if (isset($this->sharedInstancesWithParams['hashShort'][$hashKey])) { - $hashValue = $this->createHashForValues($classOrAlias, $params); - if (isset($this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue])) { - return $this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue]; - } - } - - return false; - } - - /** - * Check for an alias - * - * @param string $alias - * @return bool - */ - public function hasAlias($alias) - { - return (isset($this->aliases[$alias])); - } - - /** - * Get aliases - * - * @return array - */ - public function getAliases() - { - return $this->aliases; - } - - /** - * getClassFromAlias() - * - * @param string - * @return string|bool - * @throws Exception\RuntimeException - */ - public function getClassFromAlias($alias) - { - if (!isset($this->aliases[$alias])) { - return false; - } - $r = 0; - while (isset($this->aliases[$alias])) { - $alias = $this->aliases[$alias]; - $r++; - if ($r > 100) { - throw new Exception\RuntimeException( - sprintf('Possible infinite recursion in DI alias! Max recursion of 100 levels reached at alias "%s".', $alias) - ); - } - } - - return $alias; - } - - /** - * @param string $alias - * @return string|bool - * @throws Exception\RuntimeException - */ - protected function getBaseAlias($alias) - { - if (!$this->hasAlias($alias)) { - return false; - } - $lastAlias = false; - $r = 0; - while (isset($this->aliases[$alias])) { - $lastAlias = $alias; - $alias = $this->aliases[$alias]; - $r++; - if ($r > 100) { - throw new Exception\RuntimeException( - sprintf('Possible infinite recursion in DI alias! Max recursion of 100 levels reached at alias "%s".', $alias) - ); - } - } - - return $lastAlias; - } - - /** - * Add alias - * - * @throws Exception\InvalidArgumentException - * @param string $alias - * @param string $class - * @param array $parameters - * @return void - */ - public function addAlias($alias, $class, array $parameters = array()) - { - if (!preg_match('#^[a-zA-Z0-9-_]+$#', $alias)) { - throw new Exception\InvalidArgumentException( - 'Aliases must be alphanumeric and can contain dashes and underscores only.' - ); - } - $this->aliases[$alias] = $class; - if ($parameters) { - $this->setParameters($alias, $parameters); - } - } - - /** - * Check for configuration - * - * @param string $aliasOrClass - * @return bool - */ - public function hasConfig($aliasOrClass) - { - $key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass; - if (!isset($this->configurations[$key])) { - return false; - } - if ($this->configurations[$key] === $this->configurationTemplate) { - return false; - } - - return true; - } - - /** - * Sets configuration for a single alias/class - * - * @param string $aliasOrClass - * @param array $configuration - * @param bool $append - */ - public function setConfig($aliasOrClass, array $configuration, $append = false) - { - $key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass; - if (!isset($this->configurations[$key]) || !$append) { - $this->configurations[$key] = $this->configurationTemplate; - } - // Ignore anything but 'parameters' and 'injections' - $configuration = array( - 'parameters' => isset($configuration['parameters']) ? $configuration['parameters'] : array(), - 'injections' => isset($configuration['injections']) ? $configuration['injections'] : array(), - 'shared' => isset($configuration['shared']) ? $configuration['shared'] : true - ); - $this->configurations[$key] = array_replace_recursive($this->configurations[$key], $configuration); - } - - /** - * Get classes - * - * @return array - */ - public function getClasses() - { - $classes = array(); - foreach ($this->configurations as $name => $data) { - if (strpos($name, 'alias') === 0) { - continue; - } - $classes[] = $name; - } - - return $classes; - } - - /** - * @param string $aliasOrClass - * @return array - */ - public function getConfig($aliasOrClass) - { - $key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass; - if (isset($this->configurations[$key])) { - return $this->configurations[$key]; - } - - return $this->configurationTemplate; - } - - /** - * setParameters() is a convenience method for: - * setConfig($type, array('parameters' => array(...)), true); - * - * @param string $aliasOrClass Alias or Class - * @param array $parameters Multi-dim array of parameters and their values - * @return void - */ - public function setParameters($aliasOrClass, array $parameters) - { - $this->setConfig($aliasOrClass, array('parameters' => $parameters), true); - } - - /** - * setInjections() is a convenience method for: - * setConfig($type, array('injections' => array(...)), true); - * - * @param string $aliasOrClass Alias or Class - * @param array $injections Multi-dim array of methods and their parameters - * @return void - */ - public function setInjections($aliasOrClass, array $injections) - { - $this->setConfig($aliasOrClass, array('injections' => $injections), true); - } - - /** - * Set shared - * - * @param string $aliasOrClass - * @param bool $isShared - * @return void - */ - public function setShared($aliasOrClass, $isShared) - { - $this->setConfig($aliasOrClass, array('shared' => (bool) $isShared), true); - } - - /** - * Check for type preferences - * - * @param string $interfaceOrAbstract - * @return bool - */ - public function hasTypePreferences($interfaceOrAbstract) - { - $key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract; - - return (isset($this->typePreferences[$key]) && $this->typePreferences[$key]); - } - - /** - * Set type preference - * - * @param string $interfaceOrAbstract - * @param array $preferredImplementations - * @return InstanceManager - */ - public function setTypePreference($interfaceOrAbstract, array $preferredImplementations) - { - $key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract; - foreach ($preferredImplementations as $preferredImplementation) { - $this->addTypePreference($key, $preferredImplementation); - } - - return $this; - } - - /** - * Get type preferences - * - * @param string $interfaceOrAbstract - * @return array - */ - public function getTypePreferences($interfaceOrAbstract) - { - $key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract; - if (isset($this->typePreferences[$key])) { - return $this->typePreferences[$key]; - } - - return array(); - } - - /** - * Unset type preferences - * - * @param string $interfaceOrAbstract - * @return void - */ - public function unsetTypePreferences($interfaceOrAbstract) - { - $key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract; - unset($this->typePreferences[$key]); - } - - /** - * Adds a type preference. A type preference is a redirection to a preferred alias or type when an abstract type - * $interfaceOrAbstract is requested - * - * @param string $interfaceOrAbstract - * @param string $preferredImplementation - * @return self - */ - public function addTypePreference($interfaceOrAbstract, $preferredImplementation) - { - $key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract; - if (!isset($this->typePreferences[$key])) { - $this->typePreferences[$key] = array(); - } - $this->typePreferences[$key][] = $preferredImplementation; - - return $this; - } - - /** - * Removes a previously set type preference - * - * @param string $interfaceOrAbstract - * @param string $preferredType - * @return bool|self - */ - public function removeTypePreference($interfaceOrAbstract, $preferredType) - { - $key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract; - if (!isset($this->typePreferences[$key]) || !in_array($preferredType, $this->typePreferences[$key])) { - return false; - } - unset($this->typePreferences[$key][array_search($key, $this->typePreferences)]); - - return $this; - } - - /** - * @param string $classOrAlias - * @param string[] $paramKeys - * @return string - */ - protected function createHashForKeys($classOrAlias, $paramKeys) - { - return $classOrAlias . ':' . implode('|', $paramKeys); - } - - /** - * @param string $classOrAlias - * @param array $paramValues - * @return string - */ - protected function createHashForValues($classOrAlias, $paramValues) - { - $hashValue = ''; - foreach ($paramValues as $param) { - switch (gettype($param)) { - case 'object': - $hashValue .= spl_object_hash($param) . '|'; - break; - case 'integer': - case 'string': - case 'boolean': - case 'NULL': - case 'double': - $hashValue .= $param . '|'; - break; - case 'array': - $hashValue .= 'Array|'; - break; - case 'resource': - $hashValue .= 'resource|'; - break; - } - } - - return $hashValue; - } -} diff --git a/library/Zend/Di/LocatorInterface.php b/library/Zend/Di/LocatorInterface.php deleted file mode 100755 index 88a12f6cc..000000000 --- a/library/Zend/Di/LocatorInterface.php +++ /dev/null @@ -1,22 +0,0 @@ - - * protected $map = array('foo' => 'getFoo'); - * - * - * When encountered, the return value of that method will be used. - * - * Methods mapped in this way may expect a single, array argument, the - * $params passed to {@link get()}, if any. - * - * @var array - */ - protected $map = array(); - - /** - * Registered services and cached values - * - * @var array - */ - protected $services = array(); - - /** - * {@inheritDoc} - */ - public function set($name, $service) - { - $this->services[$name] = $service; - - return $this; - } - - /** - * Retrieve a registered service - * - * Tests first if a value is registered for the service, and, if so, - * returns it. - * - * If the value returned is a non-object callback or closure, the return - * value is retrieved, stored, and returned. Parameters passed to the method - * are passed to the callback, but only on the first retrieval. - * - * If the service requested matches a method in the method map, the return - * value of that method is returned. Parameters are passed to the matching - * method. - * - * @param string $name - * @param array $params - * @return mixed - */ - public function get($name, array $params = array()) - { - if (!isset($this->services[$name])) { - if (!isset($this->map[$name])) { - return null; - } - $method = $this->map[$name]; - - return $this->$method($params); - } - - $service = $this->services[$name]; - if ($service instanceof Closure - || (!is_object($service) && is_callable($service)) - ) { - $this->services[$name] = $service = call_user_func_array($service, $params); - } - - return $service; - } -} diff --git a/library/Zend/Di/ServiceLocator/DependencyInjectorProxy.php b/library/Zend/Di/ServiceLocator/DependencyInjectorProxy.php deleted file mode 100755 index be0c3cb1d..000000000 --- a/library/Zend/Di/ServiceLocator/DependencyInjectorProxy.php +++ /dev/null @@ -1,168 +0,0 @@ -di = $di; - $this->definitions = $di->definitions(); - $this->instanceManager = $di->instanceManager(); - } - - /** - * {@inheritDoc} - * @return GeneratorInstance - */ - public function get($name, array $params = array()) - { - return parent::get($name, $params); - } - - /** - * {@inheritDoc} - * @return GeneratorInstance - */ - public function newInstance($name, array $params = array(), $isShared = true) - { - $instance = parent::newInstance($name, $params, $isShared); - - if ($instance instanceof GeneratorInstance) { - /* @var $instance GeneratorInstance */ - $instance->setShared($isShared); - - // When a callback is used, we don't know instance the class name. - // That's why we assume $name as the instance alias - if (null === $instance->getName()) { - $instance->setAlias($name); - } - } - - return $instance; - } - - /** - * {@inheritDoc} - * @return GeneratorInstance - */ - public function createInstanceViaConstructor($class, $params, $alias = null) - { - $callParameters = array(); - - if ($this->di->definitions->hasMethod($class, '__construct') - && (count($this->di->definitions->getMethodParameters($class, '__construct')) > 0) - ) { - $callParameters = $this->resolveMethodParameters($class, '__construct', $params, $alias, true, true); - $callParameters = $callParameters ?: array(); - } - - return new GeneratorInstance($class, $alias, '__construct', $callParameters); - } - - /** - * {@inheritDoc} - * @throws \Zend\Di\Exception\InvalidCallbackException - * @return GeneratorInstance - */ - public function createInstanceViaCallback($callback, $params, $alias) - { - if (is_string($callback)) { - $callback = explode('::', $callback); - } - - if (!is_callable($callback)) { - throw new Exception\InvalidCallbackException('An invalid constructor callback was provided'); - } - - if (!is_array($callback) || is_object($callback[0])) { - throw new Exception\InvalidCallbackException( - 'For purposes of service locator generation, constructor callbacks must refer to static methods only' - ); - } - - $class = $callback[0]; - $method = $callback[1]; - - $callParameters = array(); - if ($this->di->definitions->hasMethod($class, $method)) { - $callParameters = $this->resolveMethodParameters($class, $method, $params, $alias, true, true); - } - - $callParameters = $callParameters ?: array(); - - return new GeneratorInstance(null, $alias, $callback, $callParameters); - } - - /** - * {@inheritDoc} - */ - public function handleInjectionMethodForObject($class, $method, $params, $alias, $isRequired) - { - return array( - 'method' => $method, - 'params' => $this->resolveMethodParameters($class, $method, $params, $alias, $isRequired), - ); - } - - /** - * {@inheritDoc} - */ - protected function resolveAndCallInjectionMethodForInstance($instance, $method, $params, $alias, $methodIsRequired, $methodClass = null) - { - if (!$instance instanceof GeneratorInstance) { - return parent::resolveAndCallInjectionMethodForInstance($instance, $method, $params, $alias, $methodIsRequired, $methodClass); - } - - /* @var $instance GeneratorInstance */ - $methodClass = $instance->getClass(); - $callParameters = $this->resolveMethodParameters($methodClass, $method, $params, $alias, $methodIsRequired); - - if ($callParameters !== false) { - $instance->addMethod(array( - 'method' => $method, - 'params' => $callParameters, - )); - - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - protected function getClass($instance) - { - if ($instance instanceof GeneratorInstance) { - /* @var $instance GeneratorInstance */ - - return $instance->getClass(); - } - - return parent::getClass($instance); - } -} diff --git a/library/Zend/Di/ServiceLocator/Generator.php b/library/Zend/Di/ServiceLocator/Generator.php deleted file mode 100755 index 82e8ca191..000000000 --- a/library/Zend/Di/ServiceLocator/Generator.php +++ /dev/null @@ -1,342 +0,0 @@ -injector = new DependencyInjectorProxy($injector); - } - - /** - * Set the class name for the generated service locator container - * - * @param string $name - * @return Generator - */ - public function setContainerClass($name) - { - $this->containerClass = $name; - - return $this; - } - - /** - * Set the namespace to use for the generated class file - * - * @param string $namespace - * @return Generator - */ - public function setNamespace($namespace) - { - $this->namespace = $namespace; - - return $this; - } - - /** - * Construct, configure, and return a PHP class file code generation object - * - * Creates a Zend\Code\Generator\FileGenerator object that has - * created the specified class and service locator methods. - * - * @param null|string $filename - * @throws \Zend\Di\Exception\RuntimeException - * @return FileGenerator - */ - public function getCodeGenerator($filename = null) - { - $injector = $this->injector; - $im = $injector->instanceManager(); - $indent = ' '; - $aliases = $this->reduceAliases($im->getAliases()); - $caseStatements = array(); - $getters = array(); - $definitions = $injector->definitions(); - - $fetched = array_unique(array_merge($definitions->getClasses(), $im->getAliases())); - - foreach ($fetched as $name) { - $getter = $this->normalizeAlias($name); - $meta = $injector->get($name); - $params = $meta->getParams(); - - // Build parameter list for instantiation - foreach ($params as $key => $param) { - if (null === $param || is_scalar($param) || is_array($param)) { - $string = var_export($param, 1); - if (strstr($string, '::__set_state(')) { - throw new Exception\RuntimeException('Arguments in definitions may not contain objects'); - } - $params[$key] = $string; - } elseif ($param instanceof GeneratorInstance) { - /* @var $param GeneratorInstance */ - $params[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); - } else { - $message = sprintf('Unable to use object arguments when building containers. Encountered with "%s", parameter of type "%s"', $name, get_class($param)); - throw new Exception\RuntimeException($message); - } - } - - // Strip null arguments from the end of the params list - $reverseParams = array_reverse($params, true); - foreach ($reverseParams as $key => $param) { - if ('NULL' === $param) { - unset($params[$key]); - continue; - } - break; - } - - // Create instantiation code - $constructor = $meta->getConstructor(); - if ('__construct' != $constructor) { - // Constructor callback - $callback = var_export($constructor, 1); - if (strstr($callback, '::__set_state(')) { - throw new Exception\RuntimeException('Unable to build containers that use callbacks requiring object instances'); - } - if (count($params)) { - $creation = sprintf('$object = call_user_func(%s, %s);', $callback, implode(', ', $params)); - } else { - $creation = sprintf('$object = call_user_func(%s);', $callback); - } - } else { - // Normal instantiation - $className = '\\' . ltrim($name, '\\'); - $creation = sprintf('$object = new %s(%s);', $className, implode(', ', $params)); - } - - // Create method call code - $methods = ''; - foreach ($meta->getMethods() as $methodData) { - if (!isset($methodData['name']) && !isset($methodData['method'])) { - continue; - } - $methodName = isset($methodData['name']) ? $methodData['name'] : $methodData['method']; - $methodParams = $methodData['params']; - - // Create method parameter representation - foreach ($methodParams as $key => $param) { - if (null === $param || is_scalar($param) || is_array($param)) { - $string = var_export($param, 1); - if (strstr($string, '::__set_state(')) { - throw new Exception\RuntimeException('Arguments in definitions may not contain objects'); - } - $methodParams[$key] = $string; - } elseif ($param instanceof GeneratorInstance) { - $methodParams[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); - } else { - $message = sprintf('Unable to use object arguments when generating method calls. Encountered with class "%s", method "%s", parameter of type "%s"', $name, $methodName, get_class($param)); - throw new Exception\RuntimeException($message); - } - } - - // Strip null arguments from the end of the params list - $reverseParams = array_reverse($methodParams, true); - foreach ($reverseParams as $key => $param) { - if ('NULL' === $param) { - unset($methodParams[$key]); - continue; - } - break; - } - - $methods .= sprintf("\$object->%s(%s);\n", $methodName, implode(', ', $methodParams)); - } - - // Generate caching statement - $storage = ''; - if ($im->hasSharedInstance($name, $params)) { - $storage = sprintf("\$this->services['%s'] = \$object;\n", $name); - } - - // Start creating getter - $getterBody = ''; - - // Create fetch of stored service - if ($im->hasSharedInstance($name, $params)) { - $getterBody .= sprintf("if (isset(\$this->services['%s'])) {\n", $name); - $getterBody .= sprintf("%sreturn \$this->services['%s'];\n}\n\n", $indent, $name); - } - - // Creation and method calls - $getterBody .= sprintf("%s\n", $creation); - $getterBody .= $methods; - - // Stored service - $getterBody .= $storage; - - // End getter body - $getterBody .= "return \$object;\n"; - - $getterDef = new MethodGenerator(); - $getterDef->setName($getter); - $getterDef->setBody($getterBody); - $getters[] = $getterDef; - - // Get cases for case statements - $cases = array($name); - if (isset($aliases[$name])) { - $cases = array_merge($aliases[$name], $cases); - } - - // Build case statement and store - $statement = ''; - foreach ($cases as $value) { - $statement .= sprintf("%scase '%s':\n", $indent, $value); - } - $statement .= sprintf("%sreturn \$this->%s();\n", str_repeat($indent, 2), $getter); - - $caseStatements[] = $statement; - } - - // Build switch statement - $switch = sprintf("switch (%s) {\n%s\n", '$name', implode("\n", $caseStatements)); - $switch .= sprintf("%sdefault:\n%sreturn parent::get(%s, %s);\n", $indent, str_repeat($indent, 2), '$name', '$params'); - $switch .= "}\n\n"; - - // Build get() method - $nameParam = new ParameterGenerator(); - $nameParam->setName('name'); - $paramsParam = new ParameterGenerator(); - $paramsParam->setName('params') - ->setType('array') - ->setDefaultValue(array()); - - $get = new MethodGenerator(); - $get->setName('get'); - $get->setParameters(array( - $nameParam, - $paramsParam, - )); - $get->setBody($switch); - - // Create getters for aliases - $aliasMethods = array(); - foreach ($aliases as $class => $classAliases) { - foreach ($classAliases as $alias) { - $aliasMethods[] = $this->getCodeGenMethodFromAlias($alias, $class); - } - } - - // Create class code generation object - $container = new ClassGenerator(); - $container->setName($this->containerClass) - ->setExtendedClass('ServiceLocator') - ->addMethodFromGenerator($get) - ->addMethods($getters) - ->addMethods($aliasMethods); - - // Create PHP file code generation object - $classFile = new FileGenerator(); - $classFile->setUse('Zend\Di\ServiceLocator') - ->setClass($container); - - if (null !== $this->namespace) { - $classFile->setNamespace($this->namespace); - } - - if (null !== $filename) { - $classFile->setFilename($filename); - } - - return $classFile; - } - - /** - * Reduces aliases - * - * Takes alias list and reduces it to a 2-dimensional array of - * class names pointing to an array of aliases that resolve to - * it. - * - * @param array $aliasList - * @return array - */ - protected function reduceAliases(array $aliasList) - { - $reduced = array(); - $aliases = array_keys($aliasList); - foreach ($aliasList as $alias => $service) { - if (in_array($service, $aliases)) { - do { - $service = $aliasList[$service]; - } while (in_array($service, $aliases)); - } - if (!isset($reduced[$service])) { - $reduced[$service] = array(); - } - $reduced[$service][] = $alias; - } - - return $reduced; - } - - /** - * Create a PhpMethod code generation object named after a given alias - * - * @param string $alias - * @param string $class Class to which alias refers - * @return MethodGenerator - */ - protected function getCodeGenMethodFromAlias($alias, $class) - { - $alias = $this->normalizeAlias($alias); - $method = new MethodGenerator(); - $method->setName($alias); - $method->setBody(sprintf('return $this->get(\'%s\');', $class)); - - return $method; - } - - /** - * Normalize an alias to a getter method name - * - * @param string $alias - * @return string - */ - protected function normalizeAlias($alias) - { - $normalized = preg_replace('/[^a-zA-Z0-9]/', ' ', $alias); - $normalized = 'get' . str_replace(' ', '', ucwords($normalized)); - - return $normalized; - } -} diff --git a/library/Zend/Di/ServiceLocator/GeneratorInstance.php b/library/Zend/Di/ServiceLocator/GeneratorInstance.php deleted file mode 100755 index aeb5f93ac..000000000 --- a/library/Zend/Di/ServiceLocator/GeneratorInstance.php +++ /dev/null @@ -1,196 +0,0 @@ -class = $class; - $this->alias = $alias; - $this->constructor = $constructor; - $this->params = $params; - } - - /** - * Retrieves the best available name for this instance (instance alias first then class name) - * - * @return string|null - */ - public function getName() - { - return $this->alias ? $this->alias : $this->class; - } - - /** - * Class of the instance. Null if class is unclear (such as when the instance is produced by a callback) - * - * @return string|null - */ - public function getClass() - { - return $this->class; - } - - /** - * Alias for the instance (if any) - * - * @return string|null - */ - public function getAlias() - { - return $this->alias; - } - - /** - * Set class name - * - * In the case of an instance created via a callback, we need to set the - * class name after creating the generator instance. - * - * @param string $class - * @return GeneratorInstance - */ - public function setClass($class) - { - $this->class = $class; - - return $this; - } - - /** - * Set instance alias - * - * @param string $alias - * @return GeneratorInstance - */ - public function setAlias($alias) - { - $this->alias = $alias; - - return $this; - } - - /** - * Get instantiator - * - * @return mixed constructor method name or callable responsible for generating instance - */ - public function getConstructor() - { - return $this->constructor; - } - - /** - * Parameters passed to the instantiator as an ordered list of parameters. Each parameter that refers to another - * instance fetched recursively is a GeneratorInstance itself - * - * @return array - */ - public function getParams() - { - return $this->params; - } - - /** - * Set methods - * - * @param array $methods - * @return GeneratorInstance - */ - public function setMethods(array $methods) - { - $this->methods = $methods; - - return $this; - } - - /** - * Add a method called on the instance - * - * @param $method - * @return GeneratorInstance - */ - public function addMethod($method) - { - $this->methods[] = $method; - - return $this; - } - - /** - * Retrieves a list of methods that are called on the instance in their call order. Each returned element has form - * array('method' => 'methodName', 'params' => array( ... ordered list of call parameters ... ), where every call - * parameter that is a recursively fetched instance is a GeneratorInstance itself - * - * @return array - */ - public function getMethods() - { - return $this->methods; - } - - /** - * @param bool $shared - */ - public function setShared($shared) - { - $this->shared = (bool) $shared; - } - - /** - * Retrieves whether the instance is shared or not - * - * @return bool - */ - public function isShared() - { - return $this->shared; - } -} diff --git a/library/Zend/Di/ServiceLocatorInterface.php b/library/Zend/Di/ServiceLocatorInterface.php deleted file mode 100755 index fe5e12572..000000000 --- a/library/Zend/Di/ServiceLocatorInterface.php +++ /dev/null @@ -1,23 +0,0 @@ - array( - 'Zend\Foo\Bar' => array( - 'public' => true, - 'methods' => array( - '__construct' => array( - 'params' => array( - 'foo' => 'bar', - ), - 'class' => 'Some\Default\Class' - ), - 'setConfig' => array( - 'params' => array( - 'bar' => 'baz', - ), - ), - ), - ), - ), - ) - -- Ability to pass configuration to a generated ServiceLocator - -- Skip optional arguments if not passed in configuration or part of definition - (current behavior is to raise an exception if *any* arguments are missing) - -- Scoped Containers: - - Described here: - http://picocontainer.org/scopes.html - - This is something that should be explored when we start using these containers - with ServiceLocators inside an application. While part of this has to do with - garbage collection in Java (something we need not worry with in PHP since there - is no persistent in-memory objects), the interesting use case would be having a - container cloned from another container that has more or less (a subset) of the - definitions available to the Container's newInstance() and get() facilities. - -- Better Strategy Management - - Currently, the strategies for determining dependencies is hard coded into the - various definitions. Ideally, we'd be able to have configurable strategies - that the definitions can then utilize to do their job: - - http://picocontainer.org/injection.html - - We currently support constructor injection and setter injection (methods prefixed - by set[A-Z]) - -- Annotation Parsing - - Ideally, at some point, Zend\Code\Scanner will support Annotation parsing. When - this is possible, we'd like to be able to use @inject similar to - http://picocontainer.org/annotated-method-injection.html - -- SuperType Resolution - - (partially done inside resolveMethodParameters with is_subtype_of()) - - If a class claims it needs a dependency of not an object, but a particular - interface, the ability to find an object that suits that dependency, either - through a concept called 'Preferred Objects' or via a 'Property'. The - following should be supported: - - The compiler also needs to be aware of other definitions when looking up SuperTypes - - $definition = new AggregateDefinition(); - $definition->addDefinition('Zend\Controller\DiDefinition'); - - $compiler = new Compiler() - $compiler->addDefinition($definition); - $compiler->addCodeScanner(__DIR__ . 'My/Blog'); - $array = $compiler->compile() - $definition->addDefinition(new ArrayDefinition($array)); - -- Performance & Benchmarking - - Zend\Code\Scanner- check memory usage, perhaps use gc_collect_cycles() to free memory, - we'll have to do this on large scan bases. - - Benchmark compiler: reflection vs. code scanner - - diff --git a/library/Zend/Di/composer.json b/library/Zend/Di/composer.json deleted file mode 100755 index 81f6cb781..000000000 --- a/library/Zend/Di/composer.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "zendframework/zend-di", - "description": " ", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "di" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Di\\": "" - } - }, - "target-dir": "Zend/Di", - "require": { - "php": ">=5.3.23", - "zendframework/zend-code": "self.version", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-servicemanager": "self.version" - }, - "suggest": { - "zendframework/zend-servicemanager": "Zend\\ServiceManager component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Dom/CONTRIBUTING.md b/library/Zend/Dom/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Dom/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Dom/Css2Xpath.php b/library/Zend/Dom/Css2Xpath.php deleted file mode 100755 index 7aa7d506c..000000000 --- a/library/Zend/Dom/Css2Xpath.php +++ /dev/null @@ -1,33 +0,0 @@ -errors = array(null); - - set_error_handler(array($this, 'addError'), \E_WARNING); - $nodeList = $this->query($expression); - restore_error_handler(); - - $exception = array_pop($this->errors); - if ($exception) { - throw $exception; - } - - return $nodeList; - } - - /** - * Adds an error to the stack of errors - * - * @param int $errno - * @param string $errstr - * @param string $errfile - * @param int $errline - * @return void - */ - public function addError($errno, $errstr = '', $errfile = '', $errline = 0) - { - $last_error = end($this->errors); - $this->errors[] = new ErrorException( - $errstr, - 0, - $errno, - $errfile, - $errline, - $last_error - ); - } -} diff --git a/library/Zend/Dom/Document.php b/library/Zend/Dom/Document.php deleted file mode 100755 index 456e17f86..000000000 --- a/library/Zend/Dom/Document.php +++ /dev/null @@ -1,310 +0,0 @@ -setStringDocument($document, $type, $encoding); - } - - /** - * Get raw set document - * - * @return string|null - */ - public function getStringDocument() - { - return $this->stringDocument; - } - - /** - * Set raw document - * - * @param string|null $document - * @param string|null $forcedType Type for the provided document (see constants) - * @param string|null $forcedEncoding Encoding for the provided document - * @return self - */ - protected function setStringDocument($document, $forcedType = null, $forcedEncoding = null) - { - $type = static::DOC_HTML; - if (strstr($document, 'DTD XHTML')) { - $type = static::DOC_XHTML; - } - - // Breaking XML declaration to make syntax highlighting work - if ('<' . '?xml' == substr(trim($document), 0, 5)) { - $type = static::DOC_XML; - if (preg_match('/]*xmlns="([^"]+)"[^>]*>/i', $document, $matches)) { - $this->xpathNamespaces[] = $matches[1]; - $type = static::DOC_XHTML; - } - } - - // Unsetting previously registered DOMDocument - $this->domDocument = null; - $this->stringDocument = !empty($document) ? $document : null; - - $this->setType($forcedType ?: (!empty($document) ? $type : null)); - $this->setEncoding($forcedEncoding); - $this->setErrors(array()); - - return $this; - } - - /** - * Get raw document type - * - * @return string|null - */ - public function getType() - { - return $this->type; - } - - /** - * Set raw document type - * - * @param string $type - * @return self - */ - protected function setType($type) - { - $this->type = $type; - - return $this; - } - - /** - * Get DOMDocument generated from set raw document - * - * @return DOMDocument - * @throws Exception\RuntimeException If cannot get DOMDocument; no document registered - */ - public function getDomDocument() - { - if (null === ($stringDocument = $this->getStringDocument())) { - throw new Exception\RuntimeException('Cannot get DOMDocument; no document registered'); - } - - if (null === $this->domDocument) { - $this->domDocument = $this->getDomDocumentFromString($stringDocument); - } - - return $this->domDocument; - } - - /** - * Set DOMDocument - * - * @param DOMDocument $domDocument - * @return self - */ - protected function setDomDocument(DOMDocument $domDocument) - { - $this->domDocument = $domDocument; - - return $this; - } - - /** - * Get set document encoding - * - * @return string|null - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set raw document encoding for DOMDocument generation - * - * @param string|null $encoding - * @return self - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - - return $this->encoding; - } - - /** - * Get DOMDocument generation errors - * - * @return array - */ - public function getErrors() - { - return $this->errors; - } - - /** - * Set document errors from DOMDocument generation - * - * @param array $errors - * @return self - */ - protected function setErrors($errors) - { - $this->errors = $errors; - - return $this; - } - - /** - * Get DOMDocument from set raw document - * - * @return DOMDocument - * @throws Exception\RuntimeException - */ - protected function getDomDocumentFromString($stringDocument) - { - libxml_use_internal_errors(true); - libxml_disable_entity_loader(true); - - $encoding = $this->getEncoding(); - $domDoc = null === $encoding ? new DOMDocument('1.0') : new DOMDocument('1.0', $encoding); - $type = $this->getType(); - - switch ($type) { - case static::DOC_XML: - $success = $domDoc->loadXML($stringDocument); - foreach ($domDoc->childNodes as $child) { - if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { - throw new Exception\RuntimeException( - 'Invalid XML: Detected use of illegal DOCTYPE' - ); - } - } - break; - case static::DOC_HTML: - case static::DOC_XHTML: - default: - $success = $domDoc->loadHTML($stringDocument); - break; - } - - $errors = libxml_get_errors(); - if (!empty($errors)) { - $this->setErrors($errors); - libxml_clear_errors(); - } - - libxml_disable_entity_loader(false); - libxml_use_internal_errors(false); - - if (!$success) { - throw new Exception\RuntimeException(sprintf('Error parsing document (type == %s)', $type)); - } - - return $domDoc; - } - - /** - * Get Document's registered XPath namespaces - * - * @return array - */ - public function getXpathNamespaces() - { - return $this->xpathNamespaces; - } - - /** - * Register XPath namespaces - * - * @param array $xpathNamespaces - * @return void - */ - public function registerXpathNamespaces($xpathNamespaces) - { - $this->xpathNamespaces = $xpathNamespaces; - } - - /** - * Get Document's registered XPath PHP Functions - * - * @return string|null - */ - public function getXpathPhpFunctions() - { - return $this->xpathPhpFunctions; - } - /** - * Register PHP Functions to use in internal DOMXPath - * - * @param bool $xpathPhpFunctions - * @return void - */ - public function registerXpathPhpFunctions($xpathPhpFunctions = true) - { - $this->xpathPhpFunctions = $xpathPhpFunctions; - } -} diff --git a/library/Zend/Dom/Document/NodeList.php b/library/Zend/Dom/Document/NodeList.php deleted file mode 100755 index 352326fe2..000000000 --- a/library/Zend/Dom/Document/NodeList.php +++ /dev/null @@ -1,160 +0,0 @@ -list = $list; - } - - /** - * Iterator: rewind to first element - * - * @return DOMNode - */ - public function rewind() - { - $this->position = 0; - - return $this->list->item(0); - } - - /** - * Iterator: is current position valid? - * - * @return bool - */ - public function valid() - { - if (in_array($this->position, range(0, $this->list->length - 1)) && $this->list->length > 0) { - return true; - } - - return false; - } - - /** - * Iterator: return current element - * - * @return DOMNode - */ - public function current() - { - return $this->list->item($this->position); - } - - /** - * Iterator: return key of current element - * - * @return int - */ - public function key() - { - return $this->position; - } - - /** - * Iterator: move to next element - * - * @return DOMNode - */ - public function next() - { - ++$this->position; - - return $this->list->item($this->position); - } - - /** - * Countable: get count - * - * @return int - */ - public function count() - { - return $this->list->length; - } - - /** - * ArrayAccess: offset exists - * - * @param int $key - * @return bool - */ - public function offsetExists($key) - { - if (in_array($key, range(0, $this->list->length - 1)) && $this->list->length > 0) { - return true; - } - return false; - } - - /** - * ArrayAccess: get offset - * - * @param int $key - * @return mixed - */ - public function offsetGet($key) - { - return $this->list->item($key); - } - - /** - * ArrayAccess: set offset - * - * @param mixed $key - * @param mixed $value - * @throws Exception\BadMethodCallException when attempting to write to a read-only item - */ - public function offsetSet($key, $value) - { - throw new Exception\BadMethodCallException('Attempting to write to a read-only list'); - } - - /** - * ArrayAccess: unset offset - * - * @param mixed $key - * @throws Exception\BadMethodCallException when attempting to unset a read-only item - */ - public function offsetUnset($key) - { - throw new Exception\BadMethodCallException('Attempting to unset on a read-only list'); - } -} diff --git a/library/Zend/Dom/Document/Query.php b/library/Zend/Dom/Document/Query.php deleted file mode 100755 index bea590328..000000000 --- a/library/Zend/Dom/Document/Query.php +++ /dev/null @@ -1,169 +0,0 @@ -getDomDocument()); - - $xpathNamespaces = $document->getXpathNamespaces(); - foreach ($xpathNamespaces as $prefix => $namespaceUri) { - $xpath->registerNamespace($prefix, $namespaceUri); - } - - if ($xpathPhpfunctions = $document->getXpathPhpFunctions()) { - $xpath->registerNamespace('php', 'http://php.net/xpath'); - ($xpathPhpfunctions === true) ? $xpath->registerPHPFunctions() : $xpath->registerPHPFunctions($xpathPhpfunctions); - } - - $nodeList = $xpath->queryWithErrorException($expression); - return new NodeList($nodeList); - } - - /** - * Transform CSS expression to XPath - * - * @param string $path - * @return string - */ - public static function cssToXpath($path) - { - $path = (string) $path; - if (strstr($path, ',')) { - $paths = explode(',', $path); - $expressions = array(); - foreach ($paths as $path) { - $xpath = static::cssToXpath(trim($path)); - if (is_string($xpath)) { - $expressions[] = $xpath; - } elseif (is_array($xpath)) { - $expressions = array_merge($expressions, $xpath); - } - } - return implode('|', $expressions); - } - - $paths = array('//'); - $path = preg_replace('|\s+>\s+|', '>', $path); - $segments = preg_split('/\s+/', $path); - foreach ($segments as $key => $segment) { - $pathSegment = static::_tokenize($segment); - if (0 == $key) { - if (0 === strpos($pathSegment, '[contains(')) { - $paths[0] .= '*' . ltrim($pathSegment, '*'); - } else { - $paths[0] .= $pathSegment; - } - continue; - } - if (0 === strpos($pathSegment, '[contains(')) { - foreach ($paths as $pathKey => $xpath) { - $paths[$pathKey] .= '//*' . ltrim($pathSegment, '*'); - $paths[] = $xpath . $pathSegment; - } - } else { - foreach ($paths as $pathKey => $xpath) { - $paths[$pathKey] .= '//' . $pathSegment; - } - } - } - - if (1 == count($paths)) { - return $paths[0]; - } - return implode('|', $paths); - } - - /** - * Tokenize CSS expressions to XPath - * - * @param string $expression - * @return string - */ - protected static function _tokenize($expression) - { - // Child selectors - $expression = str_replace('>', '/', $expression); - - // IDs - $expression = preg_replace('|#([a-z][a-z0-9_-]*)|i', '[@id=\'$1\']', $expression); - $expression = preg_replace('|(?cssQuery = $cssQuery; - $this->xpathQuery = $xpathQuery; - $this->document = $document; - $this->nodeList = $nodeList; - } - - /** - * Retrieve CSS Query - * - * @return string - */ - public function getCssQuery() - { - return $this->cssQuery; - } - - /** - * Retrieve XPath query - * - * @return string - */ - public function getXpathQuery() - { - return $this->xpathQuery; - } - - /** - * Retrieve DOMDocument - * - * @return DOMDocument - */ - public function getDocument() - { - return $this->document; - } - - /** - * Iterator: rewind to first element - * - * @return DOMNode - */ - public function rewind() - { - $this->position = 0; - - return $this->nodeList->item(0); - } - - /** - * Iterator: is current position valid? - * - * @return bool - */ - public function valid() - { - if (in_array($this->position, range(0, $this->nodeList->length - 1)) && $this->nodeList->length > 0) { - return true; - } - - return false; - } - - /** - * Iterator: return current element - * - * @return DOMNode - */ - public function current() - { - return $this->nodeList->item($this->position); - } - - /** - * Iterator: return key of current element - * - * @return int - */ - public function key() - { - return $this->position; - } - - /** - * Iterator: move to next element - * - * @return DOMNode - */ - public function next() - { - ++$this->position; - - return $this->nodeList->item($this->position); - } - - /** - * Countable: get count - * - * @return int - */ - public function count() - { - return $this->nodeList->length; - } - - /** - * ArrayAccess: offset exists - * - * @param int $key - * @return bool - */ - public function offsetExists($key) - { - if (in_array($key, range(0, $this->nodeList->length - 1)) && $this->nodeList->length > 0) { - return true; - } - return false; - } - - /** - * ArrayAccess: get offset - * - * @param int $key - * @return mixed - */ - public function offsetGet($key) - { - return $this->nodeList->item($key); - } - - /** - * ArrayAccess: set offset - * - * @param mixed $key - * @param mixed $value - * @throws Exception\BadMethodCallException when attempting to write to a read-only item - */ - public function offsetSet($key, $value) - { - throw new Exception\BadMethodCallException('Attempting to write to a read-only list'); - } - - /** - * ArrayAccess: unset offset - * - * @param mixed $key - * @throws Exception\BadMethodCallException when attempting to unset a read-only item - */ - public function offsetUnset($key) - { - throw new Exception\BadMethodCallException('Attempting to unset on a read-only list'); - } -} diff --git a/library/Zend/Dom/Query.php b/library/Zend/Dom/Query.php deleted file mode 100755 index 551429916..000000000 --- a/library/Zend/Dom/Query.php +++ /dev/null @@ -1,320 +0,0 @@ -setEncoding($encoding); - $this->setDocument($document); - } - - /** - * Set document encoding - * - * @param string $encoding - * @return Query - */ - public function setEncoding($encoding) - { - $this->encoding = (null === $encoding) ? null : (string) $encoding; - return $this; - } - - /** - * Get document encoding - * - * @return null|string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set document to query - * - * @param string $document - * @param null|string $encoding Document encoding - * @return Query - */ - public function setDocument($document, $encoding = null) - { - if (0 === strlen($document)) { - return $this; - } - // breaking XML declaration to make syntax highlighting work - if ('<' . '?xml' == substr(trim($document), 0, 5)) { - if (preg_match('/]*xmlns="([^"]+)"[^>]*>/i', $document, $matches)) { - $this->xpathNamespaces[] = $matches[1]; - return $this->setDocumentXhtml($document, $encoding); - } - return $this->setDocumentXml($document, $encoding); - } - if (strstr($document, 'DTD XHTML')) { - return $this->setDocumentXhtml($document, $encoding); - } - return $this->setDocumentHtml($document, $encoding); - } - - /** - * Register HTML document - * - * @param string $document - * @param null|string $encoding Document encoding - * @return Query - */ - public function setDocumentHtml($document, $encoding = null) - { - $this->document = (string) $document; - $this->docType = self::DOC_HTML; - if (null !== $encoding) { - $this->setEncoding($encoding); - } - return $this; - } - - /** - * Register XHTML document - * - * @param string $document - * @param null|string $encoding Document encoding - * @return Query - */ - public function setDocumentXhtml($document, $encoding = null) - { - $this->document = (string) $document; - $this->docType = self::DOC_XHTML; - if (null !== $encoding) { - $this->setEncoding($encoding); - } - return $this; - } - - /** - * Register XML document - * - * @param string $document - * @param null|string $encoding Document encoding - * @return Query - */ - public function setDocumentXml($document, $encoding = null) - { - $this->document = (string) $document; - $this->docType = self::DOC_XML; - if (null !== $encoding) { - $this->setEncoding($encoding); - } - return $this; - } - - /** - * Retrieve current document - * - * @return string - */ - public function getDocument() - { - return $this->document; - } - - /** - * Get document type - * - * @return string - */ - public function getDocumentType() - { - return $this->docType; - } - - /** - * Get any DOMDocument errors found - * - * @return false|array - */ - public function getDocumentErrors() - { - return $this->documentErrors; - } - - /** - * Perform a CSS selector query - * - * @param string $query - * @return NodeList - */ - public function execute($query) - { - $xpathQuery = Document\Query::cssToXpath($query); - return $this->queryXpath($xpathQuery, $query); - } - - /** - * Perform an XPath query - * - * @param string|array $xpathQuery - * @param string|null $query CSS selector query - * @throws Exception\RuntimeException - * @return NodeList - */ - public function queryXpath($xpathQuery, $query = null) - { - if (null === ($document = $this->getDocument())) { - throw new Exception\RuntimeException('Cannot query; no document registered'); - } - - $encoding = $this->getEncoding(); - libxml_use_internal_errors(true); - libxml_disable_entity_loader(true); - if (null === $encoding) { - $domDoc = new DOMDocument('1.0'); - } else { - $domDoc = new DOMDocument('1.0', $encoding); - } - $type = $this->getDocumentType(); - switch ($type) { - case self::DOC_XML: - $success = $domDoc->loadXML($document); - foreach ($domDoc->childNodes as $child) { - if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { - throw new Exception\RuntimeException( - 'Invalid XML: Detected use of illegal DOCTYPE' - ); - } - } - break; - case self::DOC_HTML: - case self::DOC_XHTML: - default: - $success = $domDoc->loadHTML($document); - break; - } - $errors = libxml_get_errors(); - if (!empty($errors)) { - $this->documentErrors = $errors; - libxml_clear_errors(); - } - libxml_disable_entity_loader(false); - libxml_use_internal_errors(false); - - if (!$success) { - throw new Exception\RuntimeException(sprintf('Error parsing document (type == %s)', $type)); - } - - $nodeList = $this->getNodeList($domDoc, $xpathQuery); - return new NodeList($query, $xpathQuery, $domDoc, $nodeList); - } - - /** - * Register XPath namespaces - * - * @param array $xpathNamespaces - * @return void - */ - public function registerXpathNamespaces($xpathNamespaces) - { - $this->xpathNamespaces = $xpathNamespaces; - } - - /** - * Register PHP Functions to use in internal DOMXPath - * - * @param bool $xpathPhpFunctions - * @return void - */ - public function registerXpathPhpFunctions($xpathPhpFunctions = true) - { - $this->xpathPhpFunctions = $xpathPhpFunctions; - } - - /** - * Prepare node list - * - * @param DOMDocument $document - * @param string|array $xpathQuery - * @return array - * @throws \ErrorException If query cannot be executed - */ - protected function getNodeList($document, $xpathQuery) - { - $xpath = new DOMXPath($document); - foreach ($this->xpathNamespaces as $prefix => $namespaceUri) { - $xpath->registerNamespace($prefix, $namespaceUri); - } - if ($this->xpathPhpFunctions) { - $xpath->registerNamespace("php", "http://php.net/xpath"); - ($this->xpathPhpFunctions === true) ? - $xpath->registerPHPFunctions() - : $xpath->registerPHPFunctions($this->xpathPhpFunctions); - } - $xpathQuery = (string) $xpathQuery; - - $nodeList = $xpath->queryWithErrorException($xpathQuery); - return $nodeList; - } -} diff --git a/library/Zend/Dom/README.md b/library/Zend/Dom/README.md deleted file mode 100755 index b82c2b9ff..000000000 --- a/library/Zend/Dom/README.md +++ /dev/null @@ -1,15 +0,0 @@ -DOM Component from ZF2 -====================== - -This is the DOM component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Dom/composer.json b/library/Zend/Dom/composer.json deleted file mode 100755 index 94433c52a..000000000 --- a/library/Zend/Dom/composer.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "zendframework/zend-dom", - "description": "provides tools for working with DOM documents and structures", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "dom" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Dom\\": "" - } - }, - "target-dir": "Zend/Dom", - "require": { - "php": ">=5.3.23" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Escaper/CONTRIBUTING.md b/library/Zend/Escaper/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Escaper/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Escaper/Escaper.php b/library/Zend/Escaper/Escaper.php deleted file mode 100755 index 3a3d30eb6..000000000 --- a/library/Zend/Escaper/Escaper.php +++ /dev/null @@ -1,387 +0,0 @@ - 'quot', // quotation mark - 38 => 'amp', // ampersand - 60 => 'lt', // less-than sign - 62 => 'gt', // greater-than sign - ); - - /** - * Current encoding for escaping. If not UTF-8, we convert strings from this encoding - * pre-escaping and back to this encoding post-escaping. - * - * @var string - */ - protected $encoding = 'utf-8'; - - /** - * Holds the value of the special flags passed as second parameter to - * htmlspecialchars(). We modify these for PHP 5.4 to take advantage - * of the new ENT_SUBSTITUTE flag for correctly dealing with invalid - * UTF-8 sequences. - * - * @var string - */ - protected $htmlSpecialCharsFlags = ENT_QUOTES; - - /** - * Static Matcher which escapes characters for HTML Attribute contexts - * - * @var callable - */ - protected $htmlAttrMatcher; - - /** - * Static Matcher which escapes characters for Javascript contexts - * - * @var callable - */ - protected $jsMatcher; - - /** - * Static Matcher which escapes characters for CSS Attribute contexts - * - * @var callable - */ - protected $cssMatcher; - - /** - * List of all encoding supported by this class - * - * @var array - */ - protected $supportedEncodings = array( - 'iso-8859-1', 'iso8859-1', 'iso-8859-5', 'iso8859-5', - 'iso-8859-15', 'iso8859-15', 'utf-8', 'cp866', - 'ibm866', '866', 'cp1251', 'windows-1251', - 'win-1251', '1251', 'cp1252', 'windows-1252', - '1252', 'koi8-r', 'koi8-ru', 'koi8r', - 'big5', '950', 'gb2312', '936', - 'big5-hkscs', 'shift_jis', 'sjis', 'sjis-win', - 'cp932', '932', 'euc-jp', 'eucjp', - 'eucjp-win', 'macroman' - ); - - /** - * Constructor: Single parameter allows setting of global encoding for use by - * the current object. If PHP 5.4 is detected, additional ENT_SUBSTITUTE flag - * is set for htmlspecialchars() calls. - * - * @param string $encoding - * @throws Exception\InvalidArgumentException - */ - public function __construct($encoding = null) - { - if ($encoding !== null) { - $encoding = (string) $encoding; - if ($encoding === '') { - throw new Exception\InvalidArgumentException( - get_class($this) . ' constructor parameter does not allow a blank value' - ); - } - - $encoding = strtolower($encoding); - if (!in_array($encoding, $this->supportedEncodings)) { - throw new Exception\InvalidArgumentException( - 'Value of \'' . $encoding . '\' passed to ' . get_class($this) - . ' constructor parameter is invalid. Provide an encoding supported by htmlspecialchars()' - ); - } - - $this->encoding = $encoding; - } - - if (defined('ENT_SUBSTITUTE')) { - $this->htmlSpecialCharsFlags|= ENT_SUBSTITUTE; - } - - // set matcher callbacks - $this->htmlAttrMatcher = array($this, 'htmlAttrMatcher'); - $this->jsMatcher = array($this, 'jsMatcher'); - $this->cssMatcher = array($this, 'cssMatcher'); - } - - /** - * Return the encoding that all output/input is expected to be encoded in. - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Escape a string for the HTML Body context where there are very few characters - * of special meaning. Internally this will use htmlspecialchars(). - * - * @param string $string - * @return string - */ - public function escapeHtml($string) - { - return htmlspecialchars($string, $this->htmlSpecialCharsFlags, $this->encoding); - } - - /** - * Escape a string for the HTML Attribute context. We use an extended set of characters - * to escape that are not covered by htmlspecialchars() to cover cases where an attribute - * might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE). - * - * @param string $string - * @return string - */ - public function escapeHtmlAttr($string) - { - $string = $this->toUtf8($string); - if ($string === '' || ctype_digit($string)) { - return $string; - } - - $result = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $this->htmlAttrMatcher, $string); - return $this->fromUtf8($result); - } - - /** - * Escape a string for the Javascript context. This does not use json_encode(). An extended - * set of characters are escaped beyond ECMAScript's rules for Javascript literal string - * escaping in order to prevent misinterpretation of Javascript as HTML leading to the - * injection of special characters and entities. The escaping used should be tolerant - * of cases where HTML escaping was not applied on top of Javascript escaping correctly. - * Backslash escaping is not used as it still leaves the escaped character as-is and so - * is not useful in a HTML context. - * - * @param string $string - * @return string - */ - public function escapeJs($string) - { - $string = $this->toUtf8($string); - if ($string === '' || ctype_digit($string)) { - return $string; - } - - $result = preg_replace_callback('/[^a-z0-9,\._]/iSu', $this->jsMatcher, $string); - return $this->fromUtf8($result); - } - - /** - * Escape a string for the URI or Parameter contexts. This should not be used to escape - * an entire URI - only a subcomponent being inserted. The function is a simple proxy - * to rawurlencode() which now implements RFC 3986 since PHP 5.3 completely. - * - * @param string $string - * @return string - */ - public function escapeUrl($string) - { - return rawurlencode($string); - } - - /** - * Escape a string for the CSS context. CSS escaping can be applied to any string being - * inserted into CSS and escapes everything except alphanumerics. - * - * @param string $string - * @return string - */ - public function escapeCss($string) - { - $string = $this->toUtf8($string); - if ($string === '' || ctype_digit($string)) { - return $string; - } - - $result = preg_replace_callback('/[^a-z0-9]/iSu', $this->cssMatcher, $string); - return $this->fromUtf8($result); - } - - /** - * Callback function for preg_replace_callback that applies HTML Attribute - * escaping to all matches. - * - * @param array $matches - * @return string - */ - protected function htmlAttrMatcher($matches) - { - $chr = $matches[0]; - $ord = ord($chr); - - /** - * The following replaces characters undefined in HTML with the - * hex entity for the Unicode replacement character. - */ - if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r") - || ($ord >= 0x7f && $ord <= 0x9f) - ) { - return '�'; - } - - /** - * Check if the current character to escape has a name entity we should - * replace it with while grabbing the integer value of the character. - */ - if (strlen($chr) > 1) { - $chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8'); - } - - $hex = bin2hex($chr); - $ord = hexdec($hex); - if (isset(static::$htmlNamedEntityMap[$ord])) { - return '&' . static::$htmlNamedEntityMap[$ord] . ';'; - } - - /** - * Per OWASP recommendations, we'll use upper hex entities - * for any other characters where a named entity does not exist. - */ - if ($ord > 255) { - return sprintf('&#x%04X;', $ord); - } - return sprintf('&#x%02X;', $ord); - } - - /** - * Callback function for preg_replace_callback that applies Javascript - * escaping to all matches. - * - * @param array $matches - * @return string - */ - protected function jsMatcher($matches) - { - $chr = $matches[0]; - if (strlen($chr) == 1) { - return sprintf('\\x%02X', ord($chr)); - } - $chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8'); - return sprintf('\\u%04s', strtoupper(bin2hex($chr))); - } - - /** - * Callback function for preg_replace_callback that applies CSS - * escaping to all matches. - * - * @param array $matches - * @return string - */ - protected function cssMatcher($matches) - { - $chr = $matches[0]; - if (strlen($chr) == 1) { - $ord = ord($chr); - } else { - $chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8'); - $ord = hexdec(bin2hex($chr)); - } - return sprintf('\\%X ', $ord); - } - - /** - * Converts a string to UTF-8 from the base encoding. The base encoding is set via this - * class' constructor. - * - * @param string $string - * @throws Exception\RuntimeException - * @return string - */ - protected function toUtf8($string) - { - if ($this->getEncoding() === 'utf-8') { - $result = $string; - } else { - $result = $this->convertEncoding($string, 'UTF-8', $this->getEncoding()); - } - - if (!$this->isUtf8($result)) { - throw new Exception\RuntimeException(sprintf( - 'String to be escaped was not valid UTF-8 or could not be converted: %s', $result - )); - } - - return $result; - } - - /** - * Converts a string from UTF-8 to the base encoding. The base encoding is set via this - * class' constructor. - * @param string $string - * @return string - */ - protected function fromUtf8($string) - { - if ($this->getEncoding() === 'utf-8') { - return $string; - } - - return $this->convertEncoding($string, $this->getEncoding(), 'UTF-8'); - } - - /** - * Checks if a given string appears to be valid UTF-8 or not. - * - * @param string $string - * @return bool - */ - protected function isUtf8($string) - { - return ($string === '' || preg_match('/^./su', $string)); - } - - /** - * Encoding conversion helper which wraps iconv and mbstring where they exist or throws - * and exception where neither is available. - * - * @param string $string - * @param string $to - * @param array|string $from - * @throws Exception\RuntimeException - * @return string - */ - protected function convertEncoding($string, $to, $from) - { - if (function_exists('iconv')) { - $result = iconv($from, $to, $string); - } elseif (function_exists('mb_convert_encoding')) { - $result = mb_convert_encoding($string, $to, $from); - } else { - throw new Exception\RuntimeException( - get_class($this) - . ' requires either the iconv or mbstring extension to be installed' - . ' when escaping for non UTF-8 strings.' - ); - } - - if ($result === false) { - return ''; // return non-fatal blank string on encoding errors from users - } - return $result; - } -} diff --git a/library/Zend/Escaper/Exception/ExceptionInterface.php b/library/Zend/Escaper/Exception/ExceptionInterface.php deleted file mode 100755 index 3a7c8a3f2..000000000 --- a/library/Zend/Escaper/Exception/ExceptionInterface.php +++ /dev/null @@ -1,14 +0,0 @@ -=5.3.23" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/EventManager/AbstractListenerAggregate.php b/library/Zend/EventManager/AbstractListenerAggregate.php deleted file mode 100755 index 3f4df278f..000000000 --- a/library/Zend/EventManager/AbstractListenerAggregate.php +++ /dev/null @@ -1,33 +0,0 @@ -listeners as $index => $callback) { - if ($events->detach($callback)) { - unset($this->listeners[$index]); - } - } - } -} diff --git a/library/Zend/EventManager/CONTRIBUTING.md b/library/Zend/EventManager/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/EventManager/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/EventManager/Event.php b/library/Zend/EventManager/Event.php deleted file mode 100755 index abc34e744..000000000 --- a/library/Zend/EventManager/Event.php +++ /dev/null @@ -1,209 +0,0 @@ -setName($name); - } - - if (null !== $target) { - $this->setTarget($target); - } - - if (null !== $params) { - $this->setParams($params); - } - } - - /** - * Get event name - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Get the event target - * - * This may be either an object, or the name of a static method. - * - * @return string|object - */ - public function getTarget() - { - return $this->target; - } - - /** - * Set parameters - * - * Overwrites parameters - * - * @param array|ArrayAccess|object $params - * @return Event - * @throws Exception\InvalidArgumentException - */ - public function setParams($params) - { - if (!is_array($params) && !is_object($params)) { - throw new Exception\InvalidArgumentException( - sprintf('Event parameters must be an array or object; received "%s"', gettype($params)) - ); - } - - $this->params = $params; - return $this; - } - - /** - * Get all parameters - * - * @return array|object|ArrayAccess - */ - public function getParams() - { - return $this->params; - } - - /** - * Get an individual parameter - * - * If the parameter does not exist, the $default value will be returned. - * - * @param string|int $name - * @param mixed $default - * @return mixed - */ - public function getParam($name, $default = null) - { - // Check in params that are arrays or implement array access - if (is_array($this->params) || $this->params instanceof ArrayAccess) { - if (!isset($this->params[$name])) { - return $default; - } - - return $this->params[$name]; - } - - // Check in normal objects - if (!isset($this->params->{$name})) { - return $default; - } - return $this->params->{$name}; - } - - /** - * Set the event name - * - * @param string $name - * @return Event - */ - public function setName($name) - { - $this->name = (string) $name; - return $this; - } - - /** - * Set the event target/context - * - * @param null|string|object $target - * @return Event - */ - public function setTarget($target) - { - $this->target = $target; - return $this; - } - - /** - * Set an individual parameter to a value - * - * @param string|int $name - * @param mixed $value - * @return Event - */ - public function setParam($name, $value) - { - if (is_array($this->params) || $this->params instanceof ArrayAccess) { - // Arrays or objects implementing array access - $this->params[$name] = $value; - } else { - // Objects - $this->params->{$name} = $value; - } - return $this; - } - - /** - * Stop further event propagation - * - * @param bool $flag - * @return void - */ - public function stopPropagation($flag = true) - { - $this->stopPropagation = (bool) $flag; - } - - /** - * Is propagation stopped? - * - * @return bool - */ - public function propagationIsStopped() - { - return $this->stopPropagation; - } -} diff --git a/library/Zend/EventManager/EventInterface.php b/library/Zend/EventManager/EventInterface.php deleted file mode 100755 index c1d0de701..000000000 --- a/library/Zend/EventManager/EventInterface.php +++ /dev/null @@ -1,96 +0,0 @@ -setIdentifiers($identifiers); - } - - /** - * Set the event class to utilize - * - * @param string $class - * @return EventManager - */ - public function setEventClass($class) - { - $this->eventClass = $class; - return $this; - } - - /** - * Set shared event manager - * - * @param SharedEventManagerInterface $sharedEventManager - * @return EventManager - */ - public function setSharedManager(SharedEventManagerInterface $sharedEventManager) - { - $this->sharedManager = $sharedEventManager; - StaticEventManager::setInstance($sharedEventManager); - return $this; - } - - /** - * Remove any shared event manager currently attached - * - * @return void - */ - public function unsetSharedManager() - { - $this->sharedManager = false; - } - - /** - * Get shared event manager - * - * If one is not defined, but we have a static instance in - * StaticEventManager, that one will be used and set in this instance. - * - * If none is available in the StaticEventManager, a boolean false is - * returned. - * - * @return false|SharedEventManagerInterface - */ - public function getSharedManager() - { - // "false" means "I do not want a shared manager; don't try and fetch one" - if (false === $this->sharedManager - || $this->sharedManager instanceof SharedEventManagerInterface - ) { - return $this->sharedManager; - } - - if (!StaticEventManager::hasInstance()) { - return false; - } - - $this->sharedManager = StaticEventManager::getInstance(); - return $this->sharedManager; - } - - /** - * Get the identifier(s) for this EventManager - * - * @return array - */ - public function getIdentifiers() - { - return $this->identifiers; - } - - /** - * Set the identifiers (overrides any currently set identifiers) - * - * @param string|int|array|Traversable $identifiers - * @return EventManager Provides a fluent interface - */ - public function setIdentifiers($identifiers) - { - if (is_array($identifiers) || $identifiers instanceof Traversable) { - $this->identifiers = array_unique((array) $identifiers); - } elseif ($identifiers !== null) { - $this->identifiers = array($identifiers); - } - return $this; - } - - /** - * Add some identifier(s) (appends to any currently set identifiers) - * - * @param string|int|array|Traversable $identifiers - * @return EventManager Provides a fluent interface - */ - public function addIdentifiers($identifiers) - { - if (is_array($identifiers) || $identifiers instanceof Traversable) { - $this->identifiers = array_unique(array_merge($this->identifiers, (array) $identifiers)); - } elseif ($identifiers !== null) { - $this->identifiers = array_unique(array_merge($this->identifiers, array($identifiers))); - } - return $this; - } - - /** - * Trigger all listeners for a given event - * - * Can emulate triggerUntil() if the last argument provided is a callback. - * - * @param string $event - * @param string|object $target Object calling emit, or symbol describing target (such as static method name) - * @param array|ArrayAccess $argv Array of arguments; typically, should be associative - * @param null|callable $callback - * @return ResponseCollection All listener return values - * @throws Exception\InvalidCallbackException - */ - public function trigger($event, $target = null, $argv = array(), $callback = null) - { - if ($event instanceof EventInterface) { - $e = $event; - $event = $e->getName(); - $callback = $target; - } elseif ($target instanceof EventInterface) { - $e = $target; - $e->setName($event); - $callback = $argv; - } elseif ($argv instanceof EventInterface) { - $e = $argv; - $e->setName($event); - $e->setTarget($target); - } else { - $e = new $this->eventClass(); - $e->setName($event); - $e->setTarget($target); - $e->setParams($argv); - } - - if ($callback && !is_callable($callback)) { - throw new Exception\InvalidCallbackException('Invalid callback provided'); - } - - // Initial value of stop propagation flag should be false - $e->stopPropagation(false); - - return $this->triggerListeners($event, $e, $callback); - } - - /** - * Trigger listeners until return value of one causes a callback to - * evaluate to true - * - * Triggers listeners until the provided callback evaluates the return - * value of one as true, or until all listeners have been executed. - * - * @param string $event - * @param string|object $target Object calling emit, or symbol describing target (such as static method name) - * @param array|ArrayAccess $argv Array of arguments; typically, should be associative - * @param callable $callback - * @return ResponseCollection - * @throws Exception\InvalidCallbackException if invalid callable provided - */ - public function triggerUntil($event, $target, $argv = null, $callback = null) - { - if ($event instanceof EventInterface) { - $e = $event; - $event = $e->getName(); - $callback = $target; - } elseif ($target instanceof EventInterface) { - $e = $target; - $e->setName($event); - $callback = $argv; - } elseif ($argv instanceof EventInterface) { - $e = $argv; - $e->setName($event); - $e->setTarget($target); - } else { - $e = new $this->eventClass(); - $e->setName($event); - $e->setTarget($target); - $e->setParams($argv); - } - - if (!is_callable($callback)) { - throw new Exception\InvalidCallbackException('Invalid callback provided'); - } - - // Initial value of stop propagation flag should be false - $e->stopPropagation(false); - - return $this->triggerListeners($event, $e, $callback); - } - - /** - * Attach a listener to an event - * - * The first argument is the event, and the next argument describes a - * callback that will respond to that event. A CallbackHandler instance - * describing the event listener combination will be returned. - * - * The last argument indicates a priority at which the event should be - * executed. By default, this value is 1; however, you may set it for any - * integer value. Higher values have higher priority (i.e., execute first). - * - * You can specify "*" for the event name. In such cases, the listener will - * be triggered for every event. - * - * @param string|array|ListenerAggregateInterface $event An event or array of event names. If a ListenerAggregateInterface, proxies to {@link attachAggregate()}. - * @param callable|int $callback If string $event provided, expects PHP callback; for a ListenerAggregateInterface $event, this will be the priority - * @param int $priority If provided, the priority at which to register the callable - * @return CallbackHandler|mixed CallbackHandler if attaching callable (to allow later unsubscribe); mixed if attaching aggregate - * @throws Exception\InvalidArgumentException - */ - public function attach($event, $callback = null, $priority = 1) - { - // Proxy ListenerAggregateInterface arguments to attachAggregate() - if ($event instanceof ListenerAggregateInterface) { - return $this->attachAggregate($event, $callback); - } - - // Null callback is invalid - if (null === $callback) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects a callback; none provided', - __METHOD__ - )); - } - - // Array of events should be registered individually, and return an array of all listeners - if (is_array($event)) { - $listeners = array(); - foreach ($event as $name) { - $listeners[] = $this->attach($name, $callback, $priority); - } - return $listeners; - } - - // If we don't have a priority queue for the event yet, create one - if (empty($this->events[$event])) { - $this->events[$event] = new PriorityQueue(); - } - - // Create a callback handler, setting the event and priority in its metadata - $listener = new CallbackHandler($callback, array('event' => $event, 'priority' => $priority)); - - // Inject the callback handler into the queue - $this->events[$event]->insert($listener, $priority); - return $listener; - } - - /** - * Attach a listener aggregate - * - * Listener aggregates accept an EventManagerInterface instance, and call attach() - * one or more times, typically to attach to multiple events using local - * methods. - * - * @param ListenerAggregateInterface $aggregate - * @param int $priority If provided, a suggested priority for the aggregate to use - * @return mixed return value of {@link ListenerAggregateInterface::attach()} - */ - public function attachAggregate(ListenerAggregateInterface $aggregate, $priority = 1) - { - return $aggregate->attach($this, $priority); - } - - /** - * Unsubscribe a listener from an event - * - * @param CallbackHandler|ListenerAggregateInterface $listener - * @return bool Returns true if event and listener found, and unsubscribed; returns false if either event or listener not found - * @throws Exception\InvalidArgumentException if invalid listener provided - */ - public function detach($listener) - { - if ($listener instanceof ListenerAggregateInterface) { - return $this->detachAggregate($listener); - } - - if (!$listener instanceof CallbackHandler) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expected a ListenerAggregateInterface or CallbackHandler; received "%s"', - __METHOD__, - (is_object($listener) ? get_class($listener) : gettype($listener)) - )); - } - - $event = $listener->getMetadatum('event'); - if (!$event || empty($this->events[$event])) { - return false; - } - $return = $this->events[$event]->remove($listener); - if (!$return) { - return false; - } - if (!count($this->events[$event])) { - unset($this->events[$event]); - } - return true; - } - - /** - * Detach a listener aggregate - * - * Listener aggregates accept an EventManagerInterface instance, and call detach() - * of all previously attached listeners. - * - * @param ListenerAggregateInterface $aggregate - * @return mixed return value of {@link ListenerAggregateInterface::detach()} - */ - public function detachAggregate(ListenerAggregateInterface $aggregate) - { - return $aggregate->detach($this); - } - - /** - * Retrieve all registered events - * - * @return array - */ - public function getEvents() - { - return array_keys($this->events); - } - - /** - * Retrieve all listeners for a given event - * - * @param string $event - * @return PriorityQueue - */ - public function getListeners($event) - { - if (!array_key_exists($event, $this->events)) { - return new PriorityQueue(); - } - return $this->events[$event]; - } - - /** - * Clear all listeners for a given event - * - * @param string $event - * @return void - */ - public function clearListeners($event) - { - if (!empty($this->events[$event])) { - unset($this->events[$event]); - } - } - - /** - * Prepare arguments - * - * Use this method if you want to be able to modify arguments from within a - * listener. It returns an ArrayObject of the arguments, which may then be - * passed to trigger() or triggerUntil(). - * - * @param array $args - * @return ArrayObject - */ - public function prepareArgs(array $args) - { - return new ArrayObject($args); - } - - /** - * Trigger listeners - * - * Actual functionality for triggering listeners, to which both trigger() and triggerUntil() - * delegate. - * - * @param string $event Event name - * @param EventInterface $e - * @param null|callable $callback - * @return ResponseCollection - */ - protected function triggerListeners($event, EventInterface $e, $callback = null) - { - $responses = new ResponseCollection; - $listeners = $this->getListeners($event); - - // Add shared/wildcard listeners to the list of listeners, - // but don't modify the listeners object - $sharedListeners = $this->getSharedListeners($event); - $sharedWildcardListeners = $this->getSharedListeners('*'); - $wildcardListeners = $this->getListeners('*'); - if (count($sharedListeners) || count($sharedWildcardListeners) || count($wildcardListeners)) { - $listeners = clone $listeners; - - // Shared listeners on this specific event - $this->insertListeners($listeners, $sharedListeners); - - // Shared wildcard listeners - $this->insertListeners($listeners, $sharedWildcardListeners); - - // Add wildcard listeners - $this->insertListeners($listeners, $wildcardListeners); - } - - foreach ($listeners as $listener) { - $listenerCallback = $listener->getCallback(); - - // Trigger the listener's callback, and push its result onto the - // response collection - $responses->push(call_user_func($listenerCallback, $e)); - - // If the event was asked to stop propagating, do so - if ($e->propagationIsStopped()) { - $responses->setStopped(true); - break; - } - - // If the result causes our validation callback to return true, - // stop propagation - if ($callback && call_user_func($callback, $responses->last())) { - $responses->setStopped(true); - break; - } - } - - return $responses; - } - - /** - * Get list of all listeners attached to the shared event manager for - * identifiers registered by this instance - * - * @param string $event - * @return array - */ - protected function getSharedListeners($event) - { - if (!$sharedManager = $this->getSharedManager()) { - return array(); - } - - $identifiers = $this->getIdentifiers(); - //Add wildcard id to the search, if not already added - if (!in_array('*', $identifiers)) { - $identifiers[] = '*'; - } - $sharedListeners = array(); - - foreach ($identifiers as $id) { - if (!$listeners = $sharedManager->getListeners($id, $event)) { - continue; - } - - if (!is_array($listeners) && !($listeners instanceof Traversable)) { - continue; - } - - foreach ($listeners as $listener) { - if (!$listener instanceof CallbackHandler) { - continue; - } - $sharedListeners[] = $listener; - } - } - - return $sharedListeners; - } - - /** - * Add listeners to the master queue of listeners - * - * Used to inject shared listeners and wildcard listeners. - * - * @param PriorityQueue $masterListeners - * @param PriorityQueue $listeners - * @return void - */ - protected function insertListeners($masterListeners, $listeners) - { - foreach ($listeners as $listener) { - $priority = $listener->getMetadatum('priority'); - if (null === $priority) { - $priority = 1; - } elseif (is_array($priority)) { - // If we have an array, likely using PriorityQueue. Grab first - // element of the array, as that's the actual priority. - $priority = array_shift($priority); - } - $masterListeners->insert($listener, $priority); - } - } -} diff --git a/library/Zend/EventManager/EventManagerAwareInterface.php b/library/Zend/EventManager/EventManagerAwareInterface.php deleted file mode 100755 index a5c25f25f..000000000 --- a/library/Zend/EventManager/EventManagerAwareInterface.php +++ /dev/null @@ -1,24 +0,0 @@ -eventIdentifier property. - * - * @param EventManagerInterface $events - * @return mixed - */ - public function setEventManager(EventManagerInterface $events) - { - $identifiers = array(__CLASS__, get_class($this)); - if (isset($this->eventIdentifier)) { - if ((is_string($this->eventIdentifier)) - || (is_array($this->eventIdentifier)) - || ($this->eventIdentifier instanceof Traversable) - ) { - $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier)); - } elseif (is_object($this->eventIdentifier)) { - $identifiers[] = $this->eventIdentifier; - } - // silently ignore invalid eventIdentifier types - } - $events->setIdentifiers($identifiers); - $this->events = $events; - if (method_exists($this, 'attachDefaultListeners')) { - $this->attachDefaultListeners(); - } - return $this; - } - - /** - * Retrieve the event manager - * - * Lazy-loads an EventManager instance if none registered. - * - * @return EventManagerInterface - */ - public function getEventManager() - { - if (!$this->events instanceof EventManagerInterface) { - $this->setEventManager(new EventManager()); - } - return $this->events; - } -} diff --git a/library/Zend/EventManager/EventManagerInterface.php b/library/Zend/EventManager/EventManagerInterface.php deleted file mode 100755 index 6a2129f93..000000000 --- a/library/Zend/EventManager/EventManagerInterface.php +++ /dev/null @@ -1,144 +0,0 @@ -setExtractFlags(self::EXTR_BOTH); - - // Iterate and remove any matches - $removed = false; - $items = array(); - $this->rewind(); - while (!$this->isEmpty()) { - $item = $this->extract(); - if ($item['data'] === $datum) { - $removed = true; - continue; - } - $items[] = $item; - } - - // Repopulate - foreach ($items as $item) { - $this->insert($item['data'], $item['priority']); - } - - $this->setExtractFlags(self::EXTR_DATA); - return $removed; - } - - /** - * Iterate the next filter in the chain - * - * Iterates and calls the next filter in the chain. - * - * @param mixed $context - * @param array $params - * @param FilterIterator $chain - * @return mixed - */ - public function next($context = null, array $params = array(), $chain = null) - { - if (empty($context) || $chain->isEmpty()) { - return; - } - - $next = $this->extract(); - if (!$next instanceof CallbackHandler) { - return; - } - - $return = call_user_func($next->getCallback(), $context, $params, $chain); - return $return; - } -} diff --git a/library/Zend/EventManager/FilterChain.php b/library/Zend/EventManager/FilterChain.php deleted file mode 100755 index d79a5de97..000000000 --- a/library/Zend/EventManager/FilterChain.php +++ /dev/null @@ -1,120 +0,0 @@ -filters = new Filter\FilterIterator(); - } - - /** - * Apply the filters - * - * Begins iteration of the filters. - * - * @param mixed $context Object under observation - * @param mixed $argv Associative array of arguments - * @return mixed - */ - public function run($context, array $argv = array()) - { - $chain = clone $this->getFilters(); - - if ($chain->isEmpty()) { - return; - } - - $next = $chain->extract(); - if (!$next instanceof CallbackHandler) { - return; - } - - return call_user_func($next->getCallback(), $context, $argv, $chain); - } - - /** - * Connect a filter to the chain - * - * @param callable $callback PHP Callback - * @param int $priority Priority in the queue at which to execute; defaults to 1 (higher numbers == higher priority) - * @return CallbackHandler (to allow later unsubscribe) - * @throws Exception\InvalidCallbackException - */ - public function attach($callback, $priority = 1) - { - if (empty($callback)) { - throw new Exception\InvalidCallbackException('No callback provided'); - } - $filter = new CallbackHandler($callback, array('priority' => $priority)); - $this->filters->insert($filter, $priority); - return $filter; - } - - /** - * Detach a filter from the chain - * - * @param CallbackHandler $filter - * @return bool Returns true if filter found and unsubscribed; returns false otherwise - */ - public function detach(CallbackHandler $filter) - { - return $this->filters->remove($filter); - } - - /** - * Retrieve all filters - * - * @return Filter\FilterIterator - */ - public function getFilters() - { - return $this->filters; - } - - /** - * Clear all filters - * - * @return void - */ - public function clearFilters() - { - $this->filters = new Filter\FilterIterator(); - } - - /** - * Return current responses - * - * Only available while the chain is still being iterated. Returns the - * current ResponseCollection. - * - * @return null|ResponseCollection - */ - public function getResponses() - { - return null; - } -} diff --git a/library/Zend/EventManager/GlobalEventManager.php b/library/Zend/EventManager/GlobalEventManager.php deleted file mode 100755 index 4bac5b574..000000000 --- a/library/Zend/EventManager/GlobalEventManager.php +++ /dev/null @@ -1,135 +0,0 @@ -trigger($event, $context, $argv); - } - - /** - * Trigger listeners until return value of one causes a callback to evaluate - * to true. - * - * @param string $event - * @param string|object $context - * @param array|object $argv - * @param callable $callback - * @return ResponseCollection - */ - public static function triggerUntil($event, $context, $argv, $callback) - { - return static::getEventCollection()->triggerUntil($event, $context, $argv, $callback); - } - - /** - * Attach a listener to an event - * - * @param string $event - * @param callable $callback - * @param int $priority - * @return CallbackHandler - */ - public static function attach($event, $callback, $priority = 1) - { - return static::getEventCollection()->attach($event, $callback, $priority); - } - - /** - * Detach a callback from a listener - * - * @param CallbackHandler $listener - * @return bool - */ - public static function detach(CallbackHandler $listener) - { - return static::getEventCollection()->detach($listener); - } - - /** - * Retrieve list of events this object manages - * - * @return array - */ - public static function getEvents() - { - return static::getEventCollection()->getEvents(); - } - - /** - * Retrieve all listeners for a given event - * - * @param string $event - * @return PriorityQueue|array - */ - public static function getListeners($event) - { - return static::getEventCollection()->getListeners($event); - } - - /** - * Clear all listeners for a given event - * - * @param string $event - * @return void - */ - public static function clearListeners($event) - { - static::getEventCollection()->clearListeners($event); - } -} diff --git a/library/Zend/EventManager/ListenerAggregateInterface.php b/library/Zend/EventManager/ListenerAggregateInterface.php deleted file mode 100755 index cd0eef4ce..000000000 --- a/library/Zend/EventManager/ListenerAggregateInterface.php +++ /dev/null @@ -1,42 +0,0 @@ -listeners as $index => $callback) { - if ($events->detach($callback)) { - unset($this->listeners[$index]); - } - } - } -} diff --git a/library/Zend/EventManager/ProvidesEvents.php b/library/Zend/EventManager/ProvidesEvents.php deleted file mode 100755 index 0cfeb1975..000000000 --- a/library/Zend/EventManager/ProvidesEvents.php +++ /dev/null @@ -1,23 +0,0 @@ -stopped; - } - - /** - * Mark the collection as stopped (or its opposite) - * - * @param bool $flag - * @return ResponseCollection - */ - public function setStopped($flag) - { - $this->stopped = (bool) $flag; - return $this; - } - - /** - * Convenient access to the first handler return value. - * - * @return mixed The first handler return value - */ - public function first() - { - return parent::bottom(); - } - - /** - * Convenient access to the last handler return value. - * - * If the collection is empty, returns null. Otherwise, returns value - * returned by last handler. - * - * @return mixed The last handler return value - */ - public function last() - { - if (count($this) === 0) { - return null; - } - return parent::top(); - } - - /** - * Check if any of the responses match the given value. - * - * @param mixed $value The value to look for among responses - * @return bool - */ - public function contains($value) - { - foreach ($this as $response) { - if ($response === $value) { - return true; - } - } - return false; - } -} diff --git a/library/Zend/EventManager/SharedEventAggregateAwareInterface.php b/library/Zend/EventManager/SharedEventAggregateAwareInterface.php deleted file mode 100755 index 4cda8bc12..000000000 --- a/library/Zend/EventManager/SharedEventAggregateAwareInterface.php +++ /dev/null @@ -1,33 +0,0 @@ - - * $sharedEventManager = new SharedEventManager(); - * $sharedEventManager->attach( - * array('My\Resource\AbstractResource', 'My\Resource\EntityResource'), - * 'getAll', - * function ($e) use ($cache) { - * if (!$id = $e->getParam('id', false)) { - * return; - * } - * if (!$data = $cache->load(get_class($resource) . '::getOne::' . $id )) { - * return; - * } - * return $data; - * } - * ); - * - * - * @param string|array $id Identifier(s) for event emitting component(s) - * @param string $event - * @param callable $callback PHP Callback - * @param int $priority Priority at which listener should execute - * @return CallbackHandler|array Either CallbackHandler or array of CallbackHandlers - */ - public function attach($id, $event, $callback, $priority = 1) - { - $ids = (array) $id; - $listeners = array(); - foreach ($ids as $id) { - if (!array_key_exists($id, $this->identifiers)) { - $this->identifiers[$id] = new EventManager($id); - } - $listeners[] = $this->identifiers[$id]->attach($event, $callback, $priority); - } - if (count($listeners) > 1) { - return $listeners; - } - return $listeners[0]; - } - - /** - * Attach a listener aggregate - * - * Listener aggregates accept an EventManagerInterface instance, and call attachShared() - * one or more times, typically to attach to multiple events using local - * methods. - * - * @param SharedListenerAggregateInterface $aggregate - * @param int $priority If provided, a suggested priority for the aggregate to use - * @return mixed return value of {@link ListenerAggregateInterface::attachShared()} - */ - public function attachAggregate(SharedListenerAggregateInterface $aggregate, $priority = 1) - { - return $aggregate->attachShared($this, $priority); - } - - /** - * Detach a listener from an event offered by a given resource - * - * @param string|int $id - * @param CallbackHandler $listener - * @return bool Returns true if event and listener found, and unsubscribed; returns false if either event or listener not found - */ - public function detach($id, CallbackHandler $listener) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - return $this->identifiers[$id]->detach($listener); - } - - /** - * Detach a listener aggregate - * - * Listener aggregates accept a SharedEventManagerInterface instance, and call detachShared() - * of all previously attached listeners. - * - * @param SharedListenerAggregateInterface $aggregate - * @return mixed return value of {@link SharedListenerAggregateInterface::detachShared()} - */ - public function detachAggregate(SharedListenerAggregateInterface $aggregate) - { - return $aggregate->detachShared($this); - } - - /** - * Retrieve all registered events for a given resource - * - * @param string|int $id - * @return array - */ - public function getEvents($id) - { - if (!array_key_exists($id, $this->identifiers)) { - //Check if there are any id wildcards listeners - if ('*' != $id && array_key_exists('*', $this->identifiers)) { - return $this->identifiers['*']->getEvents(); - } - return false; - } - return $this->identifiers[$id]->getEvents(); - } - - /** - * Retrieve all listeners for a given identifier and event - * - * @param string|int $id - * @param string|int $event - * @return false|PriorityQueue - */ - public function getListeners($id, $event) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - return $this->identifiers[$id]->getListeners($event); - } - - /** - * Clear all listeners for a given identifier, optionally for a specific event - * - * @param string|int $id - * @param null|string $event - * @return bool - */ - public function clearListeners($id, $event = null) - { - if (!array_key_exists($id, $this->identifiers)) { - return false; - } - - if (null === $event) { - unset($this->identifiers[$id]); - return true; - } - - return $this->identifiers[$id]->clearListeners($event); - } -} diff --git a/library/Zend/EventManager/SharedEventManagerAwareInterface.php b/library/Zend/EventManager/SharedEventManagerAwareInterface.php deleted file mode 100755 index 09e5c98c1..000000000 --- a/library/Zend/EventManager/SharedEventManagerAwareInterface.php +++ /dev/null @@ -1,38 +0,0 @@ -=5.3.23", - "zendframework/zend-stdlib": "self.version" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Feed/CONTRIBUTING.md b/library/Zend/Feed/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Feed/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Feed/Exception/BadMethodCallException.php b/library/Zend/Feed/Exception/BadMethodCallException.php deleted file mode 100755 index 107c3e64e..000000000 --- a/library/Zend/Feed/Exception/BadMethodCallException.php +++ /dev/null @@ -1,16 +0,0 @@ -setOptions($options); - } - } - - /** - * Process any injected configuration options - * - * @param array|Traversable $options Options array or Traversable object - * @return AbstractCallback - * @throws Exception\InvalidArgumentException - */ - public function setOptions($options) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (!is_array($options)) { - throw new Exception\InvalidArgumentException('Array or Traversable object' - . 'expected, got ' . gettype($options)); - } - - if (is_array($options)) { - $this->setOptions($options); - } - - if (array_key_exists('storage', $options)) { - $this->setStorage($options['storage']); - } - return $this; - } - - /** - * Send the response, including all headers. - * If you wish to handle this via Zend\Http, use the getter methods - * to retrieve any data needed to be set on your HTTP Response object, or - * simply give this object the HTTP Response instance to work with for you! - * - * @return void - */ - public function sendResponse() - { - $this->getHttpResponse()->send(); - } - - /** - * Sets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used - * to background save any verification tokens associated with a subscription - * or other. - * - * @param Model\SubscriptionPersistenceInterface $storage - * @return AbstractCallback - */ - public function setStorage(Model\SubscriptionPersistenceInterface $storage) - { - $this->storage = $storage; - return $this; - } - - /** - * Gets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used - * to background save any verification tokens associated with a subscription - * or other. - * - * @return Model\SubscriptionPersistenceInterface - * @throws Exception\RuntimeException - */ - public function getStorage() - { - if ($this->storage === null) { - throw new Exception\RuntimeException('No storage object has been' - . ' set that subclasses Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence'); - } - return $this->storage; - } - - /** - * An instance of a class handling Http Responses. This is implemented in - * Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with - * (i.e. not inherited from) Zend\Controller\Response\Http. - * - * @param HttpResponse|PhpResponse $httpResponse - * @return AbstractCallback - * @throws Exception\InvalidArgumentException - */ - public function setHttpResponse($httpResponse) - { - if (!$httpResponse instanceof HttpResponse && !$httpResponse instanceof PhpResponse) { - throw new Exception\InvalidArgumentException('HTTP Response object must' - . ' implement one of Zend\Feed\Pubsubhubbub\HttpResponse or' - . ' Zend\Http\PhpEnvironment\Response'); - } - $this->httpResponse = $httpResponse; - return $this; - } - - /** - * An instance of a class handling Http Responses. This is implemented in - * Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with - * (i.e. not inherited from) Zend\Controller\Response\Http. - * - * @return HttpResponse|PhpResponse - */ - public function getHttpResponse() - { - if ($this->httpResponse === null) { - $this->httpResponse = new HttpResponse; - } - return $this->httpResponse; - } - - /** - * Sets the number of Subscribers for which any updates are on behalf of. - * In other words, is this class serving one or more subscribers? How many? - * Defaults to 1 if left unchanged. - * - * @param string|int $count - * @return AbstractCallback - * @throws Exception\InvalidArgumentException - */ - public function setSubscriberCount($count) - { - $count = intval($count); - if ($count <= 0) { - throw new Exception\InvalidArgumentException('Subscriber count must be' - . ' greater than zero'); - } - $this->subscriberCount = $count; - return $this; - } - - /** - * Gets the number of Subscribers for which any updates are on behalf of. - * In other words, is this class serving one or more subscribers? How many? - * - * @return int - */ - public function getSubscriberCount() - { - return $this->subscriberCount; - } - - /** - * Attempt to detect the callback URL (specifically the path forward) - * @return string - */ - protected function _detectCallbackUrl() - { - $callbackUrl = ''; - if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) { - $callbackUrl = $_SERVER['HTTP_X_ORIGINAL_URL']; - } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) { - $callbackUrl = $_SERVER['HTTP_X_REWRITE_URL']; - } elseif (isset($_SERVER['REQUEST_URI'])) { - $callbackUrl = $_SERVER['REQUEST_URI']; - $scheme = 'http'; - if ($_SERVER['HTTPS'] == 'on') { - $scheme = 'https'; - } - $schemeAndHttpHost = $scheme . '://' . $this->_getHttpHost(); - if (strpos($callbackUrl, $schemeAndHttpHost) === 0) { - $callbackUrl = substr($callbackUrl, strlen($schemeAndHttpHost)); - } - } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { - $callbackUrl= $_SERVER['ORIG_PATH_INFO']; - if (!empty($_SERVER['QUERY_STRING'])) { - $callbackUrl .= '?' . $_SERVER['QUERY_STRING']; - } - } - return $callbackUrl; - } - - /** - * Get the HTTP host - * - * @return string - */ - protected function _getHttpHost() - { - if (!empty($_SERVER['HTTP_HOST'])) { - return $_SERVER['HTTP_HOST']; - } - $scheme = 'http'; - if ($_SERVER['HTTPS'] == 'on') { - $scheme = 'https'; - } - $name = $_SERVER['SERVER_NAME']; - $port = $_SERVER['SERVER_PORT']; - if (($scheme == 'http' && $port == 80) - || ($scheme == 'https' && $port == 443) - ) { - return $name; - } - - return $name . ':' . $port; - } - - /** - * Retrieve a Header value from either $_SERVER or Apache - * - * @param string $header - * @return bool|string - */ - protected function _getHeader($header) - { - $temp = strtoupper(str_replace('-', '_', $header)); - if (!empty($_SERVER[$temp])) { - return $_SERVER[$temp]; - } - $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header)); - if (!empty($_SERVER[$temp])) { - return $_SERVER[$temp]; - } - if (function_exists('apache_request_headers')) { - $headers = apache_request_headers(); - if (!empty($headers[$header])) { - return $headers[$header]; - } - } - return false; - } - - /** - * Return the raw body of the request - * - * @return string|false Raw body, or false if not present - */ - protected function _getRawBody() - { - $body = file_get_contents('php://input'); - if (strlen(trim($body)) == 0 && isset($GLOBALS['HTTP_RAW_POST_DATA'])) { - $body = $GLOBALS['HTTP_RAW_POST_DATA']; - } - if (strlen(trim($body)) > 0) { - return $body; - } - return false; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/CallbackInterface.php b/library/Zend/Feed/PubSubHubbub/CallbackInterface.php deleted file mode 100755 index 8873c3db4..000000000 --- a/library/Zend/Feed/PubSubHubbub/CallbackInterface.php +++ /dev/null @@ -1,51 +0,0 @@ -sendHeaders(); - echo $this->getContent(); - } - - /** - * Send all headers - * - * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code} - * has been specified, it is sent with the first header. - * - * @return void - */ - public function sendHeaders() - { - if (count($this->headers) || (200 != $this->statusCode)) { - $this->canSendHeaders(true); - } elseif (200 == $this->statusCode) { - return; - } - $httpCodeSent = false; - foreach ($this->headers as $header) { - if (!$httpCodeSent && $this->statusCode) { - header($header['name'] . ': ' . $header['value'], $header['replace'], $this->statusCode); - $httpCodeSent = true; - } else { - header($header['name'] . ': ' . $header['value'], $header['replace']); - } - } - if (!$httpCodeSent) { - header('HTTP/1.1 ' . $this->statusCode); - } - } - - /** - * Set a header - * - * If $replace is true, replaces any headers already defined with that - * $name. - * - * @param string $name - * @param string $value - * @param bool $replace - * @return \Zend\Feed\PubSubHubbub\HttpResponse - */ - public function setHeader($name, $value, $replace = false) - { - $name = $this->_normalizeHeader($name); - $value = (string) $value; - if ($replace) { - foreach ($this->headers as $key => $header) { - if ($name == $header['name']) { - unset($this->headers[$key]); - } - } - } - $this->headers[] = array( - 'name' => $name, - 'value' => $value, - 'replace' => $replace, - ); - - return $this; - } - - /** - * Check if a specific Header is set and return its value - * - * @param string $name - * @return string|null - */ - public function getHeader($name) - { - $name = $this->_normalizeHeader($name); - foreach ($this->headers as $header) { - if ($header['name'] == $name) { - return $header['value']; - } - } - } - - /** - * Return array of headers; see {@link $headers} for format - * - * @return array - */ - public function getHeaders() - { - return $this->headers; - } - - /** - * Can we send headers? - * - * @param bool $throw Whether or not to throw an exception if headers have been sent; defaults to false - * @return HttpResponse - * @throws Exception\RuntimeException - */ - public function canSendHeaders($throw = false) - { - $ok = headers_sent($file, $line); - if ($ok && $throw) { - throw new Exception\RuntimeException('Cannot send headers; headers already sent in ' . $file . ', line ' . $line); - } - return !$ok; - } - - /** - * Set HTTP response code to use with headers - * - * @param int $code - * @return HttpResponse - * @throws Exception\InvalidArgumentException - */ - public function setStatusCode($code) - { - if (!is_int($code) || (100 > $code) || (599 < $code)) { - throw new Exception\InvalidArgumentException('Invalid HTTP response' - . ' code:' . $code); - } - $this->statusCode = $code; - return $this; - } - - /** - * Retrieve HTTP response code - * - * @return int - */ - public function getStatusCode() - { - return $this->statusCode; - } - - /** - * Set body content - * - * @param string $content - * @return \Zend\Feed\PubSubHubbub\HttpResponse - */ - public function setContent($content) - { - $this->content = (string) $content; - $this->setHeader('content-length', strlen($content)); - return $this; - } - - /** - * Return the body content - * - * @return string - */ - public function getContent() - { - return $this->content; - } - - /** - * Normalizes a header name to X-Capitalized-Names - * - * @param string $name - * @return string - */ - protected function _normalizeHeader($name) - { - $filtered = str_replace(array('-', '_'), ' ', (string) $name); - $filtered = ucwords(strtolower($filtered)); - $filtered = str_replace(' ', '-', $filtered); - return $filtered; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Model/AbstractModel.php b/library/Zend/Feed/PubSubHubbub/Model/AbstractModel.php deleted file mode 100755 index 92e688133..000000000 --- a/library/Zend/Feed/PubSubHubbub/Model/AbstractModel.php +++ /dev/null @@ -1,39 +0,0 @@ -db = new TableGateway($table, null); - } else { - $this->db = $tableGateway; - } - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Model/Subscription.php b/library/Zend/Feed/PubSubHubbub/Model/Subscription.php deleted file mode 100755 index 9571106a4..000000000 --- a/library/Zend/Feed/PubSubHubbub/Model/Subscription.php +++ /dev/null @@ -1,142 +0,0 @@ -db->select(array('id' => $data['id'])); - if ($result && (0 < count($result))) { - $data['created_time'] = $result->current()->created_time; - $now = $this->getNow(); - if (array_key_exists('lease_seconds', $data) - && $data['lease_seconds'] - ) { - $data['expiration_time'] = $now->add(new DateInterval('PT' . $data['lease_seconds'] . 'S')) - ->format('Y-m-d H:i:s'); - } - $this->db->update( - $data, - array('id' => $data['id']) - ); - return false; - } - - $this->db->insert($data); - return true; - } - - /** - * Get subscription by ID/key - * - * @param string $key - * @return array - * @throws PubSubHubbub\Exception\InvalidArgumentException - */ - public function getSubscription($key) - { - if (empty($key) || !is_string($key)) { - throw new PubSubHubbub\Exception\InvalidArgumentException('Invalid parameter "key"' - .' of "' . $key . '" must be a non-empty string'); - } - $result = $this->db->select(array('id' => $key)); - if (count($result)) { - return $result->current()->getArrayCopy(); - } - return false; - } - - /** - * Determine if a subscription matching the key exists - * - * @param string $key - * @return bool - * @throws PubSubHubbub\Exception\InvalidArgumentException - */ - public function hasSubscription($key) - { - if (empty($key) || !is_string($key)) { - throw new PubSubHubbub\Exception\InvalidArgumentException('Invalid parameter "key"' - .' of "' . $key . '" must be a non-empty string'); - } - $result = $this->db->select(array('id' => $key)); - if (count($result)) { - return true; - } - return false; - } - - /** - * Delete a subscription - * - * @param string $key - * @return bool - */ - public function deleteSubscription($key) - { - $result = $this->db->select(array('id' => $key)); - if (count($result)) { - $this->db->delete( - array('id' => $key) - ); - return true; - } - return false; - } - - /** - * Get a new DateTime or the one injected for testing - * - * @return DateTime - */ - public function getNow() - { - if (null === $this->now) { - return new DateTime(); - } - return $this->now; - } - - /** - * Set a DateTime instance for assisting with unit testing - * - * @param DateTime $now - * @return Subscription - */ - public function setNow(DateTime $now) - { - $this->now = $now; - return $this; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Model/SubscriptionPersistenceInterface.php b/library/Zend/Feed/PubSubHubbub/Model/SubscriptionPersistenceInterface.php deleted file mode 100755 index ccd272329..000000000 --- a/library/Zend/Feed/PubSubHubbub/Model/SubscriptionPersistenceInterface.php +++ /dev/null @@ -1,45 +0,0 @@ -getHubs(); - } - - /** - * Allows the external environment to make ZendOAuth use a specific - * Client instance. - * - * @param Http\Client $httpClient - * @return void - */ - public static function setHttpClient(Http\Client $httpClient) - { - static::$httpClient = $httpClient; - } - - /** - * Return the singleton instance of the HTTP Client. Note that - * the instance is reset and cleared of previous parameters GET/POST. - * Headers are NOT reset but handled by this component if applicable. - * - * @return Http\Client - */ - public static function getHttpClient() - { - if (!isset(static::$httpClient)) { - static::$httpClient = new Http\Client; - } else { - static::$httpClient->resetParameters(); - } - return static::$httpClient; - } - - /** - * Simple mechanism to delete the entire singleton HTTP Client instance - * which forces a new instantiation for subsequent requests. - * - * @return void - */ - public static function clearHttpClient() - { - static::$httpClient = null; - } - - /** - * Set the Escaper instance - * - * If null, resets the instance - * - * @param null|Escaper $escaper - */ - public static function setEscaper(Escaper $escaper = null) - { - static::$escaper = $escaper; - } - - /** - * Get the Escaper instance - * - * If none registered, lazy-loads an instance. - * - * @return Escaper - */ - public static function getEscaper() - { - if (null === static::$escaper) { - static::setEscaper(new Escaper()); - } - return static::$escaper; - } - - /** - * RFC 3986 safe url encoding method - * - * @param string $string - * @return string - */ - public static function urlencode($string) - { - $escaper = static::getEscaper(); - $rawencoded = $escaper->escapeUrl($string); - $rfcencoded = str_replace('%7E', '~', $rawencoded); - return $rfcencoded; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Publisher.php b/library/Zend/Feed/PubSubHubbub/Publisher.php deleted file mode 100755 index 916ffcad5..000000000 --- a/library/Zend/Feed/PubSubHubbub/Publisher.php +++ /dev/null @@ -1,397 +0,0 @@ -setOptions($options); - } - } - - /** - * Process any injected configuration options - * - * @param array|Traversable $options Options array or Traversable object - * @return Publisher - * @throws Exception\InvalidArgumentException - */ - public function setOptions($options) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (!is_array($options)) { - throw new Exception\InvalidArgumentException('Array or Traversable object' - . 'expected, got ' . gettype($options)); - } - if (array_key_exists('hubUrls', $options)) { - $this->addHubUrls($options['hubUrls']); - } - if (array_key_exists('updatedTopicUrls', $options)) { - $this->addUpdatedTopicUrls($options['updatedTopicUrls']); - } - if (array_key_exists('parameters', $options)) { - $this->setParameters($options['parameters']); - } - return $this; - } - - /** - * Add a Hub Server URL supported by Publisher - * - * @param string $url - * @return Publisher - * @throws Exception\InvalidArgumentException - */ - public function addHubUrl($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - . ' of "' . $url . '" must be a non-empty string and a valid' - . 'URL'); - } - $this->hubUrls[] = $url; - return $this; - } - - /** - * Add an array of Hub Server URLs supported by Publisher - * - * @param array $urls - * @return Publisher - */ - public function addHubUrls(array $urls) - { - foreach ($urls as $url) { - $this->addHubUrl($url); - } - return $this; - } - - /** - * Remove a Hub Server URL - * - * @param string $url - * @return Publisher - */ - public function removeHubUrl($url) - { - if (!in_array($url, $this->getHubUrls())) { - return $this; - } - $key = array_search($url, $this->hubUrls); - unset($this->hubUrls[$key]); - return $this; - } - - /** - * Return an array of unique Hub Server URLs currently available - * - * @return array - */ - public function getHubUrls() - { - $this->hubUrls = array_unique($this->hubUrls); - return $this->hubUrls; - } - - /** - * Add a URL to a topic (Atom or RSS feed) which has been updated - * - * @param string $url - * @return Publisher - * @throws Exception\InvalidArgumentException - */ - public function addUpdatedTopicUrl($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - . ' of "' . $url . '" must be a non-empty string and a valid' - . 'URL'); - } - $this->updatedTopicUrls[] = $url; - return $this; - } - - /** - * Add an array of Topic URLs which have been updated - * - * @param array $urls - * @return Publisher - */ - public function addUpdatedTopicUrls(array $urls) - { - foreach ($urls as $url) { - $this->addUpdatedTopicUrl($url); - } - return $this; - } - - /** - * Remove an updated topic URL - * - * @param string $url - * @return Publisher - */ - public function removeUpdatedTopicUrl($url) - { - if (!in_array($url, $this->getUpdatedTopicUrls())) { - return $this; - } - $key = array_search($url, $this->updatedTopicUrls); - unset($this->updatedTopicUrls[$key]); - return $this; - } - - /** - * Return an array of unique updated topic URLs currently available - * - * @return array - */ - public function getUpdatedTopicUrls() - { - $this->updatedTopicUrls = array_unique($this->updatedTopicUrls); - return $this->updatedTopicUrls; - } - - /** - * Notifies a single Hub Server URL of changes - * - * @param string $url The Hub Server's URL - * @return void - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public function notifyHub($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - . ' of "' . $url . '" must be a non-empty string and a valid' - . 'URL'); - } - $client = $this->_getHttpClient(); - $client->setUri($url); - $response = $client->getResponse(); - if ($response->getStatusCode() !== 204) { - throw new Exception\RuntimeException('Notification to Hub Server ' - . 'at "' . $url . '" appears to have failed with a status code of "' - . $response->getStatusCode() . '" and message "' - . $response->getContent() . '"'); - } - } - - /** - * Notifies all Hub Server URLs of changes - * - * If a Hub notification fails, certain data will be retained in an - * an array retrieved using getErrors(), if a failure occurs for any Hubs - * the isSuccess() check will return FALSE. This method is designed not - * to needlessly fail with an Exception/Error unless from Zend\Http\Client. - * - * @return void - * @throws Exception\RuntimeException - */ - public function notifyAll() - { - $client = $this->_getHttpClient(); - $hubs = $this->getHubUrls(); - if (empty($hubs)) { - throw new Exception\RuntimeException('No Hub Server URLs' - . ' have been set so no notifications can be sent'); - } - $this->errors = array(); - foreach ($hubs as $url) { - $client->setUri($url); - $response = $client->getResponse(); - if ($response->getStatusCode() !== 204) { - $this->errors[] = array( - 'response' => $response, - 'hubUrl' => $url - ); - } - } - } - - /** - * Add an optional parameter to the update notification requests - * - * @param string $name - * @param string|null $value - * @return Publisher - * @throws Exception\InvalidArgumentException - */ - public function setParameter($name, $value = null) - { - if (is_array($name)) { - $this->setParameters($name); - return $this; - } - if (empty($name) || !is_string($name)) { - throw new Exception\InvalidArgumentException('Invalid parameter "name"' - . ' of "' . $name . '" must be a non-empty string'); - } - if ($value === null) { - $this->removeParameter($name); - return $this; - } - if (empty($value) || (!is_string($value) && $value !== null)) { - throw new Exception\InvalidArgumentException('Invalid parameter "value"' - . ' of "' . $value . '" must be a non-empty string'); - } - $this->parameters[$name] = $value; - return $this; - } - - /** - * Add an optional parameter to the update notification requests - * - * @param array $parameters - * @return Publisher - */ - public function setParameters(array $parameters) - { - foreach ($parameters as $name => $value) { - $this->setParameter($name, $value); - } - return $this; - } - - /** - * Remove an optional parameter for the notification requests - * - * @param string $name - * @return Publisher - * @throws Exception\InvalidArgumentException - */ - public function removeParameter($name) - { - if (empty($name) || !is_string($name)) { - throw new Exception\InvalidArgumentException('Invalid parameter "name"' - . ' of "' . $name . '" must be a non-empty string'); - } - if (array_key_exists($name, $this->parameters)) { - unset($this->parameters[$name]); - } - return $this; - } - - /** - * Return an array of optional parameters for notification requests - * - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * Returns a boolean indicator of whether the notifications to Hub - * Servers were ALL successful. If even one failed, FALSE is returned. - * - * @return bool - */ - public function isSuccess() - { - return !(count($this->errors) != 0); - } - - /** - * Return an array of errors met from any failures, including keys: - * 'response' => the Zend\Http\Response object from the failure - * 'hubUrl' => the URL of the Hub Server whose notification failed - * - * @return array - */ - public function getErrors() - { - return $this->errors; - } - - /** - * Get a basic prepared HTTP client for use - * - * @return \Zend\Http\Client - * @throws Exception\RuntimeException - */ - protected function _getHttpClient() - { - $client = PubSubHubbub::getHttpClient(); - $client->setMethod(HttpRequest::METHOD_POST); - $client->setOptions(array( - 'useragent' => 'Zend_Feed_Pubsubhubbub_Publisher/' . Version::VERSION, - )); - $params = array(); - $params[] = 'hub.mode=publish'; - $topics = $this->getUpdatedTopicUrls(); - if (empty($topics)) { - throw new Exception\RuntimeException('No updated topic URLs' - . ' have been set'); - } - foreach ($topics as $topicUrl) { - $params[] = 'hub.url=' . urlencode($topicUrl); - } - $optParams = $this->getParameters(); - foreach ($optParams as $name => $value) { - $params[] = urlencode($name) . '=' . urlencode($value); - } - $paramString = implode('&', $params); - $client->setRawBody($paramString); - return $client; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Subscriber.php b/library/Zend/Feed/PubSubHubbub/Subscriber.php deleted file mode 100755 index 265fe776b..000000000 --- a/library/Zend/Feed/PubSubHubbub/Subscriber.php +++ /dev/null @@ -1,837 +0,0 @@ -setOptions($options); - } - } - - /** - * Process any injected configuration options - * - * @param array|Traversable $options - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function setOptions($options) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (!is_array($options)) { - throw new Exception\InvalidArgumentException('Array or Traversable object' - . 'expected, got ' . gettype($options)); - } - if (array_key_exists('hubUrls', $options)) { - $this->addHubUrls($options['hubUrls']); - } - if (array_key_exists('callbackUrl', $options)) { - $this->setCallbackUrl($options['callbackUrl']); - } - if (array_key_exists('topicUrl', $options)) { - $this->setTopicUrl($options['topicUrl']); - } - if (array_key_exists('storage', $options)) { - $this->setStorage($options['storage']); - } - if (array_key_exists('leaseSeconds', $options)) { - $this->setLeaseSeconds($options['leaseSeconds']); - } - if (array_key_exists('parameters', $options)) { - $this->setParameters($options['parameters']); - } - if (array_key_exists('authentications', $options)) { - $this->addAuthentications($options['authentications']); - } - if (array_key_exists('usePathParameter', $options)) { - $this->usePathParameter($options['usePathParameter']); - } - if (array_key_exists('preferredVerificationMode', $options)) { - $this->setPreferredVerificationMode( - $options['preferredVerificationMode'] - ); - } - return $this; - } - - /** - * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe - * event will relate - * - * @param string $url - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function setTopicUrl($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - .' of "' . $url . '" must be a non-empty string and a valid' - .' URL'); - } - $this->topicUrl = $url; - return $this; - } - - /** - * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe - * event will relate - * - * @return string - * @throws Exception\RuntimeException - */ - public function getTopicUrl() - { - if (empty($this->topicUrl)) { - throw new Exception\RuntimeException('A valid Topic (RSS or Atom' - . ' feed) URL MUST be set before attempting any operation'); - } - return $this->topicUrl; - } - - /** - * Set the number of seconds for which any subscription will remain valid - * - * @param int $seconds - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function setLeaseSeconds($seconds) - { - $seconds = intval($seconds); - if ($seconds <= 0) { - throw new Exception\InvalidArgumentException('Expected lease seconds' - . ' must be an integer greater than zero'); - } - $this->leaseSeconds = $seconds; - return $this; - } - - /** - * Get the number of lease seconds on subscriptions - * - * @return int - */ - public function getLeaseSeconds() - { - return $this->leaseSeconds; - } - - /** - * Set the callback URL to be used by Hub Servers when communicating with - * this Subscriber - * - * @param string $url - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function setCallbackUrl($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - . ' of "' . $url . '" must be a non-empty string and a valid' - . ' URL'); - } - $this->callbackUrl = $url; - return $this; - } - - /** - * Get the callback URL to be used by Hub Servers when communicating with - * this Subscriber - * - * @return string - * @throws Exception\RuntimeException - */ - public function getCallbackUrl() - { - if (empty($this->callbackUrl)) { - throw new Exception\RuntimeException('A valid Callback URL MUST be' - . ' set before attempting any operation'); - } - return $this->callbackUrl; - } - - /** - * Set preferred verification mode (sync or async). By default, this - * Subscriber prefers synchronous verification, but does support - * asynchronous if that's the Hub Server's utilised mode. - * - * Zend\Feed\Pubsubhubbub\Subscriber will always send both modes, whose - * order of occurrence in the parameter list determines this preference. - * - * @param string $mode Should be 'sync' or 'async' - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function setPreferredVerificationMode($mode) - { - if ($mode !== PubSubHubbub::VERIFICATION_MODE_SYNC - && $mode !== PubSubHubbub::VERIFICATION_MODE_ASYNC - ) { - throw new Exception\InvalidArgumentException('Invalid preferred' - . ' mode specified: "' . $mode . '" but should be one of' - . ' Zend\Feed\Pubsubhubbub::VERIFICATION_MODE_SYNC or' - . ' Zend\Feed\Pubsubhubbub::VERIFICATION_MODE_ASYNC'); - } - $this->preferredVerificationMode = $mode; - return $this; - } - - /** - * Get preferred verification mode (sync or async). - * - * @return string - */ - public function getPreferredVerificationMode() - { - return $this->preferredVerificationMode; - } - - /** - * Add a Hub Server URL supported by Publisher - * - * @param string $url - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function addHubUrl($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - . ' of "' . $url . '" must be a non-empty string and a valid' - . ' URL'); - } - $this->hubUrls[] = $url; - return $this; - } - - /** - * Add an array of Hub Server URLs supported by Publisher - * - * @param array $urls - * @return Subscriber - */ - public function addHubUrls(array $urls) - { - foreach ($urls as $url) { - $this->addHubUrl($url); - } - return $this; - } - - /** - * Remove a Hub Server URL - * - * @param string $url - * @return Subscriber - */ - public function removeHubUrl($url) - { - if (!in_array($url, $this->getHubUrls())) { - return $this; - } - $key = array_search($url, $this->hubUrls); - unset($this->hubUrls[$key]); - return $this; - } - - /** - * Return an array of unique Hub Server URLs currently available - * - * @return array - */ - public function getHubUrls() - { - $this->hubUrls = array_unique($this->hubUrls); - return $this->hubUrls; - } - - /** - * Add authentication credentials for a given URL - * - * @param string $url - * @param array $authentication - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function addAuthentication($url, array $authentication) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter "url"' - . ' of "' . $url . '" must be a non-empty string and a valid' - . ' URL'); - } - $this->authentications[$url] = $authentication; - return $this; - } - - /** - * Add authentication credentials for hub URLs - * - * @param array $authentications - * @return Subscriber - */ - public function addAuthentications(array $authentications) - { - foreach ($authentications as $url => $authentication) { - $this->addAuthentication($url, $authentication); - } - return $this; - } - - /** - * Get all hub URL authentication credentials - * - * @return array - */ - public function getAuthentications() - { - return $this->authentications; - } - - /** - * Set flag indicating whether or not to use a path parameter - * - * @param bool $bool - * @return Subscriber - */ - public function usePathParameter($bool = true) - { - $this->usePathParameter = $bool; - return $this; - } - - /** - * Add an optional parameter to the (un)subscribe requests - * - * @param string $name - * @param string|null $value - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function setParameter($name, $value = null) - { - if (is_array($name)) { - $this->setParameters($name); - return $this; - } - if (empty($name) || !is_string($name)) { - throw new Exception\InvalidArgumentException('Invalid parameter "name"' - . ' of "' . $name . '" must be a non-empty string'); - } - if ($value === null) { - $this->removeParameter($name); - return $this; - } - if (empty($value) || (!is_string($value) && $value !== null)) { - throw new Exception\InvalidArgumentException('Invalid parameter "value"' - . ' of "' . $value . '" must be a non-empty string'); - } - $this->parameters[$name] = $value; - return $this; - } - - /** - * Add an optional parameter to the (un)subscribe requests - * - * @param array $parameters - * @return Subscriber - */ - public function setParameters(array $parameters) - { - foreach ($parameters as $name => $value) { - $this->setParameter($name, $value); - } - return $this; - } - - /** - * Remove an optional parameter for the (un)subscribe requests - * - * @param string $name - * @return Subscriber - * @throws Exception\InvalidArgumentException - */ - public function removeParameter($name) - { - if (empty($name) || !is_string($name)) { - throw new Exception\InvalidArgumentException('Invalid parameter "name"' - . ' of "' . $name . '" must be a non-empty string'); - } - if (array_key_exists($name, $this->parameters)) { - unset($this->parameters[$name]); - } - return $this; - } - - /** - * Return an array of optional parameters for (un)subscribe requests - * - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * Sets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used to background - * save any verification tokens associated with a subscription or other. - * - * @param Model\SubscriptionPersistenceInterface $storage - * @return Subscriber - */ - public function setStorage(Model\SubscriptionPersistenceInterface $storage) - { - $this->storage = $storage; - return $this; - } - - /** - * Gets an instance of Zend\Feed\Pubsubhubbub\Storage\StoragePersistence used - * to background save any verification tokens associated with a subscription - * or other. - * - * @return Model\SubscriptionPersistenceInterface - * @throws Exception\RuntimeException - */ - public function getStorage() - { - if ($this->storage === null) { - throw new Exception\RuntimeException('No storage vehicle ' - . 'has been set.'); - } - return $this->storage; - } - - /** - * Subscribe to one or more Hub Servers using the stored Hub URLs - * for the given Topic URL (RSS or Atom feed) - * - * @return void - */ - public function subscribeAll() - { - $this->_doRequest('subscribe'); - } - - /** - * Unsubscribe from one or more Hub Servers using the stored Hub URLs - * for the given Topic URL (RSS or Atom feed) - * - * @return void - */ - public function unsubscribeAll() - { - $this->_doRequest('unsubscribe'); - } - - /** - * Returns a boolean indicator of whether the notifications to Hub - * Servers were ALL successful. If even one failed, FALSE is returned. - * - * @return bool - */ - public function isSuccess() - { - if (count($this->errors) > 0) { - return false; - } - return true; - } - - /** - * Return an array of errors met from any failures, including keys: - * 'response' => the Zend\Http\Response object from the failure - * 'hubUrl' => the URL of the Hub Server whose notification failed - * - * @return array - */ - public function getErrors() - { - return $this->errors; - } - - /** - * Return an array of Hub Server URLs who returned a response indicating - * operation in Asynchronous Verification Mode, i.e. they will not confirm - * any (un)subscription immediately but at a later time (Hubs may be - * doing this as a batch process when load balancing) - * - * @return array - */ - public function getAsyncHubs() - { - return $this->asyncHubs; - } - - /** - * Executes an (un)subscribe request - * - * @param string $mode - * @return void - * @throws Exception\RuntimeException - */ - protected function _doRequest($mode) - { - $client = $this->_getHttpClient(); - $hubs = $this->getHubUrls(); - if (empty($hubs)) { - throw new Exception\RuntimeException('No Hub Server URLs' - . ' have been set so no subscriptions can be attempted'); - } - $this->errors = array(); - $this->asyncHubs = array(); - foreach ($hubs as $url) { - if (array_key_exists($url, $this->authentications)) { - $auth = $this->authentications[$url]; - $client->setAuth($auth[0], $auth[1]); - } - $client->setUri($url); - $client->setRawBody($params = $this->_getRequestParameters($url, $mode)); - $response = $client->send(); - if ($response->getStatusCode() !== 204 - && $response->getStatusCode() !== 202 - ) { - $this->errors[] = array( - 'response' => $response, - 'hubUrl' => $url, - ); - /** - * At first I thought it was needed, but the backend storage will - * allow tracking async without any user interference. It's left - * here in case the user is interested in knowing what Hubs - * are using async verification modes so they may update Models and - * move these to asynchronous processes. - */ - } elseif ($response->getStatusCode() == 202) { - $this->asyncHubs[] = array( - 'response' => $response, - 'hubUrl' => $url, - ); - } - } - } - - /** - * Get a basic prepared HTTP client for use - * - * @return \Zend\Http\Client - */ - protected function _getHttpClient() - { - $client = PubSubHubbub::getHttpClient(); - $client->setMethod(HttpRequest::METHOD_POST); - $client->setOptions(array('useragent' => 'Zend_Feed_Pubsubhubbub_Subscriber/' - . Version::VERSION)); - return $client; - } - - /** - * Return a list of standard protocol/optional parameters for addition to - * client's POST body that are specific to the current Hub Server URL - * - * @param string $hubUrl - * @param string $mode - * @return string - * @throws Exception\InvalidArgumentException - */ - protected function _getRequestParameters($hubUrl, $mode) - { - if (!in_array($mode, array('subscribe', 'unsubscribe'))) { - throw new Exception\InvalidArgumentException('Invalid mode specified: "' - . $mode . '" which should have been "subscribe" or "unsubscribe"'); - } - - $params = array( - 'hub.mode' => $mode, - 'hub.topic' => $this->getTopicUrl(), - ); - - if ($this->getPreferredVerificationMode() - == PubSubHubbub::VERIFICATION_MODE_SYNC - ) { - $vmodes = array( - PubSubHubbub::VERIFICATION_MODE_SYNC, - PubSubHubbub::VERIFICATION_MODE_ASYNC, - ); - } else { - $vmodes = array( - PubSubHubbub::VERIFICATION_MODE_ASYNC, - PubSubHubbub::VERIFICATION_MODE_SYNC, - ); - } - $params['hub.verify'] = array(); - foreach ($vmodes as $vmode) { - $params['hub.verify'][] = $vmode; - } - - /** - * Establish a persistent verify_token and attach key to callback - * URL's path/query_string - */ - $key = $this->_generateSubscriptionKey($params, $hubUrl); - $token = $this->_generateVerifyToken(); - $params['hub.verify_token'] = $token; - - // Note: query string only usable with PuSH 0.2 Hubs - if (!$this->usePathParameter) { - $params['hub.callback'] = $this->getCallbackUrl() - . '?xhub.subscription=' . PubSubHubbub::urlencode($key); - } else { - $params['hub.callback'] = rtrim($this->getCallbackUrl(), '/') - . '/' . PubSubHubbub::urlencode($key); - } - if ($mode == 'subscribe' && $this->getLeaseSeconds() !== null) { - $params['hub.lease_seconds'] = $this->getLeaseSeconds(); - } - - // hub.secret not currently supported - $optParams = $this->getParameters(); - foreach ($optParams as $name => $value) { - $params[$name] = $value; - } - - // store subscription to storage - $now = new DateTime(); - $expires = null; - if (isset($params['hub.lease_seconds'])) { - $expires = $now->add(new DateInterval('PT' . $params['hub.lease_seconds'] . 'S')) - ->format('Y-m-d H:i:s'); - } - $data = array( - 'id' => $key, - 'topic_url' => $params['hub.topic'], - 'hub_url' => $hubUrl, - 'created_time' => $now->format('Y-m-d H:i:s'), - 'lease_seconds' => $params['hub.lease_seconds'], - 'verify_token' => hash('sha256', $params['hub.verify_token']), - 'secret' => null, - 'expiration_time' => $expires, - 'subscription_state' => ($mode == 'unsubscribe')? PubSubHubbub::SUBSCRIPTION_TODELETE : PubSubHubbub::SUBSCRIPTION_NOTVERIFIED, - ); - $this->getStorage()->setSubscription($data); - - return $this->_toByteValueOrderedString( - $this->_urlEncode($params) - ); - } - - /** - * Simple helper to generate a verification token used in (un)subscribe - * requests to a Hub Server. Follows no particular method, which means - * it might be improved/changed in future. - * - * @return string - */ - protected function _generateVerifyToken() - { - if (!empty($this->testStaticToken)) { - return $this->testStaticToken; - } - return uniqid(rand(), true) . time(); - } - - /** - * Simple helper to generate a verification token used in (un)subscribe - * requests to a Hub Server. - * - * @param array $params - * @param string $hubUrl The Hub Server URL for which this token will apply - * @return string - */ - protected function _generateSubscriptionKey(array $params, $hubUrl) - { - $keyBase = $params['hub.topic'] . $hubUrl; - $key = md5($keyBase); - - return $key; - } - - /** - * URL Encode an array of parameters - * - * @param array $params - * @return array - */ - protected function _urlEncode(array $params) - { - $encoded = array(); - foreach ($params as $key => $value) { - if (is_array($value)) { - $ekey = PubSubHubbub::urlencode($key); - $encoded[$ekey] = array(); - foreach ($value as $duplicateKey) { - $encoded[$ekey][] - = PubSubHubbub::urlencode($duplicateKey); - } - } else { - $encoded[PubSubHubbub::urlencode($key)] - = PubSubHubbub::urlencode($value); - } - } - return $encoded; - } - - /** - * Order outgoing parameters - * - * @param array $params - * @return array - */ - protected function _toByteValueOrderedString(array $params) - { - $return = array(); - uksort($params, 'strnatcmp'); - foreach ($params as $key => $value) { - if (is_array($value)) { - foreach ($value as $keyduplicate) { - $return[] = $key . '=' . $keyduplicate; - } - } else { - $return[] = $key . '=' . $value; - } - } - return implode('&', $return); - } - - /** - * This is STRICTLY for testing purposes only... - */ - protected $testStaticToken = null; - - final public function setTestStaticToken($token) - { - $this->testStaticToken = (string) $token; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Subscriber/Callback.php b/library/Zend/Feed/PubSubHubbub/Subscriber/Callback.php deleted file mode 100755 index 5ec8af2fe..000000000 --- a/library/Zend/Feed/PubSubHubbub/Subscriber/Callback.php +++ /dev/null @@ -1,316 +0,0 @@ -subscriptionKey = $key; - return $this; - } - - /** - * Handle any callback from a Hub Server responding to a subscription or - * unsubscription request. This should be the Hub Server confirming the - * the request prior to taking action on it. - * - * @param array $httpGetData GET data if available and not in $_GET - * @param bool $sendResponseNow Whether to send response now or when asked - * @return void - */ - public function handle(array $httpGetData = null, $sendResponseNow = false) - { - if ($httpGetData === null) { - $httpGetData = $_GET; - } - - /** - * Handle any feed updates (sorry for the mess :P) - * - * This DOES NOT attempt to process a feed update. Feed updates - * SHOULD be validated/processed by an asynchronous process so as - * to avoid holding up responses to the Hub. - */ - $contentType = $this->_getHeader('Content-Type'); - if (strtolower($_SERVER['REQUEST_METHOD']) == 'post' - && $this->_hasValidVerifyToken(null, false) - && (stripos($contentType, 'application/atom+xml') === 0 - || stripos($contentType, 'application/rss+xml') === 0 - || stripos($contentType, 'application/xml') === 0 - || stripos($contentType, 'text/xml') === 0 - || stripos($contentType, 'application/rdf+xml') === 0) - ) { - $this->setFeedUpdate($this->_getRawBody()); - $this->getHttpResponse()->setHeader('X-Hub-On-Behalf-Of', $this->getSubscriberCount()); - /** - * Handle any (un)subscribe confirmation requests - */ - } elseif ($this->isValidHubVerification($httpGetData)) { - $this->getHttpResponse()->setContent($httpGetData['hub_challenge']); - - switch (strtolower($httpGetData['hub_mode'])) { - case 'subscribe': - $data = $this->currentSubscriptionData; - $data['subscription_state'] = PubSubHubbub\PubSubHubbub::SUBSCRIPTION_VERIFIED; - if (isset($httpGetData['hub_lease_seconds'])) { - $data['lease_seconds'] = $httpGetData['hub_lease_seconds']; - } - $this->getStorage()->setSubscription($data); - break; - case 'unsubscribe': - $verifyTokenKey = $this->_detectVerifyTokenKey($httpGetData); - $this->getStorage()->deleteSubscription($verifyTokenKey); - break; - default: - throw new Exception\RuntimeException(sprintf( - 'Invalid hub_mode ("%s") provided', - $httpGetData['hub_mode'] - )); - } - /** - * Hey, C'mon! We tried everything else! - */ - } else { - $this->getHttpResponse()->setStatusCode(404); - } - - if ($sendResponseNow) { - $this->sendResponse(); - } - } - - /** - * Checks validity of the request simply by making a quick pass and - * confirming the presence of all REQUIRED parameters. - * - * @param array $httpGetData - * @return bool - */ - public function isValidHubVerification(array $httpGetData) - { - /** - * As per the specification, the hub.verify_token is OPTIONAL. This - * implementation of Pubsubhubbub considers it REQUIRED and will - * always send a hub.verify_token parameter to be echoed back - * by the Hub Server. Therefore, its absence is considered invalid. - */ - if (strtolower($_SERVER['REQUEST_METHOD']) !== 'get') { - return false; - } - $required = array( - 'hub_mode', - 'hub_topic', - 'hub_challenge', - 'hub_verify_token', - ); - foreach ($required as $key) { - if (!array_key_exists($key, $httpGetData)) { - return false; - } - } - if ($httpGetData['hub_mode'] !== 'subscribe' - && $httpGetData['hub_mode'] !== 'unsubscribe' - ) { - return false; - } - if ($httpGetData['hub_mode'] == 'subscribe' - && !array_key_exists('hub_lease_seconds', $httpGetData) - ) { - return false; - } - if (!Uri::factory($httpGetData['hub_topic'])->isValid()) { - return false; - } - - /** - * Attempt to retrieve any Verification Token Key attached to Callback - * URL's path by our Subscriber implementation - */ - if (!$this->_hasValidVerifyToken($httpGetData)) { - return false; - } - return true; - } - - /** - * Sets a newly received feed (Atom/RSS) sent by a Hub as an update to a - * Topic we've subscribed to. - * - * @param string $feed - * @return \Zend\Feed\PubSubHubbub\Subscriber\Callback - */ - public function setFeedUpdate($feed) - { - $this->feedUpdate = $feed; - return $this; - } - - /** - * Check if any newly received feed (Atom/RSS) update was received - * - * @return bool - */ - public function hasFeedUpdate() - { - if ($this->feedUpdate === null) { - return false; - } - return true; - } - - /** - * Gets a newly received feed (Atom/RSS) sent by a Hub as an update to a - * Topic we've subscribed to. - * - * @return string - */ - public function getFeedUpdate() - { - return $this->feedUpdate; - } - - /** - * Check for a valid verify_token. By default attempts to compare values - * with that sent from Hub, otherwise merely ascertains its existence. - * - * @param array $httpGetData - * @param bool $checkValue - * @return bool - */ - protected function _hasValidVerifyToken(array $httpGetData = null, $checkValue = true) - { - $verifyTokenKey = $this->_detectVerifyTokenKey($httpGetData); - if (empty($verifyTokenKey)) { - return false; - } - $verifyTokenExists = $this->getStorage()->hasSubscription($verifyTokenKey); - if (!$verifyTokenExists) { - return false; - } - if ($checkValue) { - $data = $this->getStorage()->getSubscription($verifyTokenKey); - $verifyToken = $data['verify_token']; - if ($verifyToken !== hash('sha256', $httpGetData['hub_verify_token'])) { - return false; - } - $this->currentSubscriptionData = $data; - return true; - } - return true; - } - - /** - * Attempt to detect the verification token key. This would be passed in - * the Callback URL (which we are handling with this class!) as a URI - * path part (the last part by convention). - * - * @param null|array $httpGetData - * @return false|string - */ - protected function _detectVerifyTokenKey(array $httpGetData = null) - { - /** - * Available when sub keys encoding in Callback URL path - */ - if (isset($this->subscriptionKey)) { - return $this->subscriptionKey; - } - - /** - * Available only if allowed by PuSH 0.2 Hubs - */ - if (is_array($httpGetData) - && isset($httpGetData['xhub_subscription']) - ) { - return $httpGetData['xhub_subscription']; - } - - /** - * Available (possibly) if corrupted in transit and not part of $_GET - */ - $params = $this->_parseQueryString(); - if (isset($params['xhub.subscription'])) { - return rawurldecode($params['xhub.subscription']); - } - - return false; - } - - /** - * Build an array of Query String parameters. - * This bypasses $_GET which munges parameter names and cannot accept - * multiple parameters with the same key. - * - * @return array|void - */ - protected function _parseQueryString() - { - $params = array(); - $queryString = ''; - if (isset($_SERVER['QUERY_STRING'])) { - $queryString = $_SERVER['QUERY_STRING']; - } - if (empty($queryString)) { - return array(); - } - $parts = explode('&', $queryString); - foreach ($parts as $kvpair) { - $pair = explode('=', $kvpair); - $key = rawurldecode($pair[0]); - $value = rawurldecode($pair[1]); - if (isset($params[$key])) { - if (is_array($params[$key])) { - $params[$key][] = $value; - } else { - $params[$key] = array($params[$key], $value); - } - } else { - $params[$key] = $value; - } - } - return $params; - } -} diff --git a/library/Zend/Feed/PubSubHubbub/Version.php b/library/Zend/Feed/PubSubHubbub/Version.php deleted file mode 100755 index edee6953b..000000000 --- a/library/Zend/Feed/PubSubHubbub/Version.php +++ /dev/null @@ -1,15 +0,0 @@ -entry = $entry; - $this->entryKey = $entryKey; - $this->domDocument = $entry->ownerDocument; - if ($type !== null) { - $this->data['type'] = $type; - } else { - $this->data['type'] = Reader::detectType($entry); - } - $this->_loadExtensions(); - } - - /** - * Get the DOM - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->domDocument; - } - - /** - * Get the entry element - * - * @return DOMElement - */ - public function getElement() - { - return $this->entry; - } - - /** - * Get the Entry's encoding - * - * @return string - */ - public function getEncoding() - { - $assumed = $this->getDomDocument()->encoding; - if (empty($assumed)) { - $assumed = 'UTF-8'; - } - return $assumed; - } - - /** - * Get entry as xml - * - * @return string - */ - public function saveXml() - { - $dom = new DOMDocument('1.0', $this->getEncoding()); - $entry = $dom->importNode($this->getElement(), true); - $dom->appendChild($entry); - return $dom->saveXml(); - } - - /** - * Get the entry type - * - * @return string - */ - public function getType() - { - return $this->data['type']; - } - - /** - * Get the XPath query object - * - * @return DOMXPath - */ - public function getXpath() - { - if (!$this->xpath) { - $this->setXpath(new DOMXPath($this->getDomDocument())); - } - return $this->xpath; - } - - /** - * Set the XPath query - * - * @param DOMXPath $xpath - * @return \Zend\Feed\Reader\AbstractEntry - */ - public function setXpath(DOMXPath $xpath) - { - $this->xpath = $xpath; - return $this; - } - - /** - * Get registered extensions - * - * @return array - */ - public function getExtensions() - { - return $this->extensions; - } - - /** - * Return an Extension object with the matching name (postfixed with _Entry) - * - * @param string $name - * @return \Zend\Feed\Reader\Extension\AbstractEntry - */ - public function getExtension($name) - { - if (array_key_exists($name . '\Entry', $this->extensions)) { - return $this->extensions[$name . '\Entry']; - } - return null; - } - - /** - * Method overloading: call given method on first extension implementing it - * - * @param string $method - * @param array $args - * @return mixed - * @throws Exception\BadMethodCallException if no extensions implements the method - */ - public function __call($method, $args) - { - foreach ($this->extensions as $extension) { - if (method_exists($extension, $method)) { - return call_user_func_array(array($extension, $method), $args); - } - } - throw new Exception\BadMethodCallException('Method: ' . $method - . 'does not exist and could not be located on a registered Extension'); - } - - /** - * Load extensions from Zend\Feed\Reader\Reader - * - * @return void - */ - protected function _loadExtensions() - { - $all = Reader::getExtensions(); - $feed = $all['entry']; - foreach ($feed as $extension) { - if (in_array($extension, $all['core'])) { - continue; - } - $className = Reader::getPluginLoader()->getClassName($extension); - $this->extensions[$extension] = new $className( - $this->getElement(), $this->entryKey, $this->data['type'] - ); - } - } -} diff --git a/library/Zend/Feed/Reader/AbstractFeed.php b/library/Zend/Feed/Reader/AbstractFeed.php deleted file mode 100755 index f8aa49d81..000000000 --- a/library/Zend/Feed/Reader/AbstractFeed.php +++ /dev/null @@ -1,300 +0,0 @@ -domDocument = $domDocument; - $this->xpath = new DOMXPath($this->domDocument); - - if ($type !== null) { - $this->data['type'] = $type; - } else { - $this->data['type'] = Reader::detectType($this->domDocument); - } - $this->registerNamespaces(); - $this->indexEntries(); - $this->loadExtensions(); - } - - /** - * Set an original source URI for the feed being parsed. This value - * is returned from getFeedLink() method if the feed does not carry - * a self-referencing URI. - * - * @param string $uri - */ - public function setOriginalSourceUri($uri) - { - $this->originalSourceUri = $uri; - } - - /** - * Get an original source URI for the feed being parsed. Returns null if - * unset or the feed was not imported from a URI. - * - * @return string|null - */ - public function getOriginalSourceUri() - { - return $this->originalSourceUri; - } - - /** - * Get the number of feed entries. - * Required by the Iterator interface. - * - * @return int - */ - public function count() - { - return count($this->entries); - } - - /** - * Return the current entry - * - * @return \Zend\Feed\Reader\AbstractEntry - */ - public function current() - { - if (substr($this->getType(), 0, 3) == 'rss') { - $reader = new Entry\RSS($this->entries[$this->key()], $this->key(), $this->getType()); - } else { - $reader = new Entry\Atom($this->entries[$this->key()], $this->key(), $this->getType()); - } - - $reader->setXpath($this->xpath); - - return $reader; - } - - /** - * Get the DOM - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->domDocument; - } - - /** - * Get the Feed's encoding - * - * @return string - */ - public function getEncoding() - { - $assumed = $this->getDomDocument()->encoding; - if (empty($assumed)) { - $assumed = 'UTF-8'; - } - return $assumed; - } - - /** - * Get feed as xml - * - * @return string - */ - public function saveXml() - { - return $this->getDomDocument()->saveXml(); - } - - /** - * Get the DOMElement representing the items/feed element - * - * @return DOMElement - */ - public function getElement() - { - return $this->getDomDocument()->documentElement; - } - - /** - * Get the DOMXPath object for this feed - * - * @return DOMXPath - */ - public function getXpath() - { - return $this->xpath; - } - - /** - * Get the feed type - * - * @return string - */ - public function getType() - { - return $this->data['type']; - } - - /** - * Return the current feed key - * - * @return int - */ - public function key() - { - return $this->entriesKey; - } - - /** - * Move the feed pointer forward - * - */ - public function next() - { - ++$this->entriesKey; - } - - /** - * Reset the pointer in the feed object - * - */ - public function rewind() - { - $this->entriesKey = 0; - } - - /** - * Check to see if the iterator is still valid - * - * @return bool - */ - public function valid() - { - return 0 <= $this->entriesKey && $this->entriesKey < $this->count(); - } - - public function getExtensions() - { - return $this->extensions; - } - - public function __call($method, $args) - { - foreach ($this->extensions as $extension) { - if (method_exists($extension, $method)) { - return call_user_func_array(array($extension, $method), $args); - } - } - throw new Exception\BadMethodCallException('Method: ' . $method - . 'does not exist and could not be located on a registered Extension'); - } - - /** - * Return an Extension object with the matching name (postfixed with _Feed) - * - * @param string $name - * @return \Zend\Feed\Reader\Extension\AbstractFeed - */ - public function getExtension($name) - { - if (array_key_exists($name . '\Feed', $this->extensions)) { - return $this->extensions[$name . '\Feed']; - } - return null; - } - - protected function loadExtensions() - { - $all = Reader::getExtensions(); - $manager = Reader::getExtensionManager(); - $feed = $all['feed']; - foreach ($feed as $extension) { - if (in_array($extension, $all['core'])) { - continue; - } - $plugin = $manager->get($extension); - $plugin->setDomDocument($this->getDomDocument()); - $plugin->setType($this->data['type']); - $plugin->setXpath($this->xpath); - $this->extensions[$extension] = $plugin; - } - } - - /** - * Read all entries to the internal entries array - * - */ - abstract protected function indexEntries(); - - /** - * Register the default namespaces for the current feed format - * - */ - abstract protected function registerNamespaces(); -} diff --git a/library/Zend/Feed/Reader/Collection.php b/library/Zend/Feed/Reader/Collection.php deleted file mode 100755 index ac1c96384..000000000 --- a/library/Zend/Feed/Reader/Collection.php +++ /dev/null @@ -1,16 +0,0 @@ -getIterator() as $element) { - $authors[] = $element['name']; - } - return array_unique($authors); - } -} diff --git a/library/Zend/Feed/Reader/Collection/Category.php b/library/Zend/Feed/Reader/Collection/Category.php deleted file mode 100755 index 34b8fdedb..000000000 --- a/library/Zend/Feed/Reader/Collection/Category.php +++ /dev/null @@ -1,34 +0,0 @@ -getIterator() as $element) { - if (isset($element['label']) && !empty($element['label'])) { - $categories[] = $element['label']; - } else { - $categories[] = $element['term']; - } - } - return array_unique($categories); - } -} diff --git a/library/Zend/Feed/Reader/Collection/Collection.php b/library/Zend/Feed/Reader/Collection/Collection.php deleted file mode 100755 index 86a29276a..000000000 --- a/library/Zend/Feed/Reader/Collection/Collection.php +++ /dev/null @@ -1,16 +0,0 @@ -entry = $entry; - $this->entryKey = $entryKey; - $this->domDocument = $entry->ownerDocument; - if ($type !== null) { - $this->data['type'] = $type; - } elseif ($this->domDocument !== null) { - $this->data['type'] = Reader\Reader::detectType($this->domDocument); - } else { - $this->data['type'] = Reader\Reader::TYPE_ANY; - } - $this->loadExtensions(); - } - - /** - * Get the DOM - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->domDocument; - } - - /** - * Get the entry element - * - * @return DOMElement - */ - public function getElement() - { - return $this->entry; - } - - /** - * Get the Entry's encoding - * - * @return string - */ - public function getEncoding() - { - $assumed = $this->getDomDocument()->encoding; - if (empty($assumed)) { - $assumed = 'UTF-8'; - } - return $assumed; - } - - /** - * Get entry as xml - * - * @return string - */ - public function saveXml() - { - $dom = new DOMDocument('1.0', $this->getEncoding()); - $entry = $dom->importNode($this->getElement(), true); - $dom->appendChild($entry); - return $dom->saveXml(); - } - - /** - * Get the entry type - * - * @return string - */ - public function getType() - { - return $this->data['type']; - } - - /** - * Get the XPath query object - * - * @return DOMXPath - */ - public function getXpath() - { - if (!$this->xpath) { - $this->setXpath(new DOMXPath($this->getDomDocument())); - } - return $this->xpath; - } - - /** - * Set the XPath query - * - * @param DOMXPath $xpath - * @return AbstractEntry - */ - public function setXpath(DOMXPath $xpath) - { - $this->xpath = $xpath; - return $this; - } - - /** - * Get registered extensions - * - * @return array - */ - public function getExtensions() - { - return $this->extensions; - } - - /** - * Return an Extension object with the matching name (postfixed with _Entry) - * - * @param string $name - * @return Reader\Extension\AbstractEntry - */ - public function getExtension($name) - { - if (array_key_exists($name . '\\Entry', $this->extensions)) { - return $this->extensions[$name . '\\Entry']; - } - return null; - } - - /** - * Method overloading: call given method on first extension implementing it - * - * @param string $method - * @param array $args - * @return mixed - * @throws Exception\RuntimeException if no extensions implements the method - */ - public function __call($method, $args) - { - foreach ($this->extensions as $extension) { - if (method_exists($extension, $method)) { - return call_user_func_array(array($extension, $method), $args); - } - } - throw new Exception\RuntimeException('Method: ' . $method - . ' does not exist and could not be located on a registered Extension'); - } - - /** - * Load extensions from Zend\Feed\Reader\Reader - * - * @return void - */ - protected function loadExtensions() - { - $all = Reader\Reader::getExtensions(); - $manager = Reader\Reader::getExtensionManager(); - $feed = $all['entry']; - foreach ($feed as $extension) { - if (in_array($extension, $all['core'])) { - continue; - } - $plugin = $manager->get($extension); - $plugin->setEntryElement($this->getElement()); - $plugin->setEntryKey($this->entryKey); - $plugin->setType($this->data['type']); - $this->extensions[$extension] = $plugin; - } - } -} diff --git a/library/Zend/Feed/Reader/Entry/Atom.php b/library/Zend/Feed/Reader/Entry/Atom.php deleted file mode 100755 index ed61a21e5..000000000 --- a/library/Zend/Feed/Reader/Entry/Atom.php +++ /dev/null @@ -1,370 +0,0 @@ -xpathQuery = '//atom:entry[' . ($this->entryKey + 1) . ']'; - - $manager = Reader\Reader::getExtensionManager(); - $extensions = array('Atom\Entry', 'Thread\Entry', 'DublinCore\Entry'); - - foreach ($extensions as $name) { - $extension = $manager->get($name); - $extension->setEntryElement($entry); - $extension->setEntryKey($entryKey); - $extension->setType($type); - $this->extensions[$name] = $extension; - } - } - - /** - * Get the specified author - * - * @param int $index - * @return string|null - */ - public function getAuthor($index = 0) - { - $authors = $this->getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $people = $this->getExtension('Atom')->getAuthors(); - - $this->data['authors'] = $people; - - return $this->data['authors']; - } - - /** - * Get the entry content - * - * @return string - */ - public function getContent() - { - if (array_key_exists('content', $this->data)) { - return $this->data['content']; - } - - $content = $this->getExtension('Atom')->getContent(); - - $this->data['content'] = $content; - - return $this->data['content']; - } - - /** - * Get the entry creation date - * - * @return string - */ - public function getDateCreated() - { - if (array_key_exists('datecreated', $this->data)) { - return $this->data['datecreated']; - } - - $dateCreated = $this->getExtension('Atom')->getDateCreated(); - - $this->data['datecreated'] = $dateCreated; - - return $this->data['datecreated']; - } - - /** - * Get the entry modification date - * - * @return string - */ - public function getDateModified() - { - if (array_key_exists('datemodified', $this->data)) { - return $this->data['datemodified']; - } - - $dateModified = $this->getExtension('Atom')->getDateModified(); - - $this->data['datemodified'] = $dateModified; - - return $this->data['datemodified']; - } - - /** - * Get the entry description - * - * @return string - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = $this->getExtension('Atom')->getDescription(); - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the entry enclosure - * - * @return string - */ - public function getEnclosure() - { - if (array_key_exists('enclosure', $this->data)) { - return $this->data['enclosure']; - } - - $enclosure = $this->getExtension('Atom')->getEnclosure(); - - $this->data['enclosure'] = $enclosure; - - return $this->data['enclosure']; - } - - /** - * Get the entry ID - * - * @return string - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = $this->getExtension('Atom')->getId(); - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get a specific link - * - * @param int $index - * @return string - */ - public function getLink($index = 0) - { - if (!array_key_exists('links', $this->data)) { - $this->getLinks(); - } - - if (isset($this->data['links'][$index])) { - return $this->data['links'][$index]; - } - - return null; - } - - /** - * Get all links - * - * @return array - */ - public function getLinks() - { - if (array_key_exists('links', $this->data)) { - return $this->data['links']; - } - - $links = $this->getExtension('Atom')->getLinks(); - - $this->data['links'] = $links; - - return $this->data['links']; - } - - /** - * Get a permalink to the entry - * - * @return string - */ - public function getPermalink() - { - return $this->getLink(0); - } - - /** - * Get the entry title - * - * @return string - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = $this->getExtension('Atom')->getTitle(); - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * Get the number of comments/replies for current entry - * - * @return int - */ - public function getCommentCount() - { - if (array_key_exists('commentcount', $this->data)) { - return $this->data['commentcount']; - } - - $commentcount = $this->getExtension('Thread')->getCommentCount(); - - if (!$commentcount) { - $commentcount = $this->getExtension('Atom')->getCommentCount(); - } - - $this->data['commentcount'] = $commentcount; - - return $this->data['commentcount']; - } - - /** - * Returns a URI pointing to the HTML page where comments can be made on this entry - * - * @return string - */ - public function getCommentLink() - { - if (array_key_exists('commentlink', $this->data)) { - return $this->data['commentlink']; - } - - $commentlink = $this->getExtension('Atom')->getCommentLink(); - - $this->data['commentlink'] = $commentlink; - - return $this->data['commentlink']; - } - - /** - * Returns a URI pointing to a feed of all comments for this entry - * - * @return string - */ - public function getCommentFeedLink() - { - if (array_key_exists('commentfeedlink', $this->data)) { - return $this->data['commentfeedlink']; - } - - $commentfeedlink = $this->getExtension('Atom')->getCommentFeedLink(); - - $this->data['commentfeedlink'] = $commentfeedlink; - - return $this->data['commentfeedlink']; - } - - /** - * Get category data as a Reader\Reader_Collection_Category object - * - * @return Reader\Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - $categoryCollection = $this->getExtension('Atom')->getCategories(); - - if (count($categoryCollection) == 0) { - $categoryCollection = $this->getExtension('DublinCore')->getCategories(); - } - - $this->data['categories'] = $categoryCollection; - - return $this->data['categories']; - } - - /** - * Get source feed metadata from the entry - * - * @return Reader\Feed\Atom\Source|null - */ - public function getSource() - { - if (array_key_exists('source', $this->data)) { - return $this->data['source']; - } - - $source = $this->getExtension('Atom')->getSource(); - - $this->data['source'] = $source; - - return $this->data['source']; - } - - /** - * Set the XPath query (incl. on all Extensions) - * - * @param DOMXPath $xpath - * @return void - */ - public function setXpath(DOMXPath $xpath) - { - parent::setXpath($xpath); - foreach ($this->extensions as $extension) { - $extension->setXpath($this->xpath); - } - } -} diff --git a/library/Zend/Feed/Reader/Entry/EntryInterface.php b/library/Zend/Feed/Reader/Entry/EntryInterface.php deleted file mode 100755 index 86fea3ec5..000000000 --- a/library/Zend/Feed/Reader/Entry/EntryInterface.php +++ /dev/null @@ -1,129 +0,0 @@ -xpathQueryRss = '//item[' . ($this->entryKey+1) . ']'; - $this->xpathQueryRdf = '//rss:item[' . ($this->entryKey+1) . ']'; - - $manager = Reader\Reader::getExtensionManager(); - $extensions = array( - 'DublinCore\Entry', - 'Content\Entry', - 'Atom\Entry', - 'WellFormedWeb\Entry', - 'Slash\Entry', - 'Thread\Entry', - ); - foreach ($extensions as $name) { - $extension = $manager->get($name); - $extension->setEntryElement($entry); - $extension->setEntryKey($entryKey); - $extension->setType($type); - $this->extensions[$name] = $extension; - } - } - - /** - * Get an author entry - * - * @param int $index - * @return string - */ - public function getAuthor($index = 0) - { - $authors = $this->getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $authors = array(); - $authorsDc = $this->getExtension('DublinCore')->getAuthors(); - if (!empty($authorsDc)) { - foreach ($authorsDc as $author) { - $authors[] = array( - 'name' => $author['name'] - ); - } - } - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $list = $this->xpath->query($this->xpathQueryRss . '//author'); - } else { - $list = $this->xpath->query($this->xpathQueryRdf . '//rss:author'); - } - if ($list->length) { - foreach ($list as $author) { - $string = trim($author->nodeValue); - $email = null; - $name = null; - $data = array(); - // Pretty rough parsing - but it's a catchall - if (preg_match("/^.*@[^ ]*/", $string, $matches)) { - $data['email'] = trim($matches[0]); - if (preg_match("/\((.*)\)$/", $string, $matches)) { - $data['name'] = $matches[1]; - } - $authors[] = $data; - } - } - } - - if (count($authors) == 0) { - $authors = $this->getExtension('Atom')->getAuthors(); - } else { - $authors = new Reader\Collection\Author( - Reader\Reader::arrayUnique($authors) - ); - } - - if (count($authors) == 0) { - $authors = null; - } - - $this->data['authors'] = $authors; - - return $this->data['authors']; - } - - /** - * Get the entry content - * - * @return string - */ - public function getContent() - { - if (array_key_exists('content', $this->data)) { - return $this->data['content']; - } - - $content = $this->getExtension('Content')->getContent(); - - if (!$content) { - $content = $this->getDescription(); - } - - if (empty($content)) { - $content = $this->getExtension('Atom')->getContent(); - } - - $this->data['content'] = $content; - - return $this->data['content']; - } - - /** - * Get the entry's date of creation - * - * @return string - */ - public function getDateCreated() - { - return $this->getDateModified(); - } - - /** - * Get the entry's date of modification - * - * @throws Exception\RuntimeException - * @return string - */ - public function getDateModified() - { - if (array_key_exists('datemodified', $this->data)) { - return $this->data['datemodified']; - } - - $dateModified = null; - $date = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $dateModified = $this->xpath->evaluate('string(' . $this->xpathQueryRss . '/pubDate)'); - if ($dateModified) { - $dateModifiedParsed = strtotime($dateModified); - if ($dateModifiedParsed) { - $date = new DateTime('@' . $dateModifiedParsed); - } else { - $dateStandards = array(DateTime::RSS, DateTime::RFC822, - DateTime::RFC2822, null); - foreach ($dateStandards as $standard) { - try { - $date = date_create_from_format($standard, $dateModified); - break; - } catch (\Exception $e) { - if ($standard == null) { - throw new Exception\RuntimeException( - 'Could not load date due to unrecognised' - .' format (should follow RFC 822 or 2822):' - . $e->getMessage(), - 0, $e - ); - } - } - } - } - } - } - - if (!$date) { - $date = $this->getExtension('DublinCore')->getDate(); - } - - if (!$date) { - $date = $this->getExtension('Atom')->getDateModified(); - } - - if (!$date) { - $date = null; - } - - $this->data['datemodified'] = $date; - - return $this->data['datemodified']; - } - - /** - * Get the entry description - * - * @return string - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $description = $this->xpath->evaluate('string(' . $this->xpathQueryRss . '/description)'); - } else { - $description = $this->xpath->evaluate('string(' . $this->xpathQueryRdf . '/rss:description)'); - } - - if (!$description) { - $description = $this->getExtension('DublinCore')->getDescription(); - } - - if (empty($description)) { - $description = $this->getExtension('Atom')->getDescription(); - } - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the entry enclosure - * @return string - */ - public function getEnclosure() - { - if (array_key_exists('enclosure', $this->data)) { - return $this->data['enclosure']; - } - - $enclosure = null; - - if ($this->getType() == Reader\Reader::TYPE_RSS_20) { - $nodeList = $this->xpath->query($this->xpathQueryRss . '/enclosure'); - - if ($nodeList->length > 0) { - $enclosure = new \stdClass(); - $enclosure->url = $nodeList->item(0)->getAttribute('url'); - $enclosure->length = $nodeList->item(0)->getAttribute('length'); - $enclosure->type = $nodeList->item(0)->getAttribute('type'); - } - } - - if (!$enclosure) { - $enclosure = $this->getExtension('Atom')->getEnclosure(); - } - - $this->data['enclosure'] = $enclosure; - - return $this->data['enclosure']; - } - - /** - * Get the entry ID - * - * @return string - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $id = $this->xpath->evaluate('string(' . $this->xpathQueryRss . '/guid)'); - } - - if (!$id) { - $id = $this->getExtension('DublinCore')->getId(); - } - - if (empty($id)) { - $id = $this->getExtension('Atom')->getId(); - } - - if (!$id) { - if ($this->getPermalink()) { - $id = $this->getPermalink(); - } elseif ($this->getTitle()) { - $id = $this->getTitle(); - } else { - $id = null; - } - } - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get a specific link - * - * @param int $index - * @return string - */ - public function getLink($index = 0) - { - if (!array_key_exists('links', $this->data)) { - $this->getLinks(); - } - - if (isset($this->data['links'][$index])) { - return $this->data['links'][$index]; - } - - return null; - } - - /** - * Get all links - * - * @return array - */ - public function getLinks() - { - if (array_key_exists('links', $this->data)) { - return $this->data['links']; - } - - $links = array(); - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $list = $this->xpath->query($this->xpathQueryRss . '//link'); - } else { - $list = $this->xpath->query($this->xpathQueryRdf . '//rss:link'); - } - - if (!$list->length) { - $links = $this->getExtension('Atom')->getLinks(); - } else { - foreach ($list as $link) { - $links[] = $link->nodeValue; - } - } - - $this->data['links'] = $links; - - return $this->data['links']; - } - - /** - * Get all categories - * - * @return Reader\Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $list = $this->xpath->query($this->xpathQueryRss . '//category'); - } else { - $list = $this->xpath->query($this->xpathQueryRdf . '//rss:category'); - } - - if ($list->length) { - $categoryCollection = new Reader\Collection\Category; - foreach ($list as $category) { - $categoryCollection[] = array( - 'term' => $category->nodeValue, - 'scheme' => $category->getAttribute('domain'), - 'label' => $category->nodeValue, - ); - } - } else { - $categoryCollection = $this->getExtension('DublinCore')->getCategories(); - } - - if (count($categoryCollection) == 0) { - $categoryCollection = $this->getExtension('Atom')->getCategories(); - } - - $this->data['categories'] = $categoryCollection; - - return $this->data['categories']; - } - - /** - * Get a permalink to the entry - * - * @return string - */ - public function getPermalink() - { - return $this->getLink(0); - } - - /** - * Get the entry title - * - * @return string - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $title = $this->xpath->evaluate('string(' . $this->xpathQueryRss . '/title)'); - } else { - $title = $this->xpath->evaluate('string(' . $this->xpathQueryRdf . '/rss:title)'); - } - - if (!$title) { - $title = $this->getExtension('DublinCore')->getTitle(); - } - - if (!$title) { - $title = $this->getExtension('Atom')->getTitle(); - } - - if (!$title) { - $title = null; - } - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * Get the number of comments/replies for current entry - * - * @return string|null - */ - public function getCommentCount() - { - if (array_key_exists('commentcount', $this->data)) { - return $this->data['commentcount']; - } - - $commentcount = $this->getExtension('Slash')->getCommentCount(); - - if (!$commentcount) { - $commentcount = $this->getExtension('Thread')->getCommentCount(); - } - - if (!$commentcount) { - $commentcount = $this->getExtension('Atom')->getCommentCount(); - } - - if (!$commentcount) { - $commentcount = null; - } - - $this->data['commentcount'] = $commentcount; - - return $this->data['commentcount']; - } - - /** - * Returns a URI pointing to the HTML page where comments can be made on this entry - * - * @return string - */ - public function getCommentLink() - { - if (array_key_exists('commentlink', $this->data)) { - return $this->data['commentlink']; - } - - $commentlink = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $commentlink = $this->xpath->evaluate('string(' . $this->xpathQueryRss . '/comments)'); - } - - if (!$commentlink) { - $commentlink = $this->getExtension('Atom')->getCommentLink(); - } - - if (!$commentlink) { - $commentlink = null; - } - - $this->data['commentlink'] = $commentlink; - - return $this->data['commentlink']; - } - - /** - * Returns a URI pointing to a feed of all comments for this entry - * - * @return string - */ - public function getCommentFeedLink() - { - if (array_key_exists('commentfeedlink', $this->data)) { - return $this->data['commentfeedlink']; - } - - $commentfeedlink = $this->getExtension('WellFormedWeb')->getCommentFeedLink(); - - if (!$commentfeedlink) { - $commentfeedlink = $this->getExtension('Atom')->getCommentFeedLink('rss'); - } - - if (!$commentfeedlink) { - $commentfeedlink = $this->getExtension('Atom')->getCommentFeedLink('rdf'); - } - - if (!$commentfeedlink) { - $commentfeedlink = null; - } - - $this->data['commentfeedlink'] = $commentfeedlink; - - return $this->data['commentfeedlink']; - } - - /** - * Set the XPath query (incl. on all Extensions) - * - * @param DOMXPath $xpath - * @return void - */ - public function setXpath(DOMXPath $xpath) - { - parent::setXpath($xpath); - foreach ($this->extensions as $extension) { - $extension->setXpath($this->xpath); - } - } -} diff --git a/library/Zend/Feed/Reader/Exception/BadMethodCallException.php b/library/Zend/Feed/Reader/Exception/BadMethodCallException.php deleted file mode 100755 index 3e265088a..000000000 --- a/library/Zend/Feed/Reader/Exception/BadMethodCallException.php +++ /dev/null @@ -1,18 +0,0 @@ -entry = $entry; - $this->domDocument = $entry->ownerDocument; - return $this; - } - - /** - * Get the entry DOMElement - * - * @return DOMElement - */ - public function getEntryElement() - { - return $this->entry; - } - - /** - * Set the entry key - * - * @param string $entryKey - * @return AbstractEntry - */ - public function setEntryKey($entryKey) - { - $this->entryKey = $entryKey; - return $this; - } - - /** - * Get the DOM - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->domDocument; - } - - /** - * Get the Entry's encoding - * - * @return string - */ - public function getEncoding() - { - $assumed = $this->getDomDocument()->encoding; - return $assumed; - } - - /** - * Set the entry type - * - * Has side effect of setting xpath prefix - * - * @param string $type - * @return AbstractEntry - */ - public function setType($type) - { - if (null === $type) { - $this->data['type'] = null; - return $this; - } - - $this->data['type'] = $type; - if ($type === Reader\Reader::TYPE_RSS_10 - || $type === Reader\Reader::TYPE_RSS_090 - ) { - $this->setXpathPrefix('//rss:item[' . ($this->entryKey + 1) . ']'); - return $this; - } - - if ($type === Reader\Reader::TYPE_ATOM_10 - || $type === Reader\Reader::TYPE_ATOM_03 - ) { - $this->setXpathPrefix('//atom:entry[' . ($this->entryKey + 1) . ']'); - return $this; - } - - $this->setXpathPrefix('//item[' . ($this->entryKey + 1) . ']'); - return $this; - } - - /** - * Get the entry type - * - * @return string - */ - public function getType() - { - $type = $this->data['type']; - if ($type === null) { - $type = Reader\Reader::detectType($this->getEntryElement(), true); - $this->setType($type); - } - - return $type; - } - - /** - * Set the XPath query - * - * @param DOMXPath $xpath - * @return AbstractEntry - */ - public function setXpath(DOMXPath $xpath) - { - $this->xpath = $xpath; - $this->registerNamespaces(); - return $this; - } - - /** - * Get the XPath query object - * - * @return DOMXPath - */ - public function getXpath() - { - if (!$this->xpath) { - $this->setXpath(new DOMXPath($this->getDomDocument())); - } - return $this->xpath; - } - - /** - * Serialize the entry to an array - * - * @return array - */ - public function toArray() - { - return $this->data; - } - - /** - * Get the XPath prefix - * - * @return string - */ - public function getXpathPrefix() - { - return $this->xpathPrefix; - } - - /** - * Set the XPath prefix - * - * @param string $prefix - * @return AbstractEntry - */ - public function setXpathPrefix($prefix) - { - $this->xpathPrefix = $prefix; - return $this; - } - - /** - * Register XML namespaces - * - * @return void - */ - abstract protected function registerNamespaces(); -} diff --git a/library/Zend/Feed/Reader/Extension/AbstractFeed.php b/library/Zend/Feed/Reader/Extension/AbstractFeed.php deleted file mode 100755 index 1bea2e498..000000000 --- a/library/Zend/Feed/Reader/Extension/AbstractFeed.php +++ /dev/null @@ -1,176 +0,0 @@ -domDocument = $dom; - return $this; - } - - /** - * Get the DOM - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->domDocument; - } - - /** - * Get the Feed's encoding - * - * @return string - */ - public function getEncoding() - { - $assumed = $this->getDomDocument()->encoding; - return $assumed; - } - - /** - * Set the feed type - * - * @param string $type - * @return AbstractFeed - */ - public function setType($type) - { - $this->data['type'] = $type; - return $this; - } - - /** - * Get the feed type - * - * If null, it will attempt to autodetect the type. - * - * @return string - */ - public function getType() - { - $type = $this->data['type']; - if (null === $type) { - $type = Reader\Reader::detectType($this->getDomDocument()); - $this->setType($type); - } - return $type; - } - - - /** - * Return the feed as an array - * - * @return array - */ - public function toArray() // untested - { - return $this->data; - } - - /** - * Set the XPath query - * - * @param DOMXPath $xpath - * @return AbstractEntry - */ - public function setXpath(DOMXPath $xpath = null) - { - if (null === $xpath) { - $this->xpath = null; - return $this; - } - - $this->xpath = $xpath; - $this->registerNamespaces(); - return $this; - } - - /** - * Get the DOMXPath object - * - * @return string - */ - public function getXpath() - { - if (null === $this->xpath) { - $this->setXpath(new DOMXPath($this->getDomDocument())); - } - - return $this->xpath; - } - - /** - * Get the XPath prefix - * - * @return string - */ - public function getXpathPrefix() - { - return $this->xpathPrefix; - } - - /** - * Set the XPath prefix - * - * @param string $prefix - * @return void - */ - public function setXpathPrefix($prefix) - { - $this->xpathPrefix = $prefix; - } - - /** - * Register the default namespaces for the current feed format - */ - abstract protected function registerNamespaces(); -} diff --git a/library/Zend/Feed/Reader/Extension/Atom/Entry.php b/library/Zend/Feed/Reader/Extension/Atom/Entry.php deleted file mode 100755 index 9e20321cd..000000000 --- a/library/Zend/Feed/Reader/Extension/Atom/Entry.php +++ /dev/null @@ -1,630 +0,0 @@ -getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return Collection\Author - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $authors = array(); - $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom:author'); - - if (!$list->length) { - /** - * TODO: Limit query to feed level els only! - */ - $list = $this->getXpath()->query('//atom:author'); - } - - if ($list->length) { - foreach ($list as $author) { - $author = $this->getAuthorFromElement($author); - if (!empty($author)) { - $authors[] = $author; - } - } - } - - if (count($authors) == 0) { - $authors = new Collection\Author(); - } else { - $authors = new Collection\Author( - Reader\Reader::arrayUnique($authors) - ); - } - - $this->data['authors'] = $authors; - return $this->data['authors']; - } - - /** - * Get the entry content - * - * @return string - */ - public function getContent() - { - if (array_key_exists('content', $this->data)) { - return $this->data['content']; - } - - $content = null; - - $el = $this->getXpath()->query($this->getXpathPrefix() . '/atom:content'); - if ($el->length > 0) { - $el = $el->item(0); - $type = $el->getAttribute('type'); - switch ($type) { - case '': - case 'text': - case 'text/plain': - case 'html': - case 'text/html': - $content = $el->nodeValue; - break; - case 'xhtml': - $this->getXpath()->registerNamespace('xhtml', 'http://www.w3.org/1999/xhtml'); - $xhtml = $this->getXpath()->query( - $this->getXpathPrefix() . '/atom:content/xhtml:div' - )->item(0); - $d = new DOMDocument('1.0', $this->getEncoding()); - $xhtmls = $d->importNode($xhtml, true); - $d->appendChild($xhtmls); - $content = $this->collectXhtml( - $d->saveXML(), - $d->lookupPrefix('http://www.w3.org/1999/xhtml') - ); - break; - } - } - - if (!$content) { - $content = $this->getDescription(); - } - - $this->data['content'] = trim($content); - - return $this->data['content']; - } - - /** - * Parse out XHTML to remove the namespacing - * - * @param $xhtml - * @param $prefix - * @return mixed - */ - protected function collectXhtml($xhtml, $prefix) - { - if (!empty($prefix)) { - $prefix = $prefix . ':'; - } - $matches = array( - "/<\?xml[^<]*>[^<]*<" . $prefix . "div[^<]*/", - "/<\/" . $prefix . "div>\s*$/" - ); - $xhtml = preg_replace($matches, '', $xhtml); - if (!empty($prefix)) { - $xhtml = preg_replace("/(<[\/]?)" . $prefix . "([a-zA-Z]+)/", '$1$2', $xhtml); - } - return $xhtml; - } - - /** - * Get the entry creation date - * - * @return string - */ - public function getDateCreated() - { - if (array_key_exists('datecreated', $this->data)) { - return $this->data['datecreated']; - } - - $date = null; - - if ($this->getAtomType() === Reader\Reader::TYPE_ATOM_03) { - $dateCreated = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:created)'); - } else { - $dateCreated = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:published)'); - } - - if ($dateCreated) { - $date = new DateTime($dateCreated); - } - - $this->data['datecreated'] = $date; - - return $this->data['datecreated']; - } - - /** - * Get the entry modification date - * - * @return string - */ - public function getDateModified() - { - if (array_key_exists('datemodified', $this->data)) { - return $this->data['datemodified']; - } - - $date = null; - - if ($this->getAtomType() === Reader\Reader::TYPE_ATOM_03) { - $dateModified = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:modified)'); - } else { - $dateModified = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:updated)'); - } - - if ($dateModified) { - $date = new DateTime($dateModified); - } - - $this->data['datemodified'] = $date; - - return $this->data['datemodified']; - } - - /** - * Get the entry description - * - * @return string - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:summary)'); - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the entry enclosure - * - * @return string - */ - public function getEnclosure() - { - if (array_key_exists('enclosure', $this->data)) { - return $this->data['enclosure']; - } - - $enclosure = null; - - $nodeList = $this->getXpath()->query($this->getXpathPrefix() . '/atom:link[@rel="enclosure"]'); - - if ($nodeList->length > 0) { - $enclosure = new stdClass(); - $enclosure->url = $nodeList->item(0)->getAttribute('href'); - $enclosure->length = $nodeList->item(0)->getAttribute('length'); - $enclosure->type = $nodeList->item(0)->getAttribute('type'); - } - - $this->data['enclosure'] = $enclosure; - - return $this->data['enclosure']; - } - - /** - * Get the entry ID - * - * @return string - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:id)'); - - if (!$id) { - if ($this->getPermalink()) { - $id = $this->getPermalink(); - } elseif ($this->getTitle()) { - $id = $this->getTitle(); - } else { - $id = null; - } - } - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get the base URI of the feed (if set). - * - * @return string|null - */ - public function getBaseUrl() - { - if (array_key_exists('baseUrl', $this->data)) { - return $this->data['baseUrl']; - } - - $baseUrl = $this->getXpath()->evaluate('string(' - . $this->getXpathPrefix() . '/@xml:base[1]' - . ')'); - - if (!$baseUrl) { - $baseUrl = $this->getXpath()->evaluate('string(//@xml:base[1])'); - } - - if (!$baseUrl) { - $baseUrl = null; - } - - $this->data['baseUrl'] = $baseUrl; - - return $this->data['baseUrl']; - } - - /** - * Get a specific link - * - * @param int $index - * @return string - */ - public function getLink($index = 0) - { - if (!array_key_exists('links', $this->data)) { - $this->getLinks(); - } - - if (isset($this->data['links'][$index])) { - return $this->data['links'][$index]; - } - - return null; - } - - /** - * Get all links - * - * @return array - */ - public function getLinks() - { - if (array_key_exists('links', $this->data)) { - return $this->data['links']; - } - - $links = array(); - - $list = $this->getXpath()->query( - $this->getXpathPrefix() . '//atom:link[@rel="alternate"]/@href' . '|' . - $this->getXpathPrefix() . '//atom:link[not(@rel)]/@href' - ); - - if ($list->length) { - foreach ($list as $link) { - $links[] = $this->absolutiseUri($link->value); - } - } - - $this->data['links'] = $links; - - return $this->data['links']; - } - - /** - * Get a permalink to the entry - * - * @return string - */ - public function getPermalink() - { - return $this->getLink(0); - } - - /** - * Get the entry title - * - * @return string - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:title)'); - - if (!$title) { - $title = null; - } - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * Get the number of comments/replies for current entry - * - * @return int - */ - public function getCommentCount() - { - if (array_key_exists('commentcount', $this->data)) { - return $this->data['commentcount']; - } - - $count = null; - - $this->getXpath()->registerNamespace('thread10', 'http://purl.org/syndication/thread/1.0'); - $list = $this->getXpath()->query( - $this->getXpathPrefix() . '//atom:link[@rel="replies"]/@thread10:count' - ); - - if ($list->length) { - $count = $list->item(0)->value; - } - - $this->data['commentcount'] = $count; - - return $this->data['commentcount']; - } - - /** - * Returns a URI pointing to the HTML page where comments can be made on this entry - * - * @return string - */ - public function getCommentLink() - { - if (array_key_exists('commentlink', $this->data)) { - return $this->data['commentlink']; - } - - $link = null; - - $list = $this->getXpath()->query( - $this->getXpathPrefix() . '//atom:link[@rel="replies" and @type="text/html"]/@href' - ); - - if ($list->length) { - $link = $list->item(0)->value; - $link = $this->absolutiseUri($link); - } - - $this->data['commentlink'] = $link; - - return $this->data['commentlink']; - } - - /** - * Returns a URI pointing to a feed of all comments for this entry - * - * @param string $type - * @return string - */ - public function getCommentFeedLink($type = 'atom') - { - if (array_key_exists('commentfeedlink', $this->data)) { - return $this->data['commentfeedlink']; - } - - $link = null; - - $list = $this->getXpath()->query( - $this->getXpathPrefix() . '//atom:link[@rel="replies" and @type="application/' . $type.'+xml"]/@href' - ); - - if ($list->length) { - $link = $list->item(0)->value; - $link = $this->absolutiseUri($link); - } - - $this->data['commentfeedlink'] = $link; - - return $this->data['commentfeedlink']; - } - - /** - * Get all categories - * - * @return Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - if ($this->getAtomType() == Reader\Reader::TYPE_ATOM_10) { - $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom:category'); - } else { - /** - * Since Atom 0.3 did not support categories, it would have used the - * Dublin Core extension. However there is a small possibility Atom 0.3 - * may have been retrofitted to use Atom 1.0 instead. - */ - $this->getXpath()->registerNamespace('atom10', Reader\Reader::NAMESPACE_ATOM_10); - $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom10:category'); - } - - if ($list->length) { - $categoryCollection = new Collection\Category; - foreach ($list as $category) { - $categoryCollection[] = array( - 'term' => $category->getAttribute('term'), - 'scheme' => $category->getAttribute('scheme'), - 'label' => $category->getAttribute('label') - ); - } - } else { - return new Collection\Category; - } - - $this->data['categories'] = $categoryCollection; - - return $this->data['categories']; - } - - /** - * Get source feed metadata from the entry - * - * @return Reader\Feed\Atom\Source|null - */ - public function getSource() - { - if (array_key_exists('source', $this->data)) { - return $this->data['source']; - } - - $source = null; - // TODO: Investigate why _getAtomType() fails here. Is it even needed? - if ($this->getType() == Reader\Reader::TYPE_ATOM_10) { - $list = $this->getXpath()->query($this->getXpathPrefix() . '/atom:source[1]'); - if ($list->length) { - $element = $list->item(0); - $source = new Reader\Feed\Atom\Source($element, $this->getXpathPrefix()); - } - } - - $this->data['source'] = $source; - return $this->data['source']; - } - - /** - * Attempt to absolutise the URI, i.e. if a relative URI apply the - * xml:base value as a prefix to turn into an absolute URI. - * - * @param $link - * @return string - */ - protected function absolutiseUri($link) - { - if (!Uri::factory($link)->isAbsolute()) { - if ($this->getBaseUrl() !== null) { - $link = $this->getBaseUrl() . $link; - if (!Uri::factory($link)->isValid()) { - $link = null; - } - } - } - return $link; - } - - /** - * Get an author entry - * - * @param DOMElement $element - * @return string - */ - protected function getAuthorFromElement(DOMElement $element) - { - $author = array(); - - $emailNode = $element->getElementsByTagName('email'); - $nameNode = $element->getElementsByTagName('name'); - $uriNode = $element->getElementsByTagName('uri'); - - if ($emailNode->length && strlen($emailNode->item(0)->nodeValue) > 0) { - $author['email'] = $emailNode->item(0)->nodeValue; - } - - if ($nameNode->length && strlen($nameNode->item(0)->nodeValue) > 0) { - $author['name'] = $nameNode->item(0)->nodeValue; - } - - if ($uriNode->length && strlen($uriNode->item(0)->nodeValue) > 0) { - $author['uri'] = $uriNode->item(0)->nodeValue; - } - - if (empty($author)) { - return null; - } - return $author; - } - - /** - * Register the default namespaces for the current feed format - */ - protected function registerNamespaces() - { - switch ($this->getAtomType()) { - case Reader\Reader::TYPE_ATOM_03: - $this->getXpath()->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_03); - break; - default: - $this->getXpath()->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_10); - break; - } - } - - /** - * Detect the presence of any Atom namespaces in use - * - * @return string - */ - protected function getAtomType() - { - $dom = $this->getDomDocument(); - $prefixAtom03 = $dom->lookupPrefix(Reader\Reader::NAMESPACE_ATOM_03); - $prefixAtom10 = $dom->lookupPrefix(Reader\Reader::NAMESPACE_ATOM_10); - if ($dom->isDefaultNamespace(Reader\Reader::NAMESPACE_ATOM_03) - || !empty($prefixAtom03)) { - return Reader\Reader::TYPE_ATOM_03; - } - if ($dom->isDefaultNamespace(Reader\Reader::NAMESPACE_ATOM_10) - || !empty($prefixAtom10)) { - return Reader\Reader::TYPE_ATOM_10; - } - } -} diff --git a/library/Zend/Feed/Reader/Extension/Atom/Feed.php b/library/Zend/Feed/Reader/Extension/Atom/Feed.php deleted file mode 100755 index 986d23fdb..000000000 --- a/library/Zend/Feed/Reader/Extension/Atom/Feed.php +++ /dev/null @@ -1,536 +0,0 @@ -getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return Collection\Author - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $list = $this->xpath->query('//atom:author'); - - $authors = array(); - - if ($list->length) { - foreach ($list as $author) { - $author = $this->getAuthorFromElement($author); - if (!empty($author)) { - $authors[] = $author; - } - } - } - - if (count($authors) == 0) { - $authors = new Collection\Author(); - } else { - $authors = new Collection\Author( - Reader\Reader::arrayUnique($authors) - ); - } - - $this->data['authors'] = $authors; - - return $this->data['authors']; - } - - /** - * Get the copyright entry - * - * @return string|null - */ - public function getCopyright() - { - if (array_key_exists('copyright', $this->data)) { - return $this->data['copyright']; - } - - $copyright = null; - - if ($this->getType() === Reader\Reader::TYPE_ATOM_03) { - $copyright = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:copyright)'); - } else { - $copyright = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:rights)'); - } - - if (!$copyright) { - $copyright = null; - } - - $this->data['copyright'] = $copyright; - - return $this->data['copyright']; - } - - /** - * Get the feed creation date - * - * @return DateTime|null - */ - public function getDateCreated() - { - if (array_key_exists('datecreated', $this->data)) { - return $this->data['datecreated']; - } - - $date = null; - - if ($this->getType() === Reader\Reader::TYPE_ATOM_03) { - $dateCreated = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:created)'); - } else { - $dateCreated = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:published)'); - } - - if ($dateCreated) { - $date = new DateTime($dateCreated); - } - - $this->data['datecreated'] = $date; - - return $this->data['datecreated']; - } - - /** - * Get the feed modification date - * - * @return DateTime|null - */ - public function getDateModified() - { - if (array_key_exists('datemodified', $this->data)) { - return $this->data['datemodified']; - } - - $date = null; - - if ($this->getType() === Reader\Reader::TYPE_ATOM_03) { - $dateModified = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:modified)'); - } else { - $dateModified = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:updated)'); - } - - if ($dateModified) { - $date = new DateTime($dateModified); - } - - $this->data['datemodified'] = $date; - - return $this->data['datemodified']; - } - - /** - * Get the feed description - * - * @return string|null - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = null; - - if ($this->getType() === Reader\Reader::TYPE_ATOM_03) { - $description = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:tagline)'); - } else { - $description = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:subtitle)'); - } - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the feed generator entry - * - * @return string|null - */ - public function getGenerator() - { - if (array_key_exists('generator', $this->data)) { - return $this->data['generator']; - } - // TODO: Add uri support - $generator = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:generator)'); - - if (!$generator) { - $generator = null; - } - - $this->data['generator'] = $generator; - - return $this->data['generator']; - } - - /** - * Get the feed ID - * - * @return string|null - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:id)'); - - if (!$id) { - if ($this->getLink()) { - $id = $this->getLink(); - } elseif ($this->getTitle()) { - $id = $this->getTitle(); - } else { - $id = null; - } - } - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get the feed language - * - * @return string|null - */ - public function getLanguage() - { - if (array_key_exists('language', $this->data)) { - return $this->data['language']; - } - - $language = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:lang)'); - - if (!$language) { - $language = $this->xpath->evaluate('string(//@xml:lang[1])'); - } - - if (!$language) { - $language = null; - } - - $this->data['language'] = $language; - - return $this->data['language']; - } - - /** - * Get the feed image - * - * @return array|null - */ - public function getImage() - { - if (array_key_exists('image', $this->data)) { - return $this->data['image']; - } - - $imageUrl = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:logo)'); - - if (!$imageUrl) { - $image = null; - } else { - $image = array('uri' => $imageUrl); - } - - $this->data['image'] = $image; - - return $this->data['image']; - } - - /** - * Get the base URI of the feed (if set). - * - * @return string|null - */ - public function getBaseUrl() - { - if (array_key_exists('baseUrl', $this->data)) { - return $this->data['baseUrl']; - } - - $baseUrl = $this->xpath->evaluate('string(//@xml:base[1])'); - - if (!$baseUrl) { - $baseUrl = null; - } - $this->data['baseUrl'] = $baseUrl; - - return $this->data['baseUrl']; - } - - /** - * Get a link to the source website - * - * @return string|null - */ - public function getLink() - { - if (array_key_exists('link', $this->data)) { - return $this->data['link']; - } - - $link = null; - - $list = $this->xpath->query( - $this->getXpathPrefix() . '/atom:link[@rel="alternate"]/@href' . '|' . - $this->getXpathPrefix() . '/atom:link[not(@rel)]/@href' - ); - - if ($list->length) { - $link = $list->item(0)->nodeValue; - $link = $this->absolutiseUri($link); - } - - $this->data['link'] = $link; - - return $this->data['link']; - } - - /** - * Get a link to the feed's XML Url - * - * @return string|null - */ - public function getFeedLink() - { - if (array_key_exists('feedlink', $this->data)) { - return $this->data['feedlink']; - } - - $link = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:link[@rel="self"]/@href)'); - - $link = $this->absolutiseUri($link); - - $this->data['feedlink'] = $link; - - return $this->data['feedlink']; - } - - /** - * Get an array of any supported Pusubhubbub endpoints - * - * @return array|null - */ - public function getHubs() - { - if (array_key_exists('hubs', $this->data)) { - return $this->data['hubs']; - } - $hubs = array(); - - $list = $this->xpath->query($this->getXpathPrefix() - . '//atom:link[@rel="hub"]/@href'); - - if ($list->length) { - foreach ($list as $uri) { - $hubs[] = $this->absolutiseUri($uri->nodeValue); - } - } else { - $hubs = null; - } - - $this->data['hubs'] = $hubs; - - return $this->data['hubs']; - } - - /** - * Get the feed title - * - * @return string|null - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:title)'); - - if (!$title) { - $title = null; - } - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * Get all categories - * - * @return Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - if ($this->getType() == Reader\Reader::TYPE_ATOM_10) { - $list = $this->xpath->query($this->getXpathPrefix() . '/atom:category'); - } else { - /** - * Since Atom 0.3 did not support categories, it would have used the - * Dublin Core extension. However there is a small possibility Atom 0.3 - * may have been retrofittied to use Atom 1.0 instead. - */ - $this->xpath->registerNamespace('atom10', Reader\Reader::NAMESPACE_ATOM_10); - $list = $this->xpath->query($this->getXpathPrefix() . '/atom10:category'); - } - - if ($list->length) { - $categoryCollection = new Collection\Category; - foreach ($list as $category) { - $categoryCollection[] = array( - 'term' => $category->getAttribute('term'), - 'scheme' => $category->getAttribute('scheme'), - 'label' => $category->getAttribute('label') - ); - } - } else { - return new Collection\Category; - } - - $this->data['categories'] = $categoryCollection; - - return $this->data['categories']; - } - - /** - * Get an author entry in RSS format - * - * @param DOMElement $element - * @return string - */ - protected function getAuthorFromElement(DOMElement $element) - { - $author = array(); - - $emailNode = $element->getElementsByTagName('email'); - $nameNode = $element->getElementsByTagName('name'); - $uriNode = $element->getElementsByTagName('uri'); - - if ($emailNode->length && strlen($emailNode->item(0)->nodeValue) > 0) { - $author['email'] = $emailNode->item(0)->nodeValue; - } - - if ($nameNode->length && strlen($nameNode->item(0)->nodeValue) > 0) { - $author['name'] = $nameNode->item(0)->nodeValue; - } - - if ($uriNode->length && strlen($uriNode->item(0)->nodeValue) > 0) { - $author['uri'] = $uriNode->item(0)->nodeValue; - } - - if (empty($author)) { - return null; - } - return $author; - } - - /** - * Attempt to absolutise the URI, i.e. if a relative URI apply the - * xml:base value as a prefix to turn into an absolute URI. - */ - protected function absolutiseUri($link) - { - if (!Uri::factory($link)->isAbsolute()) { - if ($this->getBaseUrl() !== null) { - $link = $this->getBaseUrl() . $link; - if (!Uri::factory($link)->isValid()) { - $link = null; - } - } - } - return $link; - } - - /** - * Register the default namespaces for the current feed format - */ - protected function registerNamespaces() - { - if ($this->getType() == Reader\Reader::TYPE_ATOM_10 - || $this->getType() == Reader\Reader::TYPE_ATOM_03 - ) { - return; // pre-registered at Feed level - } - $atomDetected = $this->getAtomType(); - switch ($atomDetected) { - case Reader\Reader::TYPE_ATOM_03: - $this->xpath->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_03); - break; - default: - $this->xpath->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_10); - break; - } - } - - /** - * Detect the presence of any Atom namespaces in use - */ - protected function getAtomType() - { - $dom = $this->getDomDocument(); - $prefixAtom03 = $dom->lookupPrefix(Reader\Reader::NAMESPACE_ATOM_03); - $prefixAtom10 = $dom->lookupPrefix(Reader\Reader::NAMESPACE_ATOM_10); - if ($dom->isDefaultNamespace(Reader\Reader::NAMESPACE_ATOM_10) - || !empty($prefixAtom10) - ) { - return Reader\Reader::TYPE_ATOM_10; - } - if ($dom->isDefaultNamespace(Reader\Reader::NAMESPACE_ATOM_03) - || !empty($prefixAtom03) - ) { - return Reader\Reader::TYPE_ATOM_03; - } - } -} diff --git a/library/Zend/Feed/Reader/Extension/Content/Entry.php b/library/Zend/Feed/Reader/Extension/Content/Entry.php deleted file mode 100755 index 9b5f7cb35..000000000 --- a/library/Zend/Feed/Reader/Extension/Content/Entry.php +++ /dev/null @@ -1,36 +0,0 @@ -getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $content = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/content:encoded)'); - } else { - $content = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/content:encoded)'); - } - return $content; - } - - /** - * Register RSS Content Module namespace - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/CreativeCommons/Entry.php b/library/Zend/Feed/Reader/Extension/CreativeCommons/Entry.php deleted file mode 100755 index 1883dc6be..000000000 --- a/library/Zend/Feed/Reader/Extension/CreativeCommons/Entry.php +++ /dev/null @@ -1,72 +0,0 @@ -getLicenses(); - - if (isset($licenses[$index])) { - return $licenses[$index]; - } - - return null; - } - - /** - * Get the entry licenses - * - * @return array - */ - public function getLicenses() - { - $name = 'licenses'; - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } - - $licenses = array(); - $list = $this->xpath->evaluate($this->getXpathPrefix() . '//cc:license'); - - if ($list->length) { - foreach ($list as $license) { - $licenses[] = $license->nodeValue; - } - - $licenses = array_unique($licenses); - } else { - $cc = new Feed(); - $licenses = $cc->getLicenses(); - } - - $this->data[$name] = $licenses; - - return $this->data[$name]; - } - - /** - * Register Creative Commons namespaces - * - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('cc', 'http://backend.userland.com/creativeCommonsRssModule'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/CreativeCommons/Feed.php b/library/Zend/Feed/Reader/Extension/CreativeCommons/Feed.php deleted file mode 100755 index 99977fd44..000000000 --- a/library/Zend/Feed/Reader/Extension/CreativeCommons/Feed.php +++ /dev/null @@ -1,70 +0,0 @@ -getLicenses(); - - if (isset($licenses[$index])) { - return $licenses[$index]; - } - - return null; - } - - /** - * Get the entry licenses - * - * @return array - */ - public function getLicenses() - { - $name = 'licenses'; - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } - - $licenses = array(); - $list = $this->xpath->evaluate('channel/cc:license'); - - if ($list->length) { - foreach ($list as $license) { - $licenses[] = $license->nodeValue; - } - - $licenses = array_unique($licenses); - } - - $this->data[$name] = $licenses; - - return $this->data[$name]; - } - - /** - * Register Creative Commons namespaces - * - * @return void - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('cc', 'http://backend.userland.com/creativeCommonsRssModule'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/DublinCore/Entry.php b/library/Zend/Feed/Reader/Extension/DublinCore/Entry.php deleted file mode 100755 index 2713353ca..000000000 --- a/library/Zend/Feed/Reader/Extension/DublinCore/Entry.php +++ /dev/null @@ -1,238 +0,0 @@ -getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $authors = array(); - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc11:creator'); - - if (!$list->length) { - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc10:creator'); - } - if (!$list->length) { - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc11:publisher'); - - if (!$list->length) { - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc10:publisher'); - } - } - - if ($list->length) { - foreach ($list as $author) { - $authors[] = array( - 'name' => $author->nodeValue - ); - } - $authors = new Collection\Author( - Reader\Reader::arrayUnique($authors) - ); - } else { - $authors = null; - } - - $this->data['authors'] = $authors; - - return $this->data['authors']; - } - - /** - * Get categories (subjects under DC) - * - * @return Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc11:subject'); - - if (!$list->length) { - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc10:subject'); - } - - if ($list->length) { - $categoryCollection = new Collection\Category; - foreach ($list as $category) { - $categoryCollection[] = array( - 'term' => $category->nodeValue, - 'scheme' => null, - 'label' => $category->nodeValue, - ); - } - } else { - $categoryCollection = new Collection\Category; - } - - $this->data['categories'] = $categoryCollection; - return $this->data['categories']; - } - - - /** - * Get the entry content - * - * @return string - */ - public function getContent() - { - return $this->getDescription(); - } - - /** - * Get the entry description - * - * @return string - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = null; - $description = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:description)'); - - if (!$description) { - $description = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:description)'); - } - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the entry ID - * - * @return string - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = null; - $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:identifier)'); - - if (!$id) { - $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:identifier)'); - } - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get the entry title - * - * @return string - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = null; - $title = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:title)'); - - if (!$title) { - $title = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:title)'); - } - - if (!$title) { - $title = null; - } - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * - * - * @return DateTime|null - */ - public function getDate() - { - if (array_key_exists('date', $this->data)) { - return $this->data['date']; - } - - $d = null; - $date = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:date)'); - - if (!$date) { - $date = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:date)'); - } - - if ($date) { - $d = new DateTime($date); - } - - $this->data['date'] = $d; - - return $this->data['date']; - } - - /** - * Register DC namespaces - * - * @return void - */ - protected function registerNamespaces() - { - $this->getXpath()->registerNamespace('dc10', 'http://purl.org/dc/elements/1.0/'); - $this->getXpath()->registerNamespace('dc11', 'http://purl.org/dc/elements/1.1/'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php b/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php deleted file mode 100755 index 2738ac732..000000000 --- a/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php +++ /dev/null @@ -1,281 +0,0 @@ -getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $authors = array(); - $list = $this->getXpath()->query('//dc11:creator'); - - if (!$list->length) { - $list = $this->getXpath()->query('//dc10:creator'); - } - if (!$list->length) { - $list = $this->getXpath()->query('//dc11:publisher'); - - if (!$list->length) { - $list = $this->getXpath()->query('//dc10:publisher'); - } - } - - if ($list->length) { - foreach ($list as $author) { - $authors[] = array( - 'name' => $author->nodeValue - ); - } - $authors = new Collection\Author( - Reader\Reader::arrayUnique($authors) - ); - } else { - $authors = null; - } - - $this->data['authors'] = $authors; - - return $this->data['authors']; - } - - /** - * Get the copyright entry - * - * @return string|null - */ - public function getCopyright() - { - if (array_key_exists('copyright', $this->data)) { - return $this->data['copyright']; - } - - $copyright = null; - $copyright = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:rights)'); - - if (!$copyright) { - $copyright = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:rights)'); - } - - if (!$copyright) { - $copyright = null; - } - - $this->data['copyright'] = $copyright; - - return $this->data['copyright']; - } - - /** - * Get the feed description - * - * @return string|null - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = null; - $description = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:description)'); - - if (!$description) { - $description = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:description)'); - } - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the feed ID - * - * @return string|null - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = null; - $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:identifier)'); - - if (!$id) { - $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:identifier)'); - } - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get the feed language - * - * @return string|null - */ - public function getLanguage() - { - if (array_key_exists('language', $this->data)) { - return $this->data['language']; - } - - $language = null; - $language = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:language)'); - - if (!$language) { - $language = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:language)'); - } - - if (!$language) { - $language = null; - } - - $this->data['language'] = $language; - - return $this->data['language']; - } - - /** - * Get the feed title - * - * @return string|null - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = null; - $title = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:title)'); - - if (!$title) { - $title = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:title)'); - } - - if (!$title) { - $title = null; - } - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * - * - * @return DateTime|null - */ - public function getDate() - { - if (array_key_exists('date', $this->data)) { - return $this->data['date']; - } - - $d = null; - $date = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc11:date)'); - - if (!$date) { - $date = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/dc10:date)'); - } - - if ($date) { - $d = new DateTime($date); - } - - $this->data['date'] = $d; - - return $this->data['date']; - } - - /** - * Get categories (subjects under DC) - * - * @return Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc11:subject'); - - if (!$list->length) { - $list = $this->getXpath()->evaluate($this->getXpathPrefix() . '//dc10:subject'); - } - - if ($list->length) { - $categoryCollection = new Collection\Category; - foreach ($list as $category) { - $categoryCollection[] = array( - 'term' => $category->nodeValue, - 'scheme' => null, - 'label' => $category->nodeValue, - ); - } - } else { - $categoryCollection = new Collection\Category; - } - - $this->data['categories'] = $categoryCollection; - return $this->data['categories']; - } - - /** - * Register the default namespaces for the current feed format - * - * @return void - */ - protected function registerNamespaces() - { - $this->getXpath()->registerNamespace('dc10', 'http://purl.org/dc/elements/1.0/'); - $this->getXpath()->registerNamespace('dc11', 'http://purl.org/dc/elements/1.1/'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/Podcast/Entry.php b/library/Zend/Feed/Reader/Extension/Podcast/Entry.php deleted file mode 100755 index c97e64ff4..000000000 --- a/library/Zend/Feed/Reader/Extension/Podcast/Entry.php +++ /dev/null @@ -1,180 +0,0 @@ -data['author'])) { - return $this->data['author']; - } - - $author = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:author)'); - - if (!$author) { - $author = null; - } - - $this->data['author'] = $author; - - return $this->data['author']; - } - - /** - * Get the entry block - * - * @return string - */ - public function getBlock() - { - if (isset($this->data['block'])) { - return $this->data['block']; - } - - $block = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:block)'); - - if (!$block) { - $block = null; - } - - $this->data['block'] = $block; - - return $this->data['block']; - } - - /** - * Get the entry duration - * - * @return string - */ - public function getDuration() - { - if (isset($this->data['duration'])) { - return $this->data['duration']; - } - - $duration = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:duration)'); - - if (!$duration) { - $duration = null; - } - - $this->data['duration'] = $duration; - - return $this->data['duration']; - } - - /** - * Get the entry explicit - * - * @return string - */ - public function getExplicit() - { - if (isset($this->data['explicit'])) { - return $this->data['explicit']; - } - - $explicit = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:explicit)'); - - if (!$explicit) { - $explicit = null; - } - - $this->data['explicit'] = $explicit; - - return $this->data['explicit']; - } - - /** - * Get the entry keywords - * - * @return string - */ - public function getKeywords() - { - if (isset($this->data['keywords'])) { - return $this->data['keywords']; - } - - $keywords = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:keywords)'); - - if (!$keywords) { - $keywords = null; - } - - $this->data['keywords'] = $keywords; - - return $this->data['keywords']; - } - - /** - * Get the entry subtitle - * - * @return string - */ - public function getSubtitle() - { - if (isset($this->data['subtitle'])) { - return $this->data['subtitle']; - } - - $subtitle = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:subtitle)'); - - if (!$subtitle) { - $subtitle = null; - } - - $this->data['subtitle'] = $subtitle; - - return $this->data['subtitle']; - } - - /** - * Get the entry summary - * - * @return string - */ - public function getSummary() - { - if (isset($this->data['summary'])) { - return $this->data['summary']; - } - - $summary = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:summary)'); - - if (!$summary) { - $summary = null; - } - - $this->data['summary'] = $summary; - - return $this->data['summary']; - } - - /** - * Register iTunes namespace - * - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/Podcast/Feed.php b/library/Zend/Feed/Reader/Extension/Podcast/Feed.php deleted file mode 100755 index 66b13a48b..000000000 --- a/library/Zend/Feed/Reader/Extension/Podcast/Feed.php +++ /dev/null @@ -1,277 +0,0 @@ -data['author'])) { - return $this->data['author']; - } - - $author = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:author)'); - - if (!$author) { - $author = null; - } - - $this->data['author'] = $author; - - return $this->data['author']; - } - - /** - * Get the entry block - * - * @return string - */ - public function getBlock() - { - if (isset($this->data['block'])) { - return $this->data['block']; - } - - $block = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:block)'); - - if (!$block) { - $block = null; - } - - $this->data['block'] = $block; - - return $this->data['block']; - } - - /** - * Get the entry category - * - * @return string - */ - public function getItunesCategories() - { - if (isset($this->data['categories'])) { - return $this->data['categories']; - } - - $categoryList = $this->xpath->query($this->getXpathPrefix() . '/itunes:category'); - - $categories = array(); - - if ($categoryList->length > 0) { - foreach ($categoryList as $node) { - $children = null; - - if ($node->childNodes->length > 0) { - $children = array(); - - foreach ($node->childNodes as $childNode) { - if (!($childNode instanceof DOMText)) { - $children[$childNode->getAttribute('text')] = null; - } - } - } - - $categories[$node->getAttribute('text')] = $children; - } - } - - - if (!$categories) { - $categories = null; - } - - $this->data['categories'] = $categories; - - return $this->data['categories']; - } - - /** - * Get the entry explicit - * - * @return string - */ - public function getExplicit() - { - if (isset($this->data['explicit'])) { - return $this->data['explicit']; - } - - $explicit = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:explicit)'); - - if (!$explicit) { - $explicit = null; - } - - $this->data['explicit'] = $explicit; - - return $this->data['explicit']; - } - - /** - * Get the entry image - * - * @return string - */ - public function getItunesImage() - { - if (isset($this->data['image'])) { - return $this->data['image']; - } - - $image = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:image/@href)'); - - if (!$image) { - $image = null; - } - - $this->data['image'] = $image; - - return $this->data['image']; - } - - /** - * Get the entry keywords - * - * @return string - */ - public function getKeywords() - { - if (isset($this->data['keywords'])) { - return $this->data['keywords']; - } - - $keywords = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:keywords)'); - - if (!$keywords) { - $keywords = null; - } - - $this->data['keywords'] = $keywords; - - return $this->data['keywords']; - } - - /** - * Get the entry's new feed url - * - * @return string - */ - public function getNewFeedUrl() - { - if (isset($this->data['new-feed-url'])) { - return $this->data['new-feed-url']; - } - - $newFeedUrl = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:new-feed-url)'); - - if (!$newFeedUrl) { - $newFeedUrl = null; - } - - $this->data['new-feed-url'] = $newFeedUrl; - - return $this->data['new-feed-url']; - } - - /** - * Get the entry owner - * - * @return string - */ - public function getOwner() - { - if (isset($this->data['owner'])) { - return $this->data['owner']; - } - - $owner = null; - - $email = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:owner/itunes:email)'); - $name = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:owner/itunes:name)'); - - if (!empty($email)) { - $owner = $email . (empty($name) ? '' : ' (' . $name . ')'); - } elseif (!empty($name)) { - $owner = $name; - } - - if (!$owner) { - $owner = null; - } - - $this->data['owner'] = $owner; - - return $this->data['owner']; - } - - /** - * Get the entry subtitle - * - * @return string - */ - public function getSubtitle() - { - if (isset($this->data['subtitle'])) { - return $this->data['subtitle']; - } - - $subtitle = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:subtitle)'); - - if (!$subtitle) { - $subtitle = null; - } - - $this->data['subtitle'] = $subtitle; - - return $this->data['subtitle']; - } - - /** - * Get the entry summary - * - * @return string - */ - public function getSummary() - { - if (isset($this->data['summary'])) { - return $this->data['summary']; - } - - $summary = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/itunes:summary)'); - - if (!$summary) { - $summary = null; - } - - $this->data['summary'] = $summary; - - return $this->data['summary']; - } - - /** - * Register iTunes namespace - * - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/Slash/Entry.php b/library/Zend/Feed/Reader/Extension/Slash/Entry.php deleted file mode 100755 index 9ddb862e2..000000000 --- a/library/Zend/Feed/Reader/Extension/Slash/Entry.php +++ /dev/null @@ -1,122 +0,0 @@ -getData('section'); - } - - /** - * Get the entry department - * - * @return string|null - */ - public function getDepartment() - { - return $this->getData('department'); - } - - /** - * Get the entry hit_parade - * - * @return array - */ - public function getHitParade() - { - $name = 'hit_parade'; - - if (isset($this->data[$name])) { - return $this->data[$name]; - } - - $stringParade = $this->getData($name); - $hitParade = array(); - - if (!empty($stringParade)) { - $stringParade = explode(',', $stringParade); - - foreach ($stringParade as $hit) { - $hitParade[] = $hit + 0; //cast to integer - } - } - - $this->data[$name] = $hitParade; - return $hitParade; - } - - /** - * Get the entry comments - * - * @return int - */ - public function getCommentCount() - { - $name = 'comments'; - - if (isset($this->data[$name])) { - return $this->data[$name]; - } - - $comments = $this->getData($name, 'string'); - - if (!$comments) { - $this->data[$name] = null; - return $this->data[$name]; - } - - return $comments; - } - - /** - * Get the entry data specified by name - * @param string $name - * @param string $type - * - * @return mixed|null - */ - protected function getData($name, $type = 'string') - { - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } - - $data = $this->xpath->evaluate($type . '(' . $this->getXpathPrefix() . '/slash10:' . $name . ')'); - - if (!$data) { - $data = null; - } - - $this->data[$name] = $data; - - return $data; - } - - /** - * Register Slash namespaces - * - * @return void - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('slash10', 'http://purl.org/rss/1.0/modules/slash/'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/Syndication/Feed.php b/library/Zend/Feed/Reader/Extension/Syndication/Feed.php deleted file mode 100755 index db1724c14..000000000 --- a/library/Zend/Feed/Reader/Extension/Syndication/Feed.php +++ /dev/null @@ -1,151 +0,0 @@ -getData($name); - - if ($period === null) { - $this->data[$name] = 'daily'; - return 'daily'; //Default specified by spec - } - - switch ($period) { - case 'hourly': - case 'daily': - case 'weekly': - case 'yearly': - return $period; - default: - throw new Reader\Exception\InvalidArgumentException("Feed specified invalid update period: '$period'." - . " Must be one of hourly, daily, weekly or yearly" - ); - } - } - - /** - * Get update frequency - * - * @return int - */ - public function getUpdateFrequency() - { - $name = 'updateFrequency'; - $freq = $this->getData($name, 'number'); - - if (!$freq || $freq < 1) { - $this->data[$name] = 1; - return 1; - } - - return $freq; - } - - /** - * Get update frequency as ticks - * - * @return int - */ - public function getUpdateFrequencyAsTicks() - { - $name = 'updateFrequency'; - $freq = $this->getData($name, 'number'); - - if (!$freq || $freq < 1) { - $this->data[$name] = 1; - $freq = 1; - } - - $period = $this->getUpdatePeriod(); - $ticks = 1; - - switch ($period) { - case 'yearly': - $ticks *= 52; //TODO: fix generalisation, how? - // no break - case 'weekly': - $ticks *= 7; - // no break - case 'daily': - $ticks *= 24; - // no break - case 'hourly': - $ticks *= 3600; - break; - default: //Never arrive here, exception thrown in getPeriod() - break; - } - - return $ticks / $freq; - } - - /** - * Get update base - * - * @return DateTime|null - */ - public function getUpdateBase() - { - $updateBase = $this->getData('updateBase'); - $date = null; - if ($updateBase) { - $date = DateTime::createFromFormat(DateTime::W3C, $updateBase); - } - return $date; - } - - /** - * Get the entry data specified by name - * - * @param string $name - * @param string $type - * @return mixed|null - */ - private function getData($name, $type = 'string') - { - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } - - $data = $this->xpath->evaluate($type . '(' . $this->getXpathPrefix() . '/syn10:' . $name . ')'); - - if (!$data) { - $data = null; - } - - $this->data[$name] = $data; - - return $data; - } - - /** - * Register Syndication namespaces - * - * @return void - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('syn10', 'http://purl.org/rss/1.0/modules/syndication/'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/Thread/Entry.php b/library/Zend/Feed/Reader/Extension/Thread/Entry.php deleted file mode 100755 index d3bc31587..000000000 --- a/library/Zend/Feed/Reader/Extension/Thread/Entry.php +++ /dev/null @@ -1,72 +0,0 @@ -getData('total'); - } - - /** - * Get the entry data specified by name - * - * @param string $name - * @return mixed|null - */ - protected function getData($name) - { - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } - - $data = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/thread10:' . $name . ')'); - - if (!$data) { - $data = null; - } - - $this->data[$name] = $data; - - return $data; - } - - /** - * Register Atom Thread Extension 1.0 namespace - * - * @return void - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('thread10', 'http://purl.org/syndication/thread/1.0'); - } -} diff --git a/library/Zend/Feed/Reader/Extension/WellFormedWeb/Entry.php b/library/Zend/Feed/Reader/Extension/WellFormedWeb/Entry.php deleted file mode 100755 index 6d5a97705..000000000 --- a/library/Zend/Feed/Reader/Extension/WellFormedWeb/Entry.php +++ /dev/null @@ -1,50 +0,0 @@ -data)) { - return $this->data[$name]; - } - - $data = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/wfw:' . $name . ')'); - - if (!$data) { - $data = null; - } - - $this->data[$name] = $data; - - return $data; - } - - /** - * Register Slash namespaces - * - * @return void - */ - protected function registerNamespaces() - { - $this->xpath->registerNamespace('wfw', 'http://wellformedweb.org/CommentAPI/'); - } -} diff --git a/library/Zend/Feed/Reader/ExtensionManager.php b/library/Zend/Feed/Reader/ExtensionManager.php deleted file mode 100755 index 9103643a3..000000000 --- a/library/Zend/Feed/Reader/ExtensionManager.php +++ /dev/null @@ -1,80 +0,0 @@ -pluginManager = $pluginManager; - } - - /** - * Method overloading - * - * Proxy to composed ExtensionPluginManager instance. - * - * @param string $method - * @param array $args - * @return mixed - * @throws Exception\BadMethodCallException - */ - public function __call($method, $args) - { - if (!method_exists($this->pluginManager, $method)) { - throw new Exception\BadMethodCallException(sprintf( - 'Method by name of %s does not exist in %s', - $method, - __CLASS__ - )); - } - return call_user_func_array(array($this->pluginManager, $method), $args); - } - - /** - * Get the named extension - * - * @param string $name - * @return Extension\AbstractEntry|Extension\AbstractFeed - */ - public function get($name) - { - return $this->pluginManager->get($name); - } - - /** - * Do we have the named extension? - * - * @param string $name - * @return bool - */ - public function has($name) - { - return $this->pluginManager->has($name); - } -} diff --git a/library/Zend/Feed/Reader/ExtensionManagerInterface.php b/library/Zend/Feed/Reader/ExtensionManagerInterface.php deleted file mode 100755 index 4bbb91d9e..000000000 --- a/library/Zend/Feed/Reader/ExtensionManagerInterface.php +++ /dev/null @@ -1,29 +0,0 @@ - 'Zend\Feed\Reader\Extension\Atom\Entry', - 'atomfeed' => 'Zend\Feed\Reader\Extension\Atom\Feed', - 'contententry' => 'Zend\Feed\Reader\Extension\Content\Entry', - 'creativecommonsentry' => 'Zend\Feed\Reader\Extension\CreativeCommons\Entry', - 'creativecommonsfeed' => 'Zend\Feed\Reader\Extension\CreativeCommons\Feed', - 'dublincoreentry' => 'Zend\Feed\Reader\Extension\DublinCore\Entry', - 'dublincorefeed' => 'Zend\Feed\Reader\Extension\DublinCore\Feed', - 'podcastentry' => 'Zend\Feed\Reader\Extension\Podcast\Entry', - 'podcastfeed' => 'Zend\Feed\Reader\Extension\Podcast\Feed', - 'slashentry' => 'Zend\Feed\Reader\Extension\Slash\Entry', - 'syndicationfeed' => 'Zend\Feed\Reader\Extension\Syndication\Feed', - 'threadentry' => 'Zend\Feed\Reader\Extension\Thread\Entry', - 'wellformedwebentry' => 'Zend\Feed\Reader\Extension\WellFormedWeb\Entry', - ); - - /** - * Do not share instances - * - * @var bool - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the extension loaded is of a valid type. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Extension\AbstractEntry - || $plugin instanceof Extension\AbstractFeed - ) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Extension\AbstractFeed ' - . 'or %s\Extension\AbstractEntry', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__, - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Feed/Reader/Feed/AbstractFeed.php b/library/Zend/Feed/Reader/Feed/AbstractFeed.php deleted file mode 100755 index dd616bef7..000000000 --- a/library/Zend/Feed/Reader/Feed/AbstractFeed.php +++ /dev/null @@ -1,307 +0,0 @@ -domDocument = $domDocument; - $this->xpath = new DOMXPath($this->domDocument); - - if ($type !== null) { - $this->data['type'] = $type; - } else { - $this->data['type'] = Reader\Reader::detectType($this->domDocument); - } - $this->registerNamespaces(); - $this->indexEntries(); - $this->loadExtensions(); - } - - /** - * Set an original source URI for the feed being parsed. This value - * is returned from getFeedLink() method if the feed does not carry - * a self-referencing URI. - * - * @param string $uri - */ - public function setOriginalSourceUri($uri) - { - $this->originalSourceUri = $uri; - } - - /** - * Get an original source URI for the feed being parsed. Returns null if - * unset or the feed was not imported from a URI. - * - * @return string|null - */ - public function getOriginalSourceUri() - { - return $this->originalSourceUri; - } - - /** - * Get the number of feed entries. - * Required by the Iterator interface. - * - * @return int - */ - public function count() - { - return count($this->entries); - } - - /** - * Return the current entry - * - * @return \Zend\Feed\Reader\Entry\EntryInterface - */ - public function current() - { - if (substr($this->getType(), 0, 3) == 'rss') { - $reader = new Reader\Entry\Rss($this->entries[$this->key()], $this->key(), $this->getType()); - } else { - $reader = new Reader\Entry\Atom($this->entries[$this->key()], $this->key(), $this->getType()); - } - - $reader->setXpath($this->xpath); - - return $reader; - } - - /** - * Get the DOM - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->domDocument; - } - - /** - * Get the Feed's encoding - * - * @return string - */ - public function getEncoding() - { - $assumed = $this->getDomDocument()->encoding; - if (empty($assumed)) { - $assumed = 'UTF-8'; - } - return $assumed; - } - - /** - * Get feed as xml - * - * @return string - */ - public function saveXml() - { - return $this->getDomDocument()->saveXml(); - } - - /** - * Get the DOMElement representing the items/feed element - * - * @return DOMElement - */ - public function getElement() - { - return $this->getDomDocument()->documentElement; - } - - /** - * Get the DOMXPath object for this feed - * - * @return DOMXPath - */ - public function getXpath() - { - return $this->xpath; - } - - /** - * Get the feed type - * - * @return string - */ - public function getType() - { - return $this->data['type']; - } - - /** - * Return the current feed key - * - * @return int - */ - public function key() - { - return $this->entriesKey; - } - - /** - * Move the feed pointer forward - * - */ - public function next() - { - ++$this->entriesKey; - } - - /** - * Reset the pointer in the feed object - * - */ - public function rewind() - { - $this->entriesKey = 0; - } - - /** - * Check to see if the iterator is still valid - * - * @return bool - */ - public function valid() - { - return 0 <= $this->entriesKey && $this->entriesKey < $this->count(); - } - - public function getExtensions() - { - return $this->extensions; - } - - public function __call($method, $args) - { - foreach ($this->extensions as $extension) { - if (method_exists($extension, $method)) { - return call_user_func_array(array($extension, $method), $args); - } - } - throw new Exception\BadMethodCallException('Method: ' . $method - . 'does not exist and could not be located on a registered Extension'); - } - - /** - * Return an Extension object with the matching name (postfixed with _Feed) - * - * @param string $name - * @return \Zend\Feed\Reader\Extension\AbstractFeed - */ - public function getExtension($name) - { - if (array_key_exists($name . '\\Feed', $this->extensions)) { - return $this->extensions[$name . '\\Feed']; - } - return null; - } - - protected function loadExtensions() - { - $all = Reader\Reader::getExtensions(); - $manager = Reader\Reader::getExtensionManager(); - $feed = $all['feed']; - foreach ($feed as $extension) { - if (in_array($extension, $all['core'])) { - continue; - } - if (!$manager->has($extension)) { - throw new Exception\RuntimeException(sprintf('Unable to load extension "%s"; cannot find class', $extension)); - } - $plugin = $manager->get($extension); - $plugin->setDomDocument($this->getDomDocument()); - $plugin->setType($this->data['type']); - $plugin->setXpath($this->xpath); - $this->extensions[$extension] = $plugin; - } - } - - /** - * Read all entries to the internal entries array - * - */ - abstract protected function indexEntries(); - - /** - * Register the default namespaces for the current feed format - * - */ - abstract protected function registerNamespaces(); -} diff --git a/library/Zend/Feed/Reader/Feed/Atom.php b/library/Zend/Feed/Reader/Feed/Atom.php deleted file mode 100755 index 72efcf760..000000000 --- a/library/Zend/Feed/Reader/Feed/Atom.php +++ /dev/null @@ -1,408 +0,0 @@ -get('Atom\Feed'); - $atomFeed->setDomDocument($dom); - $atomFeed->setType($this->data['type']); - $atomFeed->setXpath($this->xpath); - $this->extensions['Atom\\Feed'] = $atomFeed; - - $atomFeed = $manager->get('DublinCore\Feed'); - $atomFeed->setDomDocument($dom); - $atomFeed->setType($this->data['type']); - $atomFeed->setXpath($this->xpath); - $this->extensions['DublinCore\\Feed'] = $atomFeed; - - foreach ($this->extensions as $extension) { - $extension->setXpathPrefix('/atom:feed'); - } - } - - /** - * Get a single author - * - * @param int $index - * @return string|null - */ - public function getAuthor($index = 0) - { - $authors = $this->getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $authors = $this->getExtension('Atom')->getAuthors(); - - $this->data['authors'] = $authors; - - return $this->data['authors']; - } - - /** - * Get the copyright entry - * - * @return string|null - */ - public function getCopyright() - { - if (array_key_exists('copyright', $this->data)) { - return $this->data['copyright']; - } - - $copyright = $this->getExtension('Atom')->getCopyright(); - - if (!$copyright) { - $copyright = null; - } - - $this->data['copyright'] = $copyright; - - return $this->data['copyright']; - } - - /** - * Get the feed creation date - * - * @return string|null - */ - public function getDateCreated() - { - if (array_key_exists('datecreated', $this->data)) { - return $this->data['datecreated']; - } - - $dateCreated = $this->getExtension('Atom')->getDateCreated(); - - if (!$dateCreated) { - $dateCreated = null; - } - - $this->data['datecreated'] = $dateCreated; - - return $this->data['datecreated']; - } - - /** - * Get the feed modification date - * - * @return string|null - */ - public function getDateModified() - { - if (array_key_exists('datemodified', $this->data)) { - return $this->data['datemodified']; - } - - $dateModified = $this->getExtension('Atom')->getDateModified(); - - if (!$dateModified) { - $dateModified = null; - } - - $this->data['datemodified'] = $dateModified; - - return $this->data['datemodified']; - } - - /** - * Get the feed lastBuild date. This is not implemented in Atom. - * - * @return string|null - */ - public function getLastBuildDate() - { - return null; - } - - /** - * Get the feed description - * - * @return string|null - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = $this->getExtension('Atom')->getDescription(); - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the feed generator entry - * - * @return string|null - */ - public function getGenerator() - { - if (array_key_exists('generator', $this->data)) { - return $this->data['generator']; - } - - $generator = $this->getExtension('Atom')->getGenerator(); - - $this->data['generator'] = $generator; - - return $this->data['generator']; - } - - /** - * Get the feed ID - * - * @return string|null - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = $this->getExtension('Atom')->getId(); - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get the feed language - * - * @return string|null - */ - public function getLanguage() - { - if (array_key_exists('language', $this->data)) { - return $this->data['language']; - } - - $language = $this->getExtension('Atom')->getLanguage(); - - if (!$language) { - $language = $this->xpath->evaluate('string(//@xml:lang[1])'); - } - - if (!$language) { - $language = null; - } - - $this->data['language'] = $language; - - return $this->data['language']; - } - - /** - * Get a link to the source website - * - * @return string|null - */ - public function getBaseUrl() - { - if (array_key_exists('baseUrl', $this->data)) { - return $this->data['baseUrl']; - } - - $baseUrl = $this->getExtension('Atom')->getBaseUrl(); - - $this->data['baseUrl'] = $baseUrl; - - return $this->data['baseUrl']; - } - - /** - * Get a link to the source website - * - * @return string|null - */ - public function getLink() - { - if (array_key_exists('link', $this->data)) { - return $this->data['link']; - } - - $link = $this->getExtension('Atom')->getLink(); - - $this->data['link'] = $link; - - return $this->data['link']; - } - - /** - * Get feed image data - * - * @return array|null - */ - public function getImage() - { - if (array_key_exists('image', $this->data)) { - return $this->data['image']; - } - - $link = $this->getExtension('Atom')->getImage(); - - $this->data['image'] = $link; - - return $this->data['image']; - } - - /** - * Get a link to the feed's XML Url - * - * @return string|null - */ - public function getFeedLink() - { - if (array_key_exists('feedlink', $this->data)) { - return $this->data['feedlink']; - } - - $link = $this->getExtension('Atom')->getFeedLink(); - - if ($link === null || empty($link)) { - $link = $this->getOriginalSourceUri(); - } - - $this->data['feedlink'] = $link; - - return $this->data['feedlink']; - } - - /** - * Get the feed title - * - * @return string|null - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = $this->getExtension('Atom')->getTitle(); - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * Get an array of any supported Pusubhubbub endpoints - * - * @return array|null - */ - public function getHubs() - { - if (array_key_exists('hubs', $this->data)) { - return $this->data['hubs']; - } - - $hubs = $this->getExtension('Atom')->getHubs(); - - $this->data['hubs'] = $hubs; - - return $this->data['hubs']; - } - - /** - * Get all categories - * - * @return Reader\Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - $categoryCollection = $this->getExtension('Atom')->getCategories(); - - if (count($categoryCollection) == 0) { - $categoryCollection = $this->getExtension('DublinCore')->getCategories(); - } - - $this->data['categories'] = $categoryCollection; - - return $this->data['categories']; - } - - /** - * Read all entries to the internal entries array - * - * @return void - */ - protected function indexEntries() - { - if ($this->getType() == Reader\Reader::TYPE_ATOM_10 || - $this->getType() == Reader\Reader::TYPE_ATOM_03) { - $entries = $this->xpath->evaluate('//atom:entry'); - - foreach ($entries as $index => $entry) { - $this->entries[$index] = $entry; - } - } - } - - /** - * Register the default namespaces for the current feed format - * - */ - protected function registerNamespaces() - { - switch ($this->data['type']) { - case Reader\Reader::TYPE_ATOM_03: - $this->xpath->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_03); - break; - case Reader\Reader::TYPE_ATOM_10: - default: - $this->xpath->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_10); - } - } -} diff --git a/library/Zend/Feed/Reader/Feed/Atom/Source.php b/library/Zend/Feed/Reader/Feed/Atom/Source.php deleted file mode 100755 index 5eabd974b..000000000 --- a/library/Zend/Feed/Reader/Feed/Atom/Source.php +++ /dev/null @@ -1,107 +0,0 @@ -domDocument = $source->ownerDocument; - $this->xpath = new DOMXPath($this->domDocument); - $this->data['type'] = $type; - $this->registerNamespaces(); - $this->loadExtensions(); - - $manager = Reader\Reader::getExtensionManager(); - $extensions = array('Atom\Feed', 'DublinCore\Feed'); - - foreach ($extensions as $name) { - $extension = $manager->get($name); - $extension->setDomDocument($this->domDocument); - $extension->setType($this->data['type']); - $extension->setXpath($this->xpath); - $this->extensions[$name] = $extension; - } - - foreach ($this->extensions as $extension) { - $extension->setXpathPrefix(rtrim($xpathPrefix, '/') . '/atom:source'); - } - } - - /** - * Since this is not an Entry carrier but a vehicle for Feed metadata, any - * applicable Entry methods are stubbed out and do nothing. - */ - - /** - * @return void - */ - public function count() - { - } - - /** - * @return void - */ - public function current() - { - } - - /** - * @return void - */ - public function key() - { - } - - /** - * @return void - */ - public function next() - { - } - - /** - * @return void - */ - public function rewind() - { - } - - /** - * @return void - */ - public function valid() - { - } - - /** - * @return void - */ - protected function indexEntries() - { - } -} diff --git a/library/Zend/Feed/Reader/Feed/FeedInterface.php b/library/Zend/Feed/Reader/Feed/FeedInterface.php deleted file mode 100755 index c98a1b333..000000000 --- a/library/Zend/Feed/Reader/Feed/FeedInterface.php +++ /dev/null @@ -1,110 +0,0 @@ -get('DublinCore\Feed'); - $feed->setDomDocument($dom); - $feed->setType($this->data['type']); - $feed->setXpath($this->xpath); - $this->extensions['DublinCore\Feed'] = $feed; - - $feed = $manager->get('Atom\Feed'); - $feed->setDomDocument($dom); - $feed->setType($this->data['type']); - $feed->setXpath($this->xpath); - $this->extensions['Atom\Feed'] = $feed; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090 - ) { - $xpathPrefix = '/rss/channel'; - } else { - $xpathPrefix = '/rdf:RDF/rss:channel'; - } - foreach ($this->extensions as $extension) { - $extension->setXpathPrefix($xpathPrefix); - } - } - - /** - * Get a single author - * - * @param int $index - * @return string|null - */ - public function getAuthor($index = 0) - { - $authors = $this->getAuthors(); - - if (isset($authors[$index])) { - return $authors[$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (array_key_exists('authors', $this->data)) { - return $this->data['authors']; - } - - $authors = array(); - $authorsDc = $this->getExtension('DublinCore')->getAuthors(); - if (!empty($authorsDc)) { - foreach ($authorsDc as $author) { - $authors[] = array( - 'name' => $author['name'] - ); - } - } - - /** - * Technically RSS doesn't specific author element use at the feed level - * but it's supported on a "just in case" basis. - */ - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 - && $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $list = $this->xpath->query('//author'); - } else { - $list = $this->xpath->query('//rss:author'); - } - if ($list->length) { - foreach ($list as $author) { - $string = trim($author->nodeValue); - $email = null; - $name = null; - $data = array(); - // Pretty rough parsing - but it's a catchall - if (preg_match("/^.*@[^ ]*/", $string, $matches)) { - $data['email'] = trim($matches[0]); - if (preg_match("/\((.*)\)$/", $string, $matches)) { - $data['name'] = $matches[1]; - } - $authors[] = $data; - } - } - } - - if (count($authors) == 0) { - $authors = $this->getExtension('Atom')->getAuthors(); - } else { - $authors = new Reader\Collection\Author( - Reader\Reader::arrayUnique($authors) - ); - } - - if (count($authors) == 0) { - $authors = null; - } - - $this->data['authors'] = $authors; - - return $this->data['authors']; - } - - /** - * Get the copyright entry - * - * @return string|null - */ - public function getCopyright() - { - if (array_key_exists('copyright', $this->data)) { - return $this->data['copyright']; - } - - $copyright = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $copyright = $this->xpath->evaluate('string(/rss/channel/copyright)'); - } - - if (!$copyright && $this->getExtension('DublinCore') !== null) { - $copyright = $this->getExtension('DublinCore')->getCopyright(); - } - - if (empty($copyright)) { - $copyright = $this->getExtension('Atom')->getCopyright(); - } - - if (!$copyright) { - $copyright = null; - } - - $this->data['copyright'] = $copyright; - - return $this->data['copyright']; - } - - /** - * Get the feed creation date - * - * @return string|null - */ - public function getDateCreated() - { - return $this->getDateModified(); - } - - /** - * Get the feed modification date - * - * @return DateTime - * @throws Exception\RuntimeException - */ - public function getDateModified() - { - if (array_key_exists('datemodified', $this->data)) { - return $this->data['datemodified']; - } - - $dateModified = null; - $date = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $dateModified = $this->xpath->evaluate('string(/rss/channel/pubDate)'); - if (!$dateModified) { - $dateModified = $this->xpath->evaluate('string(/rss/channel/lastBuildDate)'); - } - if ($dateModified) { - $dateModifiedParsed = strtotime($dateModified); - if ($dateModifiedParsed) { - $date = new DateTime('@' . $dateModifiedParsed); - } else { - $dateStandards = array(DateTime::RSS, DateTime::RFC822, - DateTime::RFC2822, null); - foreach ($dateStandards as $standard) { - try { - $date = DateTime::createFromFormat($standard, $dateModified); - break; - } catch (\Exception $e) { - if ($standard == null) { - throw new Exception\RuntimeException( - 'Could not load date due to unrecognised' - .' format (should follow RFC 822 or 2822):' - . $e->getMessage(), - 0, $e - ); - } - } - } - } - } - } - - if (!$date) { - $date = $this->getExtension('DublinCore')->getDate(); - } - - if (!$date) { - $date = $this->getExtension('Atom')->getDateModified(); - } - - if (!$date) { - $date = null; - } - - $this->data['datemodified'] = $date; - - return $this->data['datemodified']; - } - - /** - * Get the feed lastBuild date - * - * @throws Exception\RuntimeException - * @return DateTime - */ - public function getLastBuildDate() - { - if (array_key_exists('lastBuildDate', $this->data)) { - return $this->data['lastBuildDate']; - } - - $lastBuildDate = null; - $date = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $lastBuildDate = $this->xpath->evaluate('string(/rss/channel/lastBuildDate)'); - if ($lastBuildDate) { - $lastBuildDateParsed = strtotime($lastBuildDate); - if ($lastBuildDateParsed) { - $date = new DateTime('@' . $lastBuildDateParsed); - } else { - $dateStandards = array(DateTime::RSS, DateTime::RFC822, - DateTime::RFC2822, null); - foreach ($dateStandards as $standard) { - try { - $date = DateTime::createFromFormat($standard, $lastBuildDateParsed); - break; - } catch (\Exception $e) { - if ($standard == null) { - throw new Exception\RuntimeException( - 'Could not load date due to unrecognised' - .' format (should follow RFC 822 or 2822):' - . $e->getMessage(), - 0, $e - ); - } - } - } - } - } - } - - if (!$date) { - $date = null; - } - - $this->data['lastBuildDate'] = $date; - - return $this->data['lastBuildDate']; - } - - /** - * Get the feed description - * - * @return string|null - */ - public function getDescription() - { - if (array_key_exists('description', $this->data)) { - return $this->data['description']; - } - - $description = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $description = $this->xpath->evaluate('string(/rss/channel/description)'); - } else { - $description = $this->xpath->evaluate('string(/rdf:RDF/rss:channel/rss:description)'); - } - - if (!$description && $this->getExtension('DublinCore') !== null) { - $description = $this->getExtension('DublinCore')->getDescription(); - } - - if (empty($description)) { - $description = $this->getExtension('Atom')->getDescription(); - } - - if (!$description) { - $description = null; - } - - $this->data['description'] = $description; - - return $this->data['description']; - } - - /** - * Get the feed ID - * - * @return string|null - */ - public function getId() - { - if (array_key_exists('id', $this->data)) { - return $this->data['id']; - } - - $id = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $id = $this->xpath->evaluate('string(/rss/channel/guid)'); - } - - if (!$id && $this->getExtension('DublinCore') !== null) { - $id = $this->getExtension('DublinCore')->getId(); - } - - if (empty($id)) { - $id = $this->getExtension('Atom')->getId(); - } - - if (!$id) { - if ($this->getLink()) { - $id = $this->getLink(); - } elseif ($this->getTitle()) { - $id = $this->getTitle(); - } else { - $id = null; - } - } - - $this->data['id'] = $id; - - return $this->data['id']; - } - - /** - * Get the feed image data - * - * @return array|null - */ - public function getImage() - { - if (array_key_exists('image', $this->data)) { - return $this->data['image']; - } - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $list = $this->xpath->query('/rss/channel/image'); - $prefix = '/rss/channel/image[1]'; - } else { - $list = $this->xpath->query('/rdf:RDF/rss:channel/rss:image'); - $prefix = '/rdf:RDF/rss:channel/rss:image[1]'; - } - if ($list->length > 0) { - $image = array(); - $value = $this->xpath->evaluate('string(' . $prefix . '/url)'); - if ($value) { - $image['uri'] = $value; - } - $value = $this->xpath->evaluate('string(' . $prefix . '/link)'); - if ($value) { - $image['link'] = $value; - } - $value = $this->xpath->evaluate('string(' . $prefix . '/title)'); - if ($value) { - $image['title'] = $value; - } - $value = $this->xpath->evaluate('string(' . $prefix . '/height)'); - if ($value) { - $image['height'] = $value; - } - $value = $this->xpath->evaluate('string(' . $prefix . '/width)'); - if ($value) { - $image['width'] = $value; - } - $value = $this->xpath->evaluate('string(' . $prefix . '/description)'); - if ($value) { - $image['description'] = $value; - } - } else { - $image = null; - } - - $this->data['image'] = $image; - - return $this->data['image']; - } - - /** - * Get the feed language - * - * @return string|null - */ - public function getLanguage() - { - if (array_key_exists('language', $this->data)) { - return $this->data['language']; - } - - $language = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $language = $this->xpath->evaluate('string(/rss/channel/language)'); - } - - if (!$language && $this->getExtension('DublinCore') !== null) { - $language = $this->getExtension('DublinCore')->getLanguage(); - } - - if (empty($language)) { - $language = $this->getExtension('Atom')->getLanguage(); - } - - if (!$language) { - $language = $this->xpath->evaluate('string(//@xml:lang[1])'); - } - - if (!$language) { - $language = null; - } - - $this->data['language'] = $language; - - return $this->data['language']; - } - - /** - * Get a link to the feed - * - * @return string|null - */ - public function getLink() - { - if (array_key_exists('link', $this->data)) { - return $this->data['link']; - } - - $link = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $link = $this->xpath->evaluate('string(/rss/channel/link)'); - } else { - $link = $this->xpath->evaluate('string(/rdf:RDF/rss:channel/rss:link)'); - } - - if (empty($link)) { - $link = $this->getExtension('Atom')->getLink(); - } - - if (!$link) { - $link = null; - } - - $this->data['link'] = $link; - - return $this->data['link']; - } - - /** - * Get a link to the feed XML - * - * @return string|null - */ - public function getFeedLink() - { - if (array_key_exists('feedlink', $this->data)) { - return $this->data['feedlink']; - } - - $link = null; - - $link = $this->getExtension('Atom')->getFeedLink(); - - if ($link === null || empty($link)) { - $link = $this->getOriginalSourceUri(); - } - - $this->data['feedlink'] = $link; - - return $this->data['feedlink']; - } - - /** - * Get the feed generator entry - * - * @return string|null - */ - public function getGenerator() - { - if (array_key_exists('generator', $this->data)) { - return $this->data['generator']; - } - - $generator = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $generator = $this->xpath->evaluate('string(/rss/channel/generator)'); - } - - if (!$generator) { - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $generator = $this->xpath->evaluate('string(/rss/channel/atom:generator)'); - } else { - $generator = $this->xpath->evaluate('string(/rdf:RDF/rss:channel/atom:generator)'); - } - } - - if (empty($generator)) { - $generator = $this->getExtension('Atom')->getGenerator(); - } - - if (!$generator) { - $generator = null; - } - - $this->data['generator'] = $generator; - - return $this->data['generator']; - } - - /** - * Get the feed title - * - * @return string|null - */ - public function getTitle() - { - if (array_key_exists('title', $this->data)) { - return $this->data['title']; - } - - $title = null; - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $title = $this->xpath->evaluate('string(/rss/channel/title)'); - } else { - $title = $this->xpath->evaluate('string(/rdf:RDF/rss:channel/rss:title)'); - } - - if (!$title && $this->getExtension('DublinCore') !== null) { - $title = $this->getExtension('DublinCore')->getTitle(); - } - - if (!$title) { - $title = $this->getExtension('Atom')->getTitle(); - } - - if (!$title) { - $title = null; - } - - $this->data['title'] = $title; - - return $this->data['title']; - } - - /** - * Get an array of any supported Pusubhubbub endpoints - * - * @return array|null - */ - public function getHubs() - { - if (array_key_exists('hubs', $this->data)) { - return $this->data['hubs']; - } - - $hubs = $this->getExtension('Atom')->getHubs(); - - if (empty($hubs)) { - $hubs = null; - } else { - $hubs = array_unique($hubs); - } - - $this->data['hubs'] = $hubs; - - return $this->data['hubs']; - } - - /** - * Get all categories - * - * @return Reader\Collection\Category - */ - public function getCategories() - { - if (array_key_exists('categories', $this->data)) { - return $this->data['categories']; - } - - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && - $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $list = $this->xpath->query('/rss/channel//category'); - } else { - $list = $this->xpath->query('/rdf:RDF/rss:channel//rss:category'); - } - - if ($list->length) { - $categoryCollection = new Collection\Category; - foreach ($list as $category) { - $categoryCollection[] = array( - 'term' => $category->nodeValue, - 'scheme' => $category->getAttribute('domain'), - 'label' => $category->nodeValue, - ); - } - } else { - $categoryCollection = $this->getExtension('DublinCore')->getCategories(); - } - - if (count($categoryCollection) == 0) { - $categoryCollection = $this->getExtension('Atom')->getCategories(); - } - - $this->data['categories'] = $categoryCollection; - - return $this->data['categories']; - } - - /** - * Read all entries to the internal entries array - * - */ - protected function indexEntries() - { - if ($this->getType() !== Reader\Reader::TYPE_RSS_10 && $this->getType() !== Reader\Reader::TYPE_RSS_090) { - $entries = $this->xpath->evaluate('//item'); - } else { - $entries = $this->xpath->evaluate('//rss:item'); - } - - foreach ($entries as $index => $entry) { - $this->entries[$index] = $entry; - } - } - - /** - * Register the default namespaces for the current feed format - * - */ - protected function registerNamespaces() - { - switch ($this->data['type']) { - case Reader\Reader::TYPE_RSS_10: - $this->xpath->registerNamespace('rdf', Reader\Reader::NAMESPACE_RDF); - $this->xpath->registerNamespace('rss', Reader\Reader::NAMESPACE_RSS_10); - break; - - case Reader\Reader::TYPE_RSS_090: - $this->xpath->registerNamespace('rdf', Reader\Reader::NAMESPACE_RDF); - $this->xpath->registerNamespace('rss', Reader\Reader::NAMESPACE_RSS_090); - break; - } - } -} diff --git a/library/Zend/Feed/Reader/FeedSet.php b/library/Zend/Feed/Reader/FeedSet.php deleted file mode 100755 index e487bc8f4..000000000 --- a/library/Zend/Feed/Reader/FeedSet.php +++ /dev/null @@ -1,126 +0,0 @@ -getAttribute('rel')) !== 'alternate' - || !$link->getAttribute('type') || !$link->getAttribute('href')) { - continue; - } - if (!isset($this->rss) && $link->getAttribute('type') == 'application/rss+xml') { - $this->rss = $this->absolutiseUri(trim($link->getAttribute('href')), $uri); - } elseif (!isset($this->atom) && $link->getAttribute('type') == 'application/atom+xml') { - $this->atom = $this->absolutiseUri(trim($link->getAttribute('href')), $uri); - } elseif (!isset($this->rdf) && $link->getAttribute('type') == 'application/rdf+xml') { - $this->rdf = $this->absolutiseUri(trim($link->getAttribute('href')), $uri); - } - $this[] = new static(array( - 'rel' => 'alternate', - 'type' => $link->getAttribute('type'), - 'href' => $this->absolutiseUri(trim($link->getAttribute('href')), $uri), - )); - } - } - - /** - * Attempt to turn a relative URI into an absolute URI - */ - protected function absolutiseUri($link, $uri = null) - { - $linkUri = Uri::factory($link); - if (!$linkUri->isAbsolute() or !$linkUri->isValid()) { - if ($uri !== null) { - $uri = Uri::factory($uri); - - if ($link[0] !== '/') { - $link = $uri->getPath() . '/' . $link; - } - - $link = $uri->getScheme() . '://' . $uri->getHost() . '/' . $this->canonicalizePath($link); - if (!Uri::factory($link)->isValid()) { - $link = null; - } - } - } - return $link; - } - - /** - * Canonicalize relative path - */ - protected function canonicalizePath($path) - { - $parts = array_filter(explode('/', $path)); - $absolutes = array(); - foreach ($parts as $part) { - if ('.' == $part) { - continue; - } - if ('..' == $part) { - array_pop($absolutes); - } else { - $absolutes[] = $part; - } - } - return implode('/', $absolutes); - } - - /** - * Supports lazy loading of feeds using Reader::import() but - * delegates any other operations to the parent class. - * - * @param string $offset - * @return mixed - */ - public function offsetGet($offset) - { - if ($offset == 'feed' && !$this->offsetExists('feed')) { - if (!$this->offsetExists('href')) { - return null; - } - $feed = Reader::import($this->offsetGet('href')); - $this->offsetSet('feed', $feed); - return $feed; - } - return parent::offsetGet($offset); - } -} diff --git a/library/Zend/Feed/Reader/Http/ClientInterface.php b/library/Zend/Feed/Reader/Http/ClientInterface.php deleted file mode 100755 index 43932f761..000000000 --- a/library/Zend/Feed/Reader/Http/ClientInterface.php +++ /dev/null @@ -1,21 +0,0 @@ - array( - 'DublinCore\Feed', - 'Atom\Feed' - ), - 'entry' => array( - 'Content\Entry', - 'DublinCore\Entry', - 'Atom\Entry' - ), - 'core' => array( - 'DublinCore\Feed', - 'Atom\Feed', - 'Content\Entry', - 'DublinCore\Entry', - 'Atom\Entry' - ) - ); - - /** - * Get the Feed cache - * - * @return CacheStorage - */ - public static function getCache() - { - return static::$cache; - } - - /** - * Set the feed cache - * - * @param CacheStorage $cache - * @return void - */ - public static function setCache(CacheStorage $cache) - { - static::$cache = $cache; - } - - /** - * Set the HTTP client instance - * - * Sets the HTTP client object to use for retrieving the feeds. - * - * @param ZendHttp\Client $httpClient - * @return void - */ - public static function setHttpClient(ZendHttp\Client $httpClient) - { - static::$httpClient = $httpClient; - } - - - /** - * Gets the HTTP client object. If none is set, a new ZendHttp\Client will be used. - * - * @return ZendHttp\Client - */ - public static function getHttpClient() - { - if (!static::$httpClient instanceof ZendHttp\Client) { - static::$httpClient = new ZendHttp\Client(); - } - - return static::$httpClient; - } - - /** - * Toggle using POST instead of PUT and DELETE HTTP methods - * - * Some feed implementations do not accept PUT and DELETE HTTP - * methods, or they can't be used because of proxies or other - * measures. This allows turning on using POST where PUT and - * DELETE would normally be used; in addition, an - * X-Method-Override header will be sent with a value of PUT or - * DELETE as appropriate. - * - * @param bool $override Whether to override PUT and DELETE. - * @return void - */ - public static function setHttpMethodOverride($override = true) - { - static::$httpMethodOverride = $override; - } - - /** - * Get the HTTP override state - * - * @return bool - */ - public static function getHttpMethodOverride() - { - return static::$httpMethodOverride; - } - - /** - * Set the flag indicating whether or not to use HTTP conditional GET - * - * @param bool $bool - * @return void - */ - public static function useHttpConditionalGet($bool = true) - { - static::$httpConditionalGet = $bool; - } - - /** - * Import a feed by providing a URI - * - * @param string $uri The URI to the feed - * @param string $etag OPTIONAL Last received ETag for this resource - * @param string $lastModified OPTIONAL Last-Modified value for this resource - * @return Feed\FeedInterface - * @throws Exception\RuntimeException - */ - public static function import($uri, $etag = null, $lastModified = null) - { - $cache = self::getCache(); - $feed = null; - $client = self::getHttpClient(); - $client->resetParameters(); - $headers = new ZendHttp\Headers(); - $client->setHeaders($headers); - $client->setUri($uri); - $cacheId = 'Zend_Feed_Reader_' . md5($uri); - - if (static::$httpConditionalGet && $cache) { - $data = $cache->getItem($cacheId); - if ($data) { - if ($etag === null) { - $etag = $cache->getItem($cacheId . '_etag'); - } - if ($lastModified === null) { - $lastModified = $cache->getItem($cacheId . '_lastmodified'); - } - if ($etag) { - $headers->addHeaderLine('If-None-Match', $etag); - } - if ($lastModified) { - $headers->addHeaderLine('If-Modified-Since', $lastModified); - } - } - $response = $client->send(); - if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 304) { - throw new Exception\RuntimeException('Feed failed to load, got response code ' . $response->getStatusCode()); - } - if ($response->getStatusCode() == 304) { - $responseXml = $data; - } else { - $responseXml = $response->getBody(); - $cache->setItem($cacheId, $responseXml); - if ($response->getHeaders()->get('ETag')) { - $cache->setItem($cacheId . '_etag', $response->getHeaders()->get('ETag')->getFieldValue()); - } - if ($response->getHeaders()->get('Last-Modified')) { - $cache->setItem($cacheId . '_lastmodified', $response->getHeaders()->get('Last-Modified')->getFieldValue()); - } - } - return static::importString($responseXml); - } elseif ($cache) { - $data = $cache->getItem($cacheId); - if ($data) { - return static::importString($data); - } - $response = $client->send(); - if ((int) $response->getStatusCode() !== 200) { - throw new Exception\RuntimeException('Feed failed to load, got response code ' . $response->getStatusCode()); - } - $responseXml = $response->getBody(); - $cache->setItem($cacheId, $responseXml); - return static::importString($responseXml); - } else { - $response = $client->send(); - if ((int) $response->getStatusCode() !== 200) { - throw new Exception\RuntimeException('Feed failed to load, got response code ' . $response->getStatusCode()); - } - $reader = static::importString($response->getBody()); - $reader->setOriginalSourceUri($uri); - return $reader; - } - } - - /** - * Import a feed from a remote URI - * - * Performs similarly to import(), except it uses the HTTP client passed to - * the method, and does not take into account cached data. - * - * Primary purpose is to make it possible to use the Reader with alternate - * HTTP client implementations. - * - * @param string $uri - * @param Http\ClientInterface $client - * @return self - * @throws Exception\RuntimeException if response is not an Http\ResponseInterface - */ - public static function importRemoteFeed($uri, Http\ClientInterface $client) - { - $response = $client->get($uri); - if (!$response instanceof Http\ResponseInterface) { - throw new Exception\RuntimeException(sprintf( - 'Did not receive a %s\Http\ResponseInterface from the provided HTTP client; received "%s"', - __NAMESPACE__, - (is_object($response) ? get_class($response) : gettype($response)) - )); - } - - if ((int) $response->getStatusCode() !== 200) { - throw new Exception\RuntimeException('Feed failed to load, got response code ' . $response->getStatusCode()); - } - $reader = static::importString($response->getBody()); - $reader->setOriginalSourceUri($uri); - return $reader; - } - - /** - * Import a feed from a string - * - * @param string $string - * @return Feed\FeedInterface - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public static function importString($string) - { - $trimmed = trim($string); - if (!is_string($string) || empty($trimmed)) { - throw new Exception\InvalidArgumentException('Only non empty strings are allowed as input'); - } - - $libxmlErrflag = libxml_use_internal_errors(true); - $oldValue = libxml_disable_entity_loader(true); - $dom = new DOMDocument; - $status = $dom->loadXML(trim($string)); - foreach ($dom->childNodes as $child) { - if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { - throw new Exception\InvalidArgumentException( - 'Invalid XML: Detected use of illegal DOCTYPE' - ); - } - } - libxml_disable_entity_loader($oldValue); - libxml_use_internal_errors($libxmlErrflag); - - if (!$status) { - // Build error message - $error = libxml_get_last_error(); - if ($error && $error->message) { - $error->message = trim($error->message); - $errormsg = "DOMDocument cannot parse XML: {$error->message}"; - } else { - $errormsg = "DOMDocument cannot parse XML: Please check the XML document's validity"; - } - throw new Exception\RuntimeException($errormsg); - } - - $type = static::detectType($dom); - - static::registerCoreExtensions(); - - if (substr($type, 0, 3) == 'rss') { - $reader = new Feed\Rss($dom, $type); - } elseif (substr($type, 8, 5) == 'entry') { - $reader = new Entry\Atom($dom->documentElement, 0, self::TYPE_ATOM_10); - } elseif (substr($type, 0, 4) == 'atom') { - $reader = new Feed\Atom($dom, $type); - } else { - throw new Exception\RuntimeException('The URI used does not point to a ' - . 'valid Atom, RSS or RDF feed that Zend\Feed\Reader can parse.'); - } - return $reader; - } - - /** - * Imports a feed from a file located at $filename. - * - * @param string $filename - * @throws Exception\RuntimeException - * @return Feed\FeedInterface - */ - public static function importFile($filename) - { - ErrorHandler::start(); - $feed = file_get_contents($filename); - $err = ErrorHandler::stop(); - if ($feed === false) { - throw new Exception\RuntimeException("File '{$filename}' could not be loaded", 0, $err); - } - return static::importString($feed); - } - - /** - * Find feed links - * - * @param $uri - * @return FeedSet - * @throws Exception\RuntimeException - */ - public static function findFeedLinks($uri) - { - $client = static::getHttpClient(); - $client->setUri($uri); - $response = $client->send(); - if ($response->getStatusCode() !== 200) { - throw new Exception\RuntimeException("Failed to access $uri, got response code " . $response->getStatusCode()); - } - $responseHtml = $response->getBody(); - $libxmlErrflag = libxml_use_internal_errors(true); - $oldValue = libxml_disable_entity_loader(true); - $dom = new DOMDocument; - $status = $dom->loadHTML(trim($responseHtml)); - libxml_disable_entity_loader($oldValue); - libxml_use_internal_errors($libxmlErrflag); - if (!$status) { - // Build error message - $error = libxml_get_last_error(); - if ($error && $error->message) { - $error->message = trim($error->message); - $errormsg = "DOMDocument cannot parse HTML: {$error->message}"; - } else { - $errormsg = "DOMDocument cannot parse HTML: Please check the XML document's validity"; - } - throw new Exception\RuntimeException($errormsg); - } - $feedSet = new FeedSet; - $links = $dom->getElementsByTagName('link'); - $feedSet->addLinks($links, $uri); - return $feedSet; - } - - /** - * Detect the feed type of the provided feed - * - * @param Feed\AbstractFeed|DOMDocument|string $feed - * @param bool $specOnly - * @return string - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public static function detectType($feed, $specOnly = false) - { - if ($feed instanceof Feed\AbstractFeed) { - $dom = $feed->getDomDocument(); - } elseif ($feed instanceof DOMDocument) { - $dom = $feed; - } elseif (is_string($feed) && !empty($feed)) { - ErrorHandler::start(E_NOTICE|E_WARNING); - ini_set('track_errors', 1); - $oldValue = libxml_disable_entity_loader(true); - $dom = new DOMDocument; - $status = $dom->loadXML($feed); - foreach ($dom->childNodes as $child) { - if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { - throw new Exception\InvalidArgumentException( - 'Invalid XML: Detected use of illegal DOCTYPE' - ); - } - } - libxml_disable_entity_loader($oldValue); - ini_restore('track_errors'); - ErrorHandler::stop(); - if (!$status) { - if (!isset($phpErrormsg)) { - if (function_exists('xdebug_is_enabled')) { - $phpErrormsg = '(error message not available, when XDebug is running)'; - } else { - $phpErrormsg = '(error message not available)'; - } - } - throw new Exception\RuntimeException("DOMDocument cannot parse XML: $phpErrormsg"); - } - } else { - throw new Exception\InvalidArgumentException('Invalid object/scalar provided: must' - . ' be of type Zend\Feed\Reader\Feed, DomDocument or string'); - } - $xpath = new DOMXPath($dom); - - if ($xpath->query('/rss')->length) { - $type = self::TYPE_RSS_ANY; - $version = $xpath->evaluate('string(/rss/@version)'); - - if (strlen($version) > 0) { - switch ($version) { - case '2.0': - $type = self::TYPE_RSS_20; - break; - - case '0.94': - $type = self::TYPE_RSS_094; - break; - - case '0.93': - $type = self::TYPE_RSS_093; - break; - - case '0.92': - $type = self::TYPE_RSS_092; - break; - - case '0.91': - $type = self::TYPE_RSS_091; - break; - } - } - - return $type; - } - - $xpath->registerNamespace('rdf', self::NAMESPACE_RDF); - - if ($xpath->query('/rdf:RDF')->length) { - $xpath->registerNamespace('rss', self::NAMESPACE_RSS_10); - - if ($xpath->query('/rdf:RDF/rss:channel')->length - || $xpath->query('/rdf:RDF/rss:image')->length - || $xpath->query('/rdf:RDF/rss:item')->length - || $xpath->query('/rdf:RDF/rss:textinput')->length - ) { - return self::TYPE_RSS_10; - } - - $xpath->registerNamespace('rss', self::NAMESPACE_RSS_090); - - if ($xpath->query('/rdf:RDF/rss:channel')->length - || $xpath->query('/rdf:RDF/rss:image')->length - || $xpath->query('/rdf:RDF/rss:item')->length - || $xpath->query('/rdf:RDF/rss:textinput')->length - ) { - return self::TYPE_RSS_090; - } - } - - $xpath->registerNamespace('atom', self::NAMESPACE_ATOM_10); - - if ($xpath->query('//atom:feed')->length) { - return self::TYPE_ATOM_10; - } - - if ($xpath->query('//atom:entry')->length) { - if ($specOnly == true) { - return self::TYPE_ATOM_10; - } else { - return self::TYPE_ATOM_10_ENTRY; - } - } - - $xpath->registerNamespace('atom', self::NAMESPACE_ATOM_03); - - if ($xpath->query('//atom:feed')->length) { - return self::TYPE_ATOM_03; - } - - return self::TYPE_ANY; - } - - /** - * Set plugin manager for use with Extensions - * - * @param ExtensionManagerInterface $extensionManager - */ - public static function setExtensionManager(ExtensionManagerInterface $extensionManager) - { - static::$extensionManager = $extensionManager; - } - - /** - * Get plugin manager for use with Extensions - * - * @return ExtensionManagerInterface - */ - public static function getExtensionManager() - { - if (!isset(static::$extensionManager)) { - static::setExtensionManager(new ExtensionManager()); - } - return static::$extensionManager; - } - - /** - * Register an Extension by name - * - * @param string $name - * @return void - * @throws Exception\RuntimeException if unable to resolve Extension class - */ - public static function registerExtension($name) - { - $feedName = $name . '\Feed'; - $entryName = $name . '\Entry'; - $manager = static::getExtensionManager(); - if (static::isRegistered($name)) { - if ($manager->has($feedName) || $manager->has($entryName)) { - return; - } - } - - if (!$manager->has($feedName) && !$manager->has($entryName)) { - throw new Exception\RuntimeException('Could not load extension: ' . $name - . ' using Plugin Loader. Check prefix paths are configured and extension exists.'); - } - if ($manager->has($feedName)) { - static::$extensions['feed'][] = $feedName; - } - if ($manager->has($entryName)) { - static::$extensions['entry'][] = $entryName; - } - } - - /** - * Is a given named Extension registered? - * - * @param string $extensionName - * @return bool - */ - public static function isRegistered($extensionName) - { - $feedName = $extensionName . '\Feed'; - $entryName = $extensionName . '\Entry'; - if (in_array($feedName, static::$extensions['feed']) - || in_array($entryName, static::$extensions['entry']) - ) { - return true; - } - return false; - } - - /** - * Get a list of extensions - * - * @return array - */ - public static function getExtensions() - { - return static::$extensions; - } - - /** - * Reset class state to defaults - * - * @return void - */ - public static function reset() - { - static::$cache = null; - static::$httpClient = null; - static::$httpMethodOverride = false; - static::$httpConditionalGet = false; - static::$extensionManager = null; - static::$extensions = array( - 'feed' => array( - 'DublinCore\Feed', - 'Atom\Feed' - ), - 'entry' => array( - 'Content\Entry', - 'DublinCore\Entry', - 'Atom\Entry' - ), - 'core' => array( - 'DublinCore\Feed', - 'Atom\Feed', - 'Content\Entry', - 'DublinCore\Entry', - 'Atom\Entry' - ) - ); - } - - /** - * Register core (default) extensions - * - * @return void - */ - protected static function registerCoreExtensions() - { - static::registerExtension('DublinCore'); - static::registerExtension('Content'); - static::registerExtension('Atom'); - static::registerExtension('Slash'); - static::registerExtension('WellFormedWeb'); - static::registerExtension('Thread'); - static::registerExtension('Podcast'); - } - - /** - * Utility method to apply array_unique operation to a multidimensional - * array. - * - * @param array - * @return array - */ - public static function arrayUnique(array $array) - { - foreach ($array as &$value) { - $value = serialize($value); - } - $array = array_unique($array); - foreach ($array as &$value) { - $value = unserialize($value); - } - return $array; - } -} diff --git a/library/Zend/Feed/Uri.php b/library/Zend/Feed/Uri.php deleted file mode 100755 index 940bce11a..000000000 --- a/library/Zend/Feed/Uri.php +++ /dev/null @@ -1,184 +0,0 @@ -valid = false; - return; - } - - $this->scheme = isset($parsed['scheme']) ? $parsed['scheme'] : null; - $this->host = isset($parsed['host']) ? $parsed['host'] : null; - $this->port = isset($parsed['port']) ? $parsed['port'] : null; - $this->user = isset($parsed['user']) ? $parsed['user'] : null; - $this->pass = isset($parsed['pass']) ? $parsed['pass'] : null; - $this->path = isset($parsed['path']) ? $parsed['path'] : null; - $this->query = isset($parsed['query']) ? $parsed['query'] : null; - $this->fragment = isset($parsed['fragment']) ? $parsed['fragment'] : null; - } - - /** - * Create an instance - * - * Useful for chained validations - * - * @param string $uri - * @return self - */ - public static function factory($uri) - { - return new static($uri); - } - - /** - * Retrieve the host - * - * @return string - */ - public function getHost() - { - return $this->host; - } - - /** - * Retrieve the URI path - * - * @return string - */ - public function getPath() - { - return $this->path; - } - - /** - * Retrieve the scheme - * - * @return string - */ - public function getScheme() - { - return $this->scheme; - } - - /** - * Is the URI valid? - * - * @return bool - */ - public function isValid() - { - if (false === $this->valid) { - return false; - } - - if ($this->scheme && !in_array($this->scheme, $this->validSchemes)) { - return false; - } - - if ($this->host) { - if ($this->path && substr($this->path, 0, 1) != '/') { - return false; - } - return true; - } - - // no host, but user and/or port... what? - if ($this->user || $this->port) { - return false; - } - - if ($this->path) { - // Check path-only (no host) URI - if (substr($this->path, 0, 2) == '//') { - return false; - } - return true; - } - - if (! ($this->query || $this->fragment)) { - // No host, path, query or fragment - this is not a valid URI - return false; - } - - return true; - } - - /** - * Is the URI absolute? - * - * @return bool - */ - public function isAbsolute() - { - return ($this->scheme !== null); - } -} diff --git a/library/Zend/Feed/Writer/AbstractFeed.php b/library/Zend/Feed/Writer/AbstractFeed.php deleted file mode 100755 index 1dd6fe54b..000000000 --- a/library/Zend/Feed/Writer/AbstractFeed.php +++ /dev/null @@ -1,846 +0,0 @@ -_loadExtensions(); - } - - /** - * Set a single author - * - * The following option keys are supported: - * 'name' => (string) The name - * 'email' => (string) An optional email - * 'uri' => (string) An optional and valid URI - * - * @param array $author - * @throws Exception\InvalidArgumentException If any value of $author not follow the format. - * @return AbstractFeed - */ - public function addAuthor(array $author) - { - // Check array values - if (!array_key_exists('name', $author) - || empty($author['name']) - || !is_string($author['name']) - ) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter: author array must include a "name" key with a non-empty string value'); - } - - if (isset($author['email'])) { - if (empty($author['email']) || !is_string($author['email'])) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter: "email" array value must be a non-empty string'); - } - } - if (isset($author['uri'])) { - if (empty($author['uri']) || !is_string($author['uri']) || - !Uri::factory($author['uri'])->isValid() - ) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter: "uri" array value must be a non-empty string and valid URI/IRI'); - } - } - - $this->data['authors'][] = $author; - - return $this; - } - - /** - * Set an array with feed authors - * - * @see addAuthor - * @param array $authors - * @return AbstractFeed - */ - public function addAuthors(array $authors) - { - foreach ($authors as $author) { - $this->addAuthor($author); - } - - return $this; - } - - /** - * Set the copyright entry - * - * @param string $copyright - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setCopyright($copyright) - { - if (empty($copyright) || !is_string($copyright)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['copyright'] = $copyright; - - return $this; - } - - /** - * Set the feed creation date - * - * @param null|int|DateTime - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setDateCreated($date = null) - { - if ($date === null) { - $date = new DateTime(); - } elseif (is_int($date)) { - $date = new DateTime('@' . $date); - } elseif (!$date instanceof DateTime) { - throw new Exception\InvalidArgumentException('Invalid DateTime object or UNIX Timestamp' - . ' passed as parameter'); - } - $this->data['dateCreated'] = $date; - - return $this; - } - - /** - * Set the feed modification date - * - * @param null|int|DateTime - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setDateModified($date = null) - { - if ($date === null) { - $date = new DateTime(); - } elseif (is_int($date)) { - $date = new DateTime('@' . $date); - } elseif (!$date instanceof DateTime) { - throw new Exception\InvalidArgumentException('Invalid DateTime object or UNIX Timestamp' - . ' passed as parameter'); - } - $this->data['dateModified'] = $date; - - return $this; - } - - /** - * Set the feed last-build date. Ignored for Atom 1.0. - * - * @param null|int|DateTime - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setLastBuildDate($date = null) - { - if ($date === null) { - $date = new DateTime(); - } elseif (is_int($date)) { - $date = new DateTime('@' . $date); - } elseif (!$date instanceof DateTime) { - throw new Exception\InvalidArgumentException('Invalid DateTime object or UNIX Timestamp' - . ' passed as parameter'); - } - $this->data['lastBuildDate'] = $date; - - return $this; - } - - /** - * Set the feed description - * - * @param string $description - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setDescription($description) - { - if (empty($description) || !is_string($description)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['description'] = $description; - - return $this; - } - - /** - * Set the feed generator entry - * - * @param array|string $name - * @param null|string $version - * @param null|string $uri - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setGenerator($name, $version = null, $uri = null) - { - if (is_array($name)) { - $data = $name; - if (empty($data['name']) || !is_string($data['name'])) { - throw new Exception\InvalidArgumentException('Invalid parameter: "name" must be a non-empty string'); - } - $generator = array('name' => $data['name']); - if (isset($data['version'])) { - if (empty($data['version']) || !is_string($data['version'])) { - throw new Exception\InvalidArgumentException('Invalid parameter: "version" must be a non-empty string'); - } - $generator['version'] = $data['version']; - } - if (isset($data['uri'])) { - if (empty($data['uri']) || !is_string($data['uri']) || !Uri::factory($data['uri'])->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "uri" must be a non-empty string and a valid URI/IRI'); - } - $generator['uri'] = $data['uri']; - } - } else { - if (empty($name) || !is_string($name)) { - throw new Exception\InvalidArgumentException('Invalid parameter: "name" must be a non-empty string'); - } - $generator = array('name' => $name); - if (isset($version)) { - if (empty($version) || !is_string($version)) { - throw new Exception\InvalidArgumentException('Invalid parameter: "version" must be a non-empty string'); - } - $generator['version'] = $version; - } - if (isset($uri)) { - if (empty($uri) || !is_string($uri) || !Uri::factory($uri)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "uri" must be a non-empty string and a valid URI/IRI'); - } - $generator['uri'] = $uri; - } - } - $this->data['generator'] = $generator; - - return $this; - } - - /** - * Set the feed ID - URI or URN (via PCRE pattern) supported - * - * @param string $id - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setId($id) - { - if ((empty($id) || !is_string($id) || !Uri::factory($id)->isValid()) - && !preg_match("#^urn:[a-zA-Z0-9][a-zA-Z0-9\-]{1,31}:([a-zA-Z0-9\(\)\+\,\.\:\=\@\;\$\_\!\*\-]|%[0-9a-fA-F]{2})*#", $id) - && !$this->_validateTagUri($id) - ) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string and valid URI/IRI'); - } - $this->data['id'] = $id; - - return $this; - } - - /** - * Validate a URI using the tag scheme (RFC 4151) - * - * @param string $id - * @return bool - */ - protected function _validateTagUri($id) - { - if (preg_match('/^tag:(?P.*),(?P\d{4}-?\d{0,2}-?\d{0,2}):(?P.*)(.*:)*$/', $id, $matches)) { - $dvalid = false; - $date = $matches['date']; - $d6 = strtotime($date); - if ((strlen($date) == 4) && $date <= date('Y')) { - $dvalid = true; - } elseif ((strlen($date) == 7) && ($d6 < strtotime("now"))) { - $dvalid = true; - } elseif ((strlen($date) == 10) && ($d6 < strtotime("now"))) { - $dvalid = true; - } - $validator = new Validator\EmailAddress; - if ($validator->isValid($matches['name'])) { - $nvalid = true; - } else { - $nvalid = $validator->isValid('info@' . $matches['name']); - } - return $dvalid && $nvalid; - } - return false; - } - - /** - * Set a feed image (URI at minimum). Parameter is a single array with the - * required key 'uri'. When rendering as RSS, the required keys are 'uri', - * 'title' and 'link'. RSS also specifies three optional parameters 'width', - * 'height' and 'description'. Only 'uri' is required and used for Atom rendering. - * - * @param array $data - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setImage(array $data) - { - if (empty($data['uri']) || !is_string($data['uri']) - || !Uri::factory($data['uri'])->isValid() - ) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter \'uri\'' - . ' must be a non-empty string and valid URI/IRI'); - } - $this->data['image'] = $data; - - return $this; - } - - /** - * Set the feed language - * - * @param string $language - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setLanguage($language) - { - if (empty($language) || !is_string($language)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['language'] = $language; - - return $this; - } - - /** - * Set a link to the HTML source - * - * @param string $link - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setLink($link) - { - if (empty($link) || !is_string($link) || !Uri::factory($link)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string and valid URI/IRI'); - } - $this->data['link'] = $link; - - return $this; - } - - /** - * Set a link to an XML feed for any feed type/version - * - * @param string $link - * @param string $type - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setFeedLink($link, $type) - { - if (empty($link) || !is_string($link) || !Uri::factory($link)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "link"" must be a non-empty string and valid URI/IRI'); - } - if (!in_array(strtolower($type), array('rss', 'rdf', 'atom'))) { - throw new Exception\InvalidArgumentException('Invalid parameter: "type"; You must declare the type of feed the link points to, i.e. RSS, RDF or Atom'); - } - $this->data['feedLinks'][strtolower($type)] = $link; - - return $this; - } - - /** - * Set the feed title - * - * @param string $title - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setTitle($title) - { - if (empty($title) || !is_string($title)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['title'] = $title; - - return $this; - } - - /** - * Set the feed character encoding - * - * @param string $encoding - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setEncoding($encoding) - { - if (empty($encoding) || !is_string($encoding)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['encoding'] = $encoding; - - return $this; - } - - /** - * Set the feed's base URL - * - * @param string $url - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function setBaseUrl($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "url" array value' - . ' must be a non-empty string and valid URI/IRI'); - } - $this->data['baseUrl'] = $url; - - return $this; - } - - /** - * Add a Pubsubhubbub hub endpoint URL - * - * @param string $url - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function addHub($url) - { - if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "url" array value' - . ' must be a non-empty string and valid URI/IRI'); - } - if (!isset($this->data['hubs'])) { - $this->data['hubs'] = array(); - } - $this->data['hubs'][] = $url; - - return $this; - } - - /** - * Add Pubsubhubbub hub endpoint URLs - * - * @param array $urls - * @return AbstractFeed - */ - public function addHubs(array $urls) - { - foreach ($urls as $url) { - $this->addHub($url); - } - - return $this; - } - - /** - * Add a feed category - * - * @param array $category - * @throws Exception\InvalidArgumentException - * @return AbstractFeed - */ - public function addCategory(array $category) - { - if (!isset($category['term'])) { - throw new Exception\InvalidArgumentException('Each category must be an array and ' - . 'contain at least a "term" element containing the machine ' - . ' readable category name'); - } - if (isset($category['scheme'])) { - if (empty($category['scheme']) - || !is_string($category['scheme']) - || !Uri::factory($category['scheme'])->isValid() - ) { - throw new Exception\InvalidArgumentException('The Atom scheme or RSS domain of' - . ' a category must be a valid URI'); - } - } - if (!isset($this->data['categories'])) { - $this->data['categories'] = array(); - } - $this->data['categories'][] = $category; - - return $this; - } - - /** - * Set an array of feed categories - * - * @param array $categories - * @return AbstractFeed - */ - public function addCategories(array $categories) - { - foreach ($categories as $category) { - $this->addCategory($category); - } - - return $this; - } - - /** - * Get a single author - * - * @param int $index - * @return string|null - */ - public function getAuthor($index = 0) - { - if (isset($this->data['authors'][$index])) { - return $this->data['authors'][$index]; - } - - return null; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (!array_key_exists('authors', $this->data)) { - return null; - } - return $this->data['authors']; - } - - /** - * Get the copyright entry - * - * @return string|null - */ - public function getCopyright() - { - if (!array_key_exists('copyright', $this->data)) { - return null; - } - return $this->data['copyright']; - } - - /** - * Get the feed creation date - * - * @return string|null - */ - public function getDateCreated() - { - if (!array_key_exists('dateCreated', $this->data)) { - return null; - } - return $this->data['dateCreated']; - } - - /** - * Get the feed modification date - * - * @return string|null - */ - public function getDateModified() - { - if (!array_key_exists('dateModified', $this->data)) { - return null; - } - return $this->data['dateModified']; - } - - /** - * Get the feed last-build date - * - * @return string|null - */ - public function getLastBuildDate() - { - if (!array_key_exists('lastBuildDate', $this->data)) { - return null; - } - return $this->data['lastBuildDate']; - } - - /** - * Get the feed description - * - * @return string|null - */ - public function getDescription() - { - if (!array_key_exists('description', $this->data)) { - return null; - } - return $this->data['description']; - } - - /** - * Get the feed generator entry - * - * @return string|null - */ - public function getGenerator() - { - if (!array_key_exists('generator', $this->data)) { - return null; - } - return $this->data['generator']; - } - - /** - * Get the feed ID - * - * @return string|null - */ - public function getId() - { - if (!array_key_exists('id', $this->data)) { - return null; - } - return $this->data['id']; - } - - /** - * Get the feed image URI - * - * @return array - */ - public function getImage() - { - if (!array_key_exists('image', $this->data)) { - return null; - } - return $this->data['image']; - } - - /** - * Get the feed language - * - * @return string|null - */ - public function getLanguage() - { - if (!array_key_exists('language', $this->data)) { - return null; - } - return $this->data['language']; - } - - /** - * Get a link to the HTML source - * - * @return string|null - */ - public function getLink() - { - if (!array_key_exists('link', $this->data)) { - return null; - } - return $this->data['link']; - } - - /** - * Get a link to the XML feed - * - * @return string|null - */ - public function getFeedLinks() - { - if (!array_key_exists('feedLinks', $this->data)) { - return null; - } - return $this->data['feedLinks']; - } - - /** - * Get the feed title - * - * @return string|null - */ - public function getTitle() - { - if (!array_key_exists('title', $this->data)) { - return null; - } - return $this->data['title']; - } - - /** - * Get the feed character encoding - * - * @return string|null - */ - public function getEncoding() - { - if (!array_key_exists('encoding', $this->data)) { - return 'UTF-8'; - } - return $this->data['encoding']; - } - - /** - * Get the feed's base url - * - * @return string|null - */ - public function getBaseUrl() - { - if (!array_key_exists('baseUrl', $this->data)) { - return null; - } - return $this->data['baseUrl']; - } - - /** - * Get the URLs used as Pubsubhubbub hubs endpoints - * - * @return string|null - */ - public function getHubs() - { - if (!array_key_exists('hubs', $this->data)) { - return null; - } - return $this->data['hubs']; - } - - /** - * Get the feed categories - * - * @return string|null - */ - public function getCategories() - { - if (!array_key_exists('categories', $this->data)) { - return null; - } - return $this->data['categories']; - } - - /** - * Resets the instance and deletes all data - * - * @return void - */ - public function reset() - { - $this->data = array(); - } - - /** - * Set the current feed type being exported to "rss" or "atom". This allows - * other objects to gracefully choose whether to execute or not, depending - * on their appropriateness for the current type, e.g. renderers. - * - * @param string $type - * @return AbstractFeed - */ - public function setType($type) - { - $this->type = $type; - return $this; - } - - /** - * Retrieve the current or last feed type exported. - * - * @return string Value will be "rss" or "atom" - */ - public function getType() - { - return $this->type; - } - - /** - * Unset a specific data point - * - * @param string $name - * @return AbstractFeed - */ - public function remove($name) - { - if (isset($this->data[$name])) { - unset($this->data[$name]); - } - return $this; - } - - /** - * Method overloading: call given method on first extension implementing it - * - * @param string $method - * @param array $args - * @return mixed - * @throws Exception\BadMethodCallException if no extensions implements the method - */ - public function __call($method, $args) - { - foreach ($this->extensions as $extension) { - try { - return call_user_func_array(array($extension, $method), $args); - } catch (Exception\BadMethodCallException $e) { - } - } - throw new Exception\BadMethodCallException( - 'Method: ' . $method . ' does not exist and could not be located on a registered Extension' - ); - } - - /** - * Load extensions from Zend\Feed\Writer\Writer - * - * @throws Exception\RuntimeException - * @return void - */ - protected function _loadExtensions() - { - $all = Writer::getExtensions(); - $manager = Writer::getExtensionManager(); - $exts = $all['feed']; - foreach ($exts as $ext) { - if (!$manager->has($ext)) { - throw new Exception\RuntimeException(sprintf('Unable to load extension "%s"; could not resolve to class', $ext)); - } - $this->extensions[$ext] = $manager->get($ext); - $this->extensions[$ext]->setEncoding($this->getEncoding()); - } - } -} diff --git a/library/Zend/Feed/Writer/Deleted.php b/library/Zend/Feed/Writer/Deleted.php deleted file mode 100755 index b91ee0945..000000000 --- a/library/Zend/Feed/Writer/Deleted.php +++ /dev/null @@ -1,236 +0,0 @@ -data['encoding'] = $encoding; - - return $this; - } - - /** - * Get the feed character encoding - * - * @return string|null - */ - public function getEncoding() - { - if (!array_key_exists('encoding', $this->data)) { - return 'UTF-8'; - } - return $this->data['encoding']; - } - - /** - * Unset a specific data point - * - * @param string $name - * @return Deleted - */ - public function remove($name) - { - if (isset($this->data[$name])) { - unset($this->data[$name]); - } - - return $this; - } - - /** - * Set the current feed type being exported to "rss" or "atom". This allows - * other objects to gracefully choose whether to execute or not, depending - * on their appropriateness for the current type, e.g. renderers. - * - * @param string $type - * @return Deleted - */ - public function setType($type) - { - $this->type = $type; - return $this; - } - - /** - * Retrieve the current or last feed type exported. - * - * @return string Value will be "rss" or "atom" - */ - public function getType() - { - return $this->type; - } - - /** - * Set reference - * - * @param $reference - * @throws Exception\InvalidArgumentException - * @return Deleted - */ - public function setReference($reference) - { - if (empty($reference) || !is_string($reference)) { - throw new Exception\InvalidArgumentException('Invalid parameter: reference must be a non-empty string'); - } - $this->data['reference'] = $reference; - - return $this; - } - - /** - * @return string - */ - public function getReference() - { - if (!array_key_exists('reference', $this->data)) { - return null; - } - return $this->data['reference']; - } - - /** - * Set when - * - * @param null|string|DateTime $date - * @throws Exception\InvalidArgumentException - * @return Deleted - */ - public function setWhen($date = null) - { - if ($date === null) { - $date = new DateTime(); - } elseif (is_int($date)) { - $date = new DateTime('@' . $date); - } elseif (!$date instanceof DateTime) { - throw new Exception\InvalidArgumentException('Invalid DateTime object or UNIX Timestamp' - . ' passed as parameter'); - } - $this->data['when'] = $date; - - return $this; - } - - /** - * @return DateTime - */ - public function getWhen() - { - if (!array_key_exists('when', $this->data)) { - return null; - } - return $this->data['when']; - } - - /** - * Set by - * - * @param array $by - * @throws Exception\InvalidArgumentException - * @return Deleted - */ - public function setBy(array $by) - { - $author = array(); - if (!array_key_exists('name', $by) - || empty($by['name']) - || !is_string($by['name']) - ) { - throw new Exception\InvalidArgumentException('Invalid parameter: author array must include a' - . ' "name" key with a non-empty string value'); - } - $author['name'] = $by['name']; - if (isset($by['email'])) { - if (empty($by['email']) || !is_string($by['email'])) { - throw new Exception\InvalidArgumentException('Invalid parameter: "email" array' - . ' value must be a non-empty string'); - } - $author['email'] = $by['email']; - } - if (isset($by['uri'])) { - if (empty($by['uri']) - || !is_string($by['uri']) - || !Uri::factory($by['uri'])->isValid() - ) { - throw new Exception\InvalidArgumentException('Invalid parameter: "uri" array value must' - . ' be a non-empty string and valid URI/IRI'); - } - $author['uri'] = $by['uri']; - } - $this->data['by'] = $author; - - return $this; - } - - /** - * @return string - */ - public function getBy() - { - if (!array_key_exists('by', $this->data)) { - return null; - } - return $this->data['by']; - } - - /** - * @param string $comment - * @return Deleted - */ - public function setComment($comment) - { - $this->data['comment'] = $comment; - return $this; - } - - /** - * @return string - */ - public function getComment() - { - if (!array_key_exists('comment', $this->data)) { - return null; - } - return $this->data['comment']; - } -} diff --git a/library/Zend/Feed/Writer/Entry.php b/library/Zend/Feed/Writer/Entry.php deleted file mode 100755 index c5b1085ac..000000000 --- a/library/Zend/Feed/Writer/Entry.php +++ /dev/null @@ -1,765 +0,0 @@ -_loadExtensions(); - } - - /** - * Set a single author - * - * The following option keys are supported: - * 'name' => (string) The name - * 'email' => (string) An optional email - * 'uri' => (string) An optional and valid URI - * - * @param array $author - * @throws Exception\InvalidArgumentException If any value of $author not follow the format. - * @return Entry - */ - public function addAuthor(array $author) - { - // Check array values - if (!array_key_exists('name', $author) - || empty($author['name']) - || !is_string($author['name']) - ) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter: author array must include a "name" key with a non-empty string value'); - } - - if (isset($author['email'])) { - if (empty($author['email']) || !is_string($author['email'])) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter: "email" array value must be a non-empty string'); - } - } - if (isset($author['uri'])) { - if (empty($author['uri']) || !is_string($author['uri']) || - !Uri::factory($author['uri'])->isValid() - ) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter: "uri" array value must be a non-empty string and valid URI/IRI'); - } - } - - $this->data['authors'][] = $author; - - return $this; - } - - /** - * Set an array with feed authors - * - * @see addAuthor - * @param array $authors - * @return Entry - */ - public function addAuthors(array $authors) - { - foreach ($authors as $author) { - $this->addAuthor($author); - } - - return $this; - } - - /** - * Set the feed character encoding - * - * @param string $encoding - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setEncoding($encoding) - { - if (empty($encoding) || !is_string($encoding)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['encoding'] = $encoding; - - return $this; - } - - /** - * Get the feed character encoding - * - * @return string|null - */ - public function getEncoding() - { - if (!array_key_exists('encoding', $this->data)) { - return 'UTF-8'; - } - return $this->data['encoding']; - } - - /** - * Set the copyright entry - * - * @param string $copyright - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setCopyright($copyright) - { - if (empty($copyright) || !is_string($copyright)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['copyright'] = $copyright; - - return $this; - } - - /** - * Set the entry's content - * - * @param string $content - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setContent($content) - { - if (empty($content) || !is_string($content)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['content'] = $content; - - return $this; - } - - /** - * Set the feed creation date - * - * @param null|int|DateTime $date - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setDateCreated($date = null) - { - if ($date === null) { - $date = new DateTime(); - } elseif (is_int($date)) { - $date = new DateTime('@' . $date); - } elseif (!$date instanceof DateTime) { - throw new Exception\InvalidArgumentException('Invalid DateTime object or UNIX Timestamp passed as parameter'); - } - $this->data['dateCreated'] = $date; - - return $this; - } - - /** - * Set the feed modification date - * - * @param null|int|DateTime $date - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setDateModified($date = null) - { - if ($date === null) { - $date = new DateTime(); - } elseif (is_int($date)) { - $date = new DateTime('@' . $date); - } elseif (!$date instanceof DateTime) { - throw new Exception\InvalidArgumentException('Invalid DateTime object or UNIX Timestamp passed as parameter'); - } - $this->data['dateModified'] = $date; - - return $this; - } - - /** - * Set the feed description - * - * @param string $description - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setDescription($description) - { - if (empty($description) || !is_string($description)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['description'] = $description; - - return $this; - } - - /** - * Set the feed ID - * - * @param string $id - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setId($id) - { - if (empty($id) || !is_string($id)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['id'] = $id; - - return $this; - } - - /** - * Set a link to the HTML source of this entry - * - * @param string $link - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setLink($link) - { - if (empty($link) || !is_string($link) || !Uri::factory($link)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string and valid URI/IRI'); - } - $this->data['link'] = $link; - - return $this; - } - - /** - * Set the number of comments associated with this entry - * - * @param int $count - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setCommentCount($count) - { - if (!is_numeric($count) || (int) $count != $count || (int) $count < 0) { - throw new Exception\InvalidArgumentException('Invalid parameter: "count" must be a positive integer number or zero'); - } - $this->data['commentCount'] = (int) $count; - - return $this; - } - - /** - * Set a link to a HTML page containing comments associated with this entry - * - * @param string $link - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setCommentLink($link) - { - if (empty($link) || !is_string($link) || !Uri::factory($link)->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "link" must be a non-empty string and valid URI/IRI'); - } - $this->data['commentLink'] = $link; - - return $this; - } - - /** - * Set a link to an XML feed for any comments associated with this entry - * - * @param array $link - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setCommentFeedLink(array $link) - { - if (!isset($link['uri']) || !is_string($link['uri']) || !Uri::factory($link['uri'])->isValid()) { - throw new Exception\InvalidArgumentException('Invalid parameter: "link" must be a non-empty string and valid URI/IRI'); - } - if (!isset($link['type']) || !in_array($link['type'], array('atom', 'rss', 'rdf'))) { - throw new Exception\InvalidArgumentException('Invalid parameter: "type" must be one' - . ' of "atom", "rss" or "rdf"'); - } - if (!isset($this->data['commentFeedLinks'])) { - $this->data['commentFeedLinks'] = array(); - } - $this->data['commentFeedLinks'][] = $link; - - return $this; - } - - /** - * Set a links to an XML feed for any comments associated with this entry. - * Each link is an array with keys "uri" and "type", where type is one of: - * "atom", "rss" or "rdf". - * - * @param array $links - * @return Entry - */ - public function setCommentFeedLinks(array $links) - { - foreach ($links as $link) { - $this->setCommentFeedLink($link); - } - - return $this; - } - - /** - * Set the feed title - * - * @param string $title - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setTitle($title) - { - if (empty($title) || !is_string($title)) { - throw new Exception\InvalidArgumentException('Invalid parameter: parameter must be a non-empty string'); - } - $this->data['title'] = $title; - - return $this; - } - - /** - * Get an array with feed authors - * - * @return array - */ - public function getAuthors() - { - if (!array_key_exists('authors', $this->data)) { - return null; - } - return $this->data['authors']; - } - - /** - * Get the entry content - * - * @return string - */ - public function getContent() - { - if (!array_key_exists('content', $this->data)) { - return null; - } - return $this->data['content']; - } - - /** - * Get the entry copyright information - * - * @return string - */ - public function getCopyright() - { - if (!array_key_exists('copyright', $this->data)) { - return null; - } - return $this->data['copyright']; - } - - /** - * Get the entry creation date - * - * @return string - */ - public function getDateCreated() - { - if (!array_key_exists('dateCreated', $this->data)) { - return null; - } - return $this->data['dateCreated']; - } - - /** - * Get the entry modification date - * - * @return string - */ - public function getDateModified() - { - if (!array_key_exists('dateModified', $this->data)) { - return null; - } - return $this->data['dateModified']; - } - - /** - * Get the entry description - * - * @return string - */ - public function getDescription() - { - if (!array_key_exists('description', $this->data)) { - return null; - } - return $this->data['description']; - } - - /** - * Get the entry ID - * - * @return string - */ - public function getId() - { - if (!array_key_exists('id', $this->data)) { - return null; - } - return $this->data['id']; - } - - /** - * Get a link to the HTML source - * - * @return string|null - */ - public function getLink() - { - if (!array_key_exists('link', $this->data)) { - return null; - } - return $this->data['link']; - } - - - /** - * Get all links - * - * @return array - */ - public function getLinks() - { - if (!array_key_exists('links', $this->data)) { - return null; - } - return $this->data['links']; - } - - /** - * Get the entry title - * - * @return string - */ - public function getTitle() - { - if (!array_key_exists('title', $this->data)) { - return null; - } - return $this->data['title']; - } - - /** - * Get the number of comments/replies for current entry - * - * @return int - */ - public function getCommentCount() - { - if (!array_key_exists('commentCount', $this->data)) { - return null; - } - return $this->data['commentCount']; - } - - /** - * Returns a URI pointing to the HTML page where comments can be made on this entry - * - * @return string - */ - public function getCommentLink() - { - if (!array_key_exists('commentLink', $this->data)) { - return null; - } - return $this->data['commentLink']; - } - - /** - * Returns an array of URIs pointing to a feed of all comments for this entry - * where the array keys indicate the feed type (atom, rss or rdf). - * - * @return string - */ - public function getCommentFeedLinks() - { - if (!array_key_exists('commentFeedLinks', $this->data)) { - return null; - } - return $this->data['commentFeedLinks']; - } - - /** - * Add an entry category - * - * @param array $category - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function addCategory(array $category) - { - if (!isset($category['term'])) { - throw new Exception\InvalidArgumentException('Each category must be an array and ' - . 'contain at least a "term" element containing the machine ' - . ' readable category name'); - } - if (isset($category['scheme'])) { - if (empty($category['scheme']) - || !is_string($category['scheme']) - || !Uri::factory($category['scheme'])->isValid() - ) { - throw new Exception\InvalidArgumentException('The Atom scheme or RSS domain of' - . ' a category must be a valid URI'); - } - } - if (!isset($this->data['categories'])) { - $this->data['categories'] = array(); - } - $this->data['categories'][] = $category; - - return $this; - } - - /** - * Set an array of entry categories - * - * @param array $categories - * @return Entry - */ - public function addCategories(array $categories) - { - foreach ($categories as $category) { - $this->addCategory($category); - } - - return $this; - } - - /** - * Get the entry categories - * - * @return string|null - */ - public function getCategories() - { - if (!array_key_exists('categories', $this->data)) { - return null; - } - return $this->data['categories']; - } - - /** - * Adds an enclosure to the entry. The array parameter may contain the - * keys 'uri', 'type' and 'length'. Only 'uri' is required for Atom, though the - * others must also be provided or RSS rendering (where they are required) - * will throw an Exception. - * - * @param array $enclosure - * @throws Exception\InvalidArgumentException - * @return Entry - */ - public function setEnclosure(array $enclosure) - { - if (!isset($enclosure['uri'])) { - throw new Exception\InvalidArgumentException('Enclosure "uri" is not set'); - } - if (!Uri::factory($enclosure['uri'])->isValid()) { - throw new Exception\InvalidArgumentException('Enclosure "uri" is not a valid URI/IRI'); - } - $this->data['enclosure'] = $enclosure; - - return $this; - } - - /** - * Retrieve an array of all enclosures to be added to entry. - * - * @return array - */ - public function getEnclosure() - { - if (!array_key_exists('enclosure', $this->data)) { - return null; - } - return $this->data['enclosure']; - } - - /** - * Unset a specific data point - * - * @param string $name - * @return Entry - */ - public function remove($name) - { - if (isset($this->data[$name])) { - unset($this->data[$name]); - } - - return $this; - } - - /** - * Get registered extensions - * - * @return array - */ - public function getExtensions() - { - return $this->extensions; - } - - /** - * Return an Extension object with the matching name (postfixed with _Entry) - * - * @param string $name - * @return object - */ - public function getExtension($name) - { - if (array_key_exists($name . '\\Entry', $this->extensions)) { - return $this->extensions[$name . '\\Entry']; - } - return null; - } - - /** - * Set the current feed type being exported to "rss" or "atom". This allows - * other objects to gracefully choose whether to execute or not, depending - * on their appropriateness for the current type, e.g. renderers. - * - * @param string $type - * @return Entry - */ - public function setType($type) - { - $this->type = $type; - return $this; - } - - /** - * Retrieve the current or last feed type exported. - * - * @return string Value will be "rss" or "atom" - */ - public function getType() - { - return $this->type; - } - - /** - * Method overloading: call given method on first extension implementing it - * - * @param string $method - * @param array $args - * @return mixed - * @throws Exception\BadMethodCallException if no extensions implements the method - */ - public function __call($method, $args) - { - foreach ($this->extensions as $extension) { - try { - return call_user_func_array(array($extension, $method), $args); - } catch (\BadMethodCallException $e) { - } - } - throw new Exception\BadMethodCallException('Method: ' . $method - . ' does not exist and could not be located on a registered Extension'); - } - - /** - * Creates a new Zend\Feed\Writer\Source data container for use. This is NOT - * added to the current feed automatically, but is necessary to create a - * container with some initial values preset based on the current feed data. - * - * @return Source - */ - public function createSource() - { - $source = new Source; - if ($this->getEncoding()) { - $source->setEncoding($this->getEncoding()); - } - $source->setType($this->getType()); - return $source; - } - - /** - * Appends a Zend\Feed\Writer\Entry object representing a new entry/item - * the feed data container's internal group of entries. - * - * @param Source $source - * @return Entry - */ - public function setSource(Source $source) - { - $this->data['source'] = $source; - return $this; - } - - /** - * @return Source - */ - public function getSource() - { - if (isset($this->data['source'])) { - return $this->data['source']; - } - return null; - } - - /** - * Load extensions from Zend\Feed\Writer\Writer - * - * @return void - */ - protected function _loadExtensions() - { - $all = Writer::getExtensions(); - $manager = Writer::getExtensionManager(); - $exts = $all['entry']; - foreach ($exts as $ext) { - $this->extensions[$ext] = $manager->get($ext); - $this->extensions[$ext]->setEncoding($this->getEncoding()); - } - } -} diff --git a/library/Zend/Feed/Writer/Exception/BadMethodCallException.php b/library/Zend/Feed/Writer/Exception/BadMethodCallException.php deleted file mode 100755 index 79d1c82c7..000000000 --- a/library/Zend/Feed/Writer/Exception/BadMethodCallException.php +++ /dev/null @@ -1,23 +0,0 @@ -container = $container; - return $this; - } - - /** - * Set feed encoding - * - * @param string $enc - * @return AbstractRenderer - */ - public function setEncoding($enc) - { - $this->encoding = $enc; - return $this; - } - - /** - * Get feed encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set DOMDocument and DOMElement on which to operate - * - * @param DOMDocument $dom - * @param DOMElement $base - * @return AbstractRenderer - */ - public function setDomDocument(DOMDocument $dom, DOMElement $base) - { - $this->dom = $dom; - $this->base = $base; - return $this; - } - - /** - * Get data container being rendered - * - * @return mixed - */ - public function getDataContainer() - { - return $this->container; - } - - /** - * Set feed type - * - * @param string $type - * @return AbstractRenderer - */ - public function setType($type) - { - $this->type = $type; - return $this; - } - - /** - * Get feedtype - * - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Set root element of document - * - * @param DOMElement $root - * @return AbstractRenderer - */ - public function setRootElement(DOMElement $root) - { - $this->rootElement = $root; - return $this; - } - - /** - * Get root element - * - * @return DOMElement - */ - public function getRootElement() - { - return $this->rootElement; - } - - /** - * Append namespaces to feed - * - * @return void - */ - abstract protected function _appendNamespaces(); -} diff --git a/library/Zend/Feed/Writer/Extension/Atom/Renderer/Feed.php b/library/Zend/Feed/Writer/Extension/Atom/Renderer/Feed.php deleted file mode 100755 index 6b24ec01c..000000000 --- a/library/Zend/Feed/Writer/Extension/Atom/Renderer/Feed.php +++ /dev/null @@ -1,108 +0,0 @@ -getType()) == 'atom') { - return; - } - $this->_setFeedLinks($this->dom, $this->base); - $this->_setHubs($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append namespaces to root element of feed - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:atom', - 'http://www.w3.org/2005/Atom'); - } - - /** - * Set feed link elements - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setFeedLinks(DOMDocument $dom, DOMElement $root) - { - $flinks = $this->getDataContainer()->getFeedLinks(); - if (!$flinks || empty($flinks)) { - return; - } - foreach ($flinks as $type => $href) { - if (strtolower($type) == $this->getType()) { // issue 2605 - $mime = 'application/' . strtolower($type) . '+xml'; - $flink = $dom->createElement('atom:link'); - $root->appendChild($flink); - $flink->setAttribute('rel', 'self'); - $flink->setAttribute('type', $mime); - $flink->setAttribute('href', $href); - } - } - $this->called = true; - } - - /** - * Set PuSH hubs - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setHubs(DOMDocument $dom, DOMElement $root) - { - $hubs = $this->getDataContainer()->getHubs(); - if (!$hubs || empty($hubs)) { - return; - } - foreach ($hubs as $hubUrl) { - $hub = $dom->createElement('atom:link'); - $hub->setAttribute('rel', 'hub'); - $hub->setAttribute('href', $hubUrl); - $root->appendChild($hub); - } - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/Content/Renderer/Entry.php b/library/Zend/Feed/Writer/Extension/Content/Renderer/Entry.php deleted file mode 100755 index b90315169..000000000 --- a/library/Zend/Feed/Writer/Extension/Content/Renderer/Entry.php +++ /dev/null @@ -1,75 +0,0 @@ -getType()) == 'atom') { - return; - } - $this->_setContent($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append namespaces to root element - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:content', - 'http://purl.org/rss/1.0/modules/content/'); - } - - /** - * Set entry content - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setContent(DOMDocument $dom, DOMElement $root) - { - $content = $this->getDataContainer()->getContent(); - if (!$content) { - return; - } - $element = $dom->createElement('content:encoded'); - $root->appendChild($element); - $cdata = $dom->createCDATASection($content); - $element->appendChild($cdata); - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Entry.php b/library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Entry.php deleted file mode 100755 index 8f9465c70..000000000 --- a/library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Entry.php +++ /dev/null @@ -1,79 +0,0 @@ -getType()) == 'atom') { - return; - } - $this->_setAuthors($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append namespaces to entry - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:dc', - 'http://purl.org/dc/elements/1.1/'); - } - - /** - * Set entry author elements - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->getDataContainer()->getAuthors(); - if (!$authors || empty($authors)) { - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('dc:creator'); - if (array_key_exists('name', $data)) { - $text = $dom->createTextNode($data['name']); - $author->appendChild($text); - $root->appendChild($author); - } - } - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Feed.php b/library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Feed.php deleted file mode 100755 index 6e68f98e8..000000000 --- a/library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Feed.php +++ /dev/null @@ -1,79 +0,0 @@ -getType()) == 'atom') { - return; - } - $this->_setAuthors($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append namespaces to feed element - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:dc', - 'http://purl.org/dc/elements/1.1/'); - } - - /** - * Set feed authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->getDataContainer()->getAuthors(); - if (!$authors || empty($authors)) { - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('dc:creator'); - if (array_key_exists('name', $data)) { - $text = $dom->createTextNode($data['name']); - $author->appendChild($text); - $root->appendChild($author); - } - } - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/ITunes/Entry.php b/library/Zend/Feed/Writer/Extension/ITunes/Entry.php deleted file mode 100755 index 1b7b64aa5..000000000 --- a/library/Zend/Feed/Writer/Extension/ITunes/Entry.php +++ /dev/null @@ -1,246 +0,0 @@ -stringWrapper = StringUtils::getWrapper($this->encoding); - } - - /** - * Set feed encoding - * - * @param string $enc - * @return Entry - */ - public function setEncoding($enc) - { - $this->stringWrapper = StringUtils::getWrapper($enc); - $this->encoding = $enc; - return $this; - } - - /** - * Get feed encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set a block value of "yes" or "no". You may also set an empty string. - * - * @param string - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesBlock($value) - { - if (!ctype_alpha($value) && strlen($value) > 0) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "block" may only' - . ' contain alphabetic characters'); - } - - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "block" may only' - . ' contain a maximum of 255 characters'); - } - $this->data['block'] = $value; - } - - /** - * Add authors to itunes entry - * - * @param array $values - * @return Entry - */ - public function addItunesAuthors(array $values) - { - foreach ($values as $value) { - $this->addItunesAuthor($value); - } - return $this; - } - - /** - * Add author to itunes entry - * - * @param string $value - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function addItunesAuthor($value) - { - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "author" may only' - . ' contain a maximum of 255 characters each'); - } - if (!isset($this->data['authors'])) { - $this->data['authors'] = array(); - } - $this->data['authors'][] = $value; - return $this; - } - - /** - * Set duration - * - * @param int $value - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesDuration($value) - { - $value = (string) $value; - if (!ctype_digit($value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}$/", $value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/", $value) - ) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "duration" may only' - . ' be of a specified [[HH:]MM:]SS format'); - } - $this->data['duration'] = $value; - return $this; - } - - /** - * Set "explicit" flag - * - * @param bool $value - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesExplicit($value) - { - if (!in_array($value, array('yes', 'no', 'clean'))) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "explicit" may only' - . ' be one of "yes", "no" or "clean"'); - } - $this->data['explicit'] = $value; - return $this; - } - - /** - * Set keywords - * - * @param array $value - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesKeywords(array $value) - { - if (count($value) > 12) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "keywords" may only' - . ' contain a maximum of 12 terms'); - } - - $concat = implode(',', $value); - if ($this->stringWrapper->strlen($concat) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "keywords" may only' - . ' have a concatenated length of 255 chars where terms are delimited' - . ' by a comma'); - } - $this->data['keywords'] = $value; - return $this; - } - - /** - * Set subtitle - * - * @param string $value - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesSubtitle($value) - { - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "subtitle" may only' - . ' contain a maximum of 255 characters'); - } - $this->data['subtitle'] = $value; - return $this; - } - - /** - * Set summary - * - * @param string $value - * @return Entry - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesSummary($value) - { - if ($this->stringWrapper->strlen($value) > 4000) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "summary" may only' - . ' contain a maximum of 4000 characters'); - } - $this->data['summary'] = $value; - return $this; - } - - /** - * Overloading to itunes specific setters - * - * @param string $method - * @param array $params - * @throws Writer\Exception\BadMethodCallException - * @return mixed - */ - public function __call($method, array $params) - { - $point = lcfirst(substr($method, 9)); - if (!method_exists($this, 'setItunes' . ucfirst($point)) - && !method_exists($this, 'addItunes' . ucfirst($point)) - ) { - throw new Writer\Exception\BadMethodCallException( - 'invalid method: ' . $method - ); - } - if (!array_key_exists($point, $this->data) - || empty($this->data[$point]) - ) { - return null; - } - return $this->data[$point]; - } -} diff --git a/library/Zend/Feed/Writer/Extension/ITunes/Feed.php b/library/Zend/Feed/Writer/Extension/ITunes/Feed.php deleted file mode 100755 index 22c54db6e..000000000 --- a/library/Zend/Feed/Writer/Extension/ITunes/Feed.php +++ /dev/null @@ -1,362 +0,0 @@ -stringWrapper = StringUtils::getWrapper($this->encoding); - } - - /** - * Set feed encoding - * - * @param string $enc - * @return Feed - */ - public function setEncoding($enc) - { - $this->stringWrapper = StringUtils::getWrapper($enc); - $this->encoding = $enc; - return $this; - } - - /** - * Get feed encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set a block value of "yes" or "no". You may also set an empty string. - * - * @param string - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesBlock($value) - { - if (!ctype_alpha($value) && strlen($value) > 0) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "block" may only' - . ' contain alphabetic characters'); - } - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "block" may only' - . ' contain a maximum of 255 characters'); - } - $this->data['block'] = $value; - return $this; - } - - /** - * Add feed authors - * - * @param array $values - * @return Feed - */ - public function addItunesAuthors(array $values) - { - foreach ($values as $value) { - $this->addItunesAuthor($value); - } - return $this; - } - - /** - * Add feed author - * - * @param string $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function addItunesAuthor($value) - { - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "author" may only' - . ' contain a maximum of 255 characters each'); - } - if (!isset($this->data['authors'])) { - $this->data['authors'] = array(); - } - $this->data['authors'][] = $value; - return $this; - } - - /** - * Set feed categories - * - * @param array $values - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesCategories(array $values) - { - if (!isset($this->data['categories'])) { - $this->data['categories'] = array(); - } - foreach ($values as $key => $value) { - if (!is_array($value)) { - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "category" may only' - . ' contain a maximum of 255 characters each'); - } - $this->data['categories'][] = $value; - } else { - if ($this->stringWrapper->strlen($key) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "category" may only' - . ' contain a maximum of 255 characters each'); - } - $this->data['categories'][$key] = array(); - foreach ($value as $val) { - if ($this->stringWrapper->strlen($val) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "category" may only' - . ' contain a maximum of 255 characters each'); - } - $this->data['categories'][$key][] = $val; - } - } - } - return $this; - } - - /** - * Set feed image (icon) - * - * @param string $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesImage($value) - { - if (!Uri::factory($value)->isValid()) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "image" may only' - . ' be a valid URI/IRI'); - } - if (!in_array(substr($value, -3), array('jpg', 'png'))) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "image" may only' - . ' use file extension "jpg" or "png" which must be the last three' - . ' characters of the URI (i.e. no query string or fragment)'); - } - $this->data['image'] = $value; - return $this; - } - - /** - * Set feed cumulative duration - * - * @param string $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesDuration($value) - { - $value = (string) $value; - if (!ctype_digit($value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}$/", $value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/", $value) - ) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "duration" may only' - . ' be of a specified [[HH:]MM:]SS format'); - } - $this->data['duration'] = $value; - return $this; - } - - /** - * Set "explicit" flag - * - * @param bool $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesExplicit($value) - { - if (!in_array($value, array('yes', 'no', 'clean'))) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "explicit" may only' - . ' be one of "yes", "no" or "clean"'); - } - $this->data['explicit'] = $value; - return $this; - } - - /** - * Set feed keywords - * - * @param array $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesKeywords(array $value) - { - if (count($value) > 12) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "keywords" may only' - . ' contain a maximum of 12 terms'); - } - $concat = implode(',', $value); - if ($this->stringWrapper->strlen($concat) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "keywords" may only' - . ' have a concatenated length of 255 chars where terms are delimited' - . ' by a comma'); - } - $this->data['keywords'] = $value; - return $this; - } - - /** - * Set new feed URL - * - * @param string $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesNewFeedUrl($value) - { - if (!Uri::factory($value)->isValid()) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "newFeedUrl" may only' - . ' be a valid URI/IRI'); - } - $this->data['newFeedUrl'] = $value; - return $this; - } - - /** - * Add feed owners - * - * @param array $values - * @return Feed - */ - public function addItunesOwners(array $values) - { - foreach ($values as $value) { - $this->addItunesOwner($value); - } - return $this; - } - - /** - * Add feed owner - * - * @param array $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function addItunesOwner(array $value) - { - if (!isset($value['name']) || !isset($value['email'])) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "owner" must' - . ' be an array containing keys "name" and "email"'); - } - if ($this->stringWrapper->strlen($value['name']) > 255 - || $this->stringWrapper->strlen($value['email']) > 255 - ) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: any "owner" may only' - . ' contain a maximum of 255 characters each for "name" and "email"'); - } - if (!isset($this->data['owners'])) { - $this->data['owners'] = array(); - } - $this->data['owners'][] = $value; - return $this; - } - - /** - * Set feed subtitle - * - * @param string $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesSubtitle($value) - { - if ($this->stringWrapper->strlen($value) > 255) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "subtitle" may only' - . ' contain a maximum of 255 characters'); - } - $this->data['subtitle'] = $value; - return $this; - } - - /** - * Set feed summary - * - * @param string $value - * @return Feed - * @throws Writer\Exception\InvalidArgumentException - */ - public function setItunesSummary($value) - { - if ($this->stringWrapper->strlen($value) > 4000) { - throw new Writer\Exception\InvalidArgumentException('invalid parameter: "summary" may only' - . ' contain a maximum of 4000 characters'); - } - $this->data['summary'] = $value; - return $this; - } - - /** - * Overloading: proxy to internal setters - * - * @param string $method - * @param array $params - * @return mixed - * @throws Writer\Exception\BadMethodCallException - */ - public function __call($method, array $params) - { - $point = lcfirst(substr($method, 9)); - if (!method_exists($this, 'setItunes' . ucfirst($point)) - && !method_exists($this, 'addItunes' . ucfirst($point)) - ) { - throw new Writer\Exception\BadMethodCallException( - 'invalid method: ' . $method - ); - } - if (!array_key_exists($point, $this->data) || empty($this->data[$point])) { - return null; - } - return $this->data[$point]; - } -} diff --git a/library/Zend/Feed/Writer/Extension/ITunes/Renderer/Entry.php b/library/Zend/Feed/Writer/Extension/ITunes/Renderer/Entry.php deleted file mode 100755 index bc57d1daa..000000000 --- a/library/Zend/Feed/Writer/Extension/ITunes/Renderer/Entry.php +++ /dev/null @@ -1,200 +0,0 @@ -_setAuthors($this->dom, $this->base); - $this->_setBlock($this->dom, $this->base); - $this->_setDuration($this->dom, $this->base); - $this->_setExplicit($this->dom, $this->base); - $this->_setKeywords($this->dom, $this->base); - $this->_setSubtitle($this->dom, $this->base); - $this->_setSummary($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append namespaces to entry root - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:itunes', - 'http://www.itunes.com/dtds/podcast-1.0.dtd'); - } - - /** - * Set entry authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->getDataContainer()->getItunesAuthors(); - if (!$authors || empty($authors)) { - return; - } - foreach ($authors as $author) { - $el = $dom->createElement('itunes:author'); - $text = $dom->createTextNode($author); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - } - - /** - * Set itunes block - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBlock(DOMDocument $dom, DOMElement $root) - { - $block = $this->getDataContainer()->getItunesBlock(); - if ($block === null) { - return; - } - $el = $dom->createElement('itunes:block'); - $text = $dom->createTextNode($block); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set entry duration - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDuration(DOMDocument $dom, DOMElement $root) - { - $duration = $this->getDataContainer()->getItunesDuration(); - if (!$duration) { - return; - } - $el = $dom->createElement('itunes:duration'); - $text = $dom->createTextNode($duration); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set explicit flag - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setExplicit(DOMDocument $dom, DOMElement $root) - { - $explicit = $this->getDataContainer()->getItunesExplicit(); - if ($explicit === null) { - return; - } - $el = $dom->createElement('itunes:explicit'); - $text = $dom->createTextNode($explicit); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set entry keywords - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setKeywords(DOMDocument $dom, DOMElement $root) - { - $keywords = $this->getDataContainer()->getItunesKeywords(); - if (!$keywords || empty($keywords)) { - return; - } - $el = $dom->createElement('itunes:keywords'); - $text = $dom->createTextNode(implode(',', $keywords)); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set entry subtitle - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setSubtitle(DOMDocument $dom, DOMElement $root) - { - $subtitle = $this->getDataContainer()->getItunesSubtitle(); - if (!$subtitle) { - return; - } - $el = $dom->createElement('itunes:subtitle'); - $text = $dom->createTextNode($subtitle); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set entry summary - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setSummary(DOMDocument $dom, DOMElement $root) - { - $summary = $this->getDataContainer()->getItunesSummary(); - if (!$summary) { - return; - } - $el = $dom->createElement('itunes:summary'); - $text = $dom->createTextNode($summary); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/ITunes/Renderer/Feed.php b/library/Zend/Feed/Writer/Extension/ITunes/Renderer/Feed.php deleted file mode 100755 index e6113a22f..000000000 --- a/library/Zend/Feed/Writer/Extension/ITunes/Renderer/Feed.php +++ /dev/null @@ -1,303 +0,0 @@ -_setAuthors($this->dom, $this->base); - $this->_setBlock($this->dom, $this->base); - $this->_setCategories($this->dom, $this->base); - $this->_setImage($this->dom, $this->base); - $this->_setDuration($this->dom, $this->base); - $this->_setExplicit($this->dom, $this->base); - $this->_setKeywords($this->dom, $this->base); - $this->_setNewFeedUrl($this->dom, $this->base); - $this->_setOwners($this->dom, $this->base); - $this->_setSubtitle($this->dom, $this->base); - $this->_setSummary($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append feed namespaces - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:itunes', - 'http://www.itunes.com/dtds/podcast-1.0.dtd'); - } - - /** - * Set feed authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->getDataContainer()->getItunesAuthors(); - if (!$authors || empty($authors)) { - return; - } - foreach ($authors as $author) { - $el = $dom->createElement('itunes:author'); - $text = $dom->createTextNode($author); - $el->appendChild($text); - $root->appendChild($el); - } - $this->called = true; - } - - /** - * Set feed itunes block - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBlock(DOMDocument $dom, DOMElement $root) - { - $block = $this->getDataContainer()->getItunesBlock(); - if ($block === null) { - return; - } - $el = $dom->createElement('itunes:block'); - $text = $dom->createTextNode($block); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set feed categories - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCategories(DOMDocument $dom, DOMElement $root) - { - $cats = $this->getDataContainer()->getItunesCategories(); - if (!$cats || empty($cats)) { - return; - } - foreach ($cats as $key => $cat) { - if (!is_array($cat)) { - $el = $dom->createElement('itunes:category'); - $el->setAttribute('text', $cat); - $root->appendChild($el); - } else { - $el = $dom->createElement('itunes:category'); - $el->setAttribute('text', $key); - $root->appendChild($el); - foreach ($cat as $subcat) { - $el2 = $dom->createElement('itunes:category'); - $el2->setAttribute('text', $subcat); - $el->appendChild($el2); - } - } - } - $this->called = true; - } - - /** - * Set feed image (icon) - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setImage(DOMDocument $dom, DOMElement $root) - { - $image = $this->getDataContainer()->getItunesImage(); - if (!$image) { - return; - } - $el = $dom->createElement('itunes:image'); - $el->setAttribute('href', $image); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set feed cumulative duration - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDuration(DOMDocument $dom, DOMElement $root) - { - $duration = $this->getDataContainer()->getItunesDuration(); - if (!$duration) { - return; - } - $el = $dom->createElement('itunes:duration'); - $text = $dom->createTextNode($duration); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set explicit flag - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setExplicit(DOMDocument $dom, DOMElement $root) - { - $explicit = $this->getDataContainer()->getItunesExplicit(); - if ($explicit === null) { - return; - } - $el = $dom->createElement('itunes:explicit'); - $text = $dom->createTextNode($explicit); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set feed keywords - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setKeywords(DOMDocument $dom, DOMElement $root) - { - $keywords = $this->getDataContainer()->getItunesKeywords(); - if (!$keywords || empty($keywords)) { - return; - } - $el = $dom->createElement('itunes:keywords'); - $text = $dom->createTextNode(implode(',', $keywords)); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set feed's new URL - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setNewFeedUrl(DOMDocument $dom, DOMElement $root) - { - $url = $this->getDataContainer()->getItunesNewFeedUrl(); - if (!$url) { - return; - } - $el = $dom->createElement('itunes:new-feed-url'); - $text = $dom->createTextNode($url); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set feed owners - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setOwners(DOMDocument $dom, DOMElement $root) - { - $owners = $this->getDataContainer()->getItunesOwners(); - if (!$owners || empty($owners)) { - return; - } - foreach ($owners as $owner) { - $el = $dom->createElement('itunes:owner'); - $name = $dom->createElement('itunes:name'); - $text = $dom->createTextNode($owner['name']); - $name->appendChild($text); - $email = $dom->createElement('itunes:email'); - $text = $dom->createTextNode($owner['email']); - $email->appendChild($text); - $root->appendChild($el); - $el->appendChild($name); - $el->appendChild($email); - } - $this->called = true; - } - - /** - * Set feed subtitle - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setSubtitle(DOMDocument $dom, DOMElement $root) - { - $subtitle = $this->getDataContainer()->getItunesSubtitle(); - if (!$subtitle) { - return; - } - $el = $dom->createElement('itunes:subtitle'); - $text = $dom->createTextNode($subtitle); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } - - /** - * Set feed summary - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setSummary(DOMDocument $dom, DOMElement $root) - { - $summary = $this->getDataContainer()->getItunesSummary(); - if (!$summary) { - return; - } - $el = $dom->createElement('itunes:summary'); - $text = $dom->createTextNode($summary); - $el->appendChild($text); - $root->appendChild($el); - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/RendererInterface.php b/library/Zend/Feed/Writer/Extension/RendererInterface.php deleted file mode 100755 index e72346c20..000000000 --- a/library/Zend/Feed/Writer/Extension/RendererInterface.php +++ /dev/null @@ -1,49 +0,0 @@ -getType()) == 'atom') { - return; // RSS 2.0 only - } - $this->_setCommentCount($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append entry namespaces - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:slash', - 'http://purl.org/rss/1.0/modules/slash/'); - } - - /** - * Set entry comment count - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCommentCount(DOMDocument $dom, DOMElement $root) - { - $count = $this->getDataContainer()->getCommentCount(); - if (!$count) { - $count = 0; - } - $tcount = $this->dom->createElement('slash:comments'); - $tcount->nodeValue = $count; - $root->appendChild($tcount); - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/Threading/Renderer/Entry.php b/library/Zend/Feed/Writer/Extension/Threading/Renderer/Entry.php deleted file mode 100755 index a0ea739d8..000000000 --- a/library/Zend/Feed/Writer/Extension/Threading/Renderer/Entry.php +++ /dev/null @@ -1,128 +0,0 @@ -getType()) == 'rss') { - return; // Atom 1.0 only - } - $this->_setCommentLink($this->dom, $this->base); - $this->_setCommentFeedLinks($this->dom, $this->base); - $this->_setCommentCount($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append entry namespaces - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:thr', - 'http://purl.org/syndication/thread/1.0'); - } - - /** - * Set comment link - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCommentLink(DOMDocument $dom, DOMElement $root) - { - $link = $this->getDataContainer()->getCommentLink(); - if (!$link) { - return; - } - $clink = $this->dom->createElement('link'); - $clink->setAttribute('rel', 'replies'); - $clink->setAttribute('type', 'text/html'); - $clink->setAttribute('href', $link); - $count = $this->getDataContainer()->getCommentCount(); - if ($count !== null) { - $clink->setAttribute('thr:count', $count); - } - $root->appendChild($clink); - $this->called = true; - } - - /** - * Set comment feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCommentFeedLinks(DOMDocument $dom, DOMElement $root) - { - $links = $this->getDataContainer()->getCommentFeedLinks(); - if (!$links || empty($links)) { - return; - } - foreach ($links as $link) { - $flink = $this->dom->createElement('link'); - $flink->setAttribute('rel', 'replies'); - $flink->setAttribute('type', 'application/' . $link['type'] . '+xml'); - $flink->setAttribute('href', $link['uri']); - $count = $this->getDataContainer()->getCommentCount(); - if ($count !== null) { - $flink->setAttribute('thr:count', $count); - } - $root->appendChild($flink); - $this->called = true; - } - } - - /** - * Set entry comment count - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCommentCount(DOMDocument $dom, DOMElement $root) - { - $count = $this->getDataContainer()->getCommentCount(); - if ($count === null) { - return; - } - $tcount = $this->dom->createElement('thr:total'); - $tcount->nodeValue = $count; - $root->appendChild($tcount); - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/Extension/WellFormedWeb/Renderer/Entry.php b/library/Zend/Feed/Writer/Extension/WellFormedWeb/Renderer/Entry.php deleted file mode 100755 index d661360a1..000000000 --- a/library/Zend/Feed/Writer/Extension/WellFormedWeb/Renderer/Entry.php +++ /dev/null @@ -1,79 +0,0 @@ -getType()) == 'atom') { - return; // RSS 2.0 only - } - $this->_setCommentFeedLinks($this->dom, $this->base); - if ($this->called) { - $this->_appendNamespaces(); - } - } - - /** - * Append entry namespaces - * - * @return void - */ - protected function _appendNamespaces() - { - $this->getRootElement()->setAttribute('xmlns:wfw', - 'http://wellformedweb.org/CommentAPI/'); - } - - /** - * Set entry comment feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCommentFeedLinks(DOMDocument $dom, DOMElement $root) - { - $links = $this->getDataContainer()->getCommentFeedLinks(); - if (!$links || empty($links)) { - return; - } - foreach ($links as $link) { - if ($link['type'] == 'rss') { - $flink = $this->dom->createElement('wfw:commentRss'); - $text = $dom->createTextNode($link['uri']); - $flink->appendChild($text); - $root->appendChild($flink); - } - } - $this->called = true; - } -} diff --git a/library/Zend/Feed/Writer/ExtensionManager.php b/library/Zend/Feed/Writer/ExtensionManager.php deleted file mode 100755 index 77d49a0dc..000000000 --- a/library/Zend/Feed/Writer/ExtensionManager.php +++ /dev/null @@ -1,80 +0,0 @@ -pluginManager = $pluginManager; - } - - /** - * Method overloading - * - * Proxy to composed ExtensionPluginManager instance. - * - * @param string $method - * @param array $args - * @return mixed - * @throws Exception\BadMethodCallException - */ - public function __call($method, $args) - { - if (!method_exists($this->pluginManager, $method)) { - throw new Exception\BadMethodCallException(sprintf( - 'Method by name of %s does not exist in %s', - $method, - __CLASS__ - )); - } - return call_user_func_array(array($this->pluginManager, $method), $args); - } - - /** - * Get the named extension - * - * @param string $name - * @return Extension\AbstractRenderer - */ - public function get($name) - { - return $this->pluginManager->get($name); - } - - /** - * Do we have the named extension? - * - * @param string $name - * @return bool - */ - public function has($name) - { - return $this->pluginManager->has($name); - } -} diff --git a/library/Zend/Feed/Writer/ExtensionManagerInterface.php b/library/Zend/Feed/Writer/ExtensionManagerInterface.php deleted file mode 100755 index 0f7e023fe..000000000 --- a/library/Zend/Feed/Writer/ExtensionManagerInterface.php +++ /dev/null @@ -1,29 +0,0 @@ - 'Zend\Feed\Writer\Extension\Atom\Renderer\Feed', - 'contentrendererentry' => 'Zend\Feed\Writer\Extension\Content\Renderer\Entry', - 'dublincorerendererentry' => 'Zend\Feed\Writer\Extension\DublinCore\Renderer\Entry', - 'dublincorerendererfeed' => 'Zend\Feed\Writer\Extension\DublinCore\Renderer\Feed', - 'itunesentry' => 'Zend\Feed\Writer\Extension\ITunes\Entry', - 'itunesfeed' => 'Zend\Feed\Writer\Extension\ITunes\Feed', - 'itunesrendererentry' => 'Zend\Feed\Writer\Extension\ITunes\Renderer\Entry', - 'itunesrendererfeed' => 'Zend\Feed\Writer\Extension\ITunes\Renderer\Feed', - 'slashrendererentry' => 'Zend\Feed\Writer\Extension\Slash\Renderer\Entry', - 'threadingrendererentry' => 'Zend\Feed\Writer\Extension\Threading\Renderer\Entry', - 'wellformedwebrendererentry' => 'Zend\Feed\Writer\Extension\WellFormedWeb\Renderer\Entry', - ); - - /** - * Do not share instances - * - * @var bool - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the extension loaded is of a valid type. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Extension\AbstractRenderer) { - // we're okay - return; - } - - if ('Feed' == substr(get_class($plugin), -4)) { - // we're okay - return; - } - - if ('Entry' == substr(get_class($plugin), -5)) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Extension\RendererInterface ' - . 'or the classname must end in "Feed" or "Entry"', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Feed/Writer/Feed.php b/library/Zend/Feed/Writer/Feed.php deleted file mode 100755 index 36b2b3ba9..000000000 --- a/library/Zend/Feed/Writer/Feed.php +++ /dev/null @@ -1,239 +0,0 @@ -getEncoding()) { - $entry->setEncoding($this->getEncoding()); - } - $entry->setType($this->getType()); - return $entry; - } - - /** - * Appends a Zend\Feed\Writer\Deleted object representing a new entry tombstone - * to the feed data container's internal group of entries. - * - * @param Deleted $deleted - * @return void - */ - public function addTombstone(Deleted $deleted) - { - $this->entries[] = $deleted; - } - - /** - * Creates a new Zend\Feed\Writer\Deleted data container for use. This is NOT - * added to the current feed automatically, but is necessary to create a - * container with some initial values preset based on the current feed data. - * - * @return Deleted - */ - public function createTombstone() - { - $deleted = new Deleted; - if ($this->getEncoding()) { - $deleted->setEncoding($this->getEncoding()); - } - $deleted->setType($this->getType()); - return $deleted; - } - - /** - * Appends a Zend\Feed\Writer\Entry object representing a new entry/item - * the feed data container's internal group of entries. - * - * @param Entry $entry - * @return Feed - */ - public function addEntry(Entry $entry) - { - $this->entries[] = $entry; - return $this; - } - - /** - * Removes a specific indexed entry from the internal queue. Entries must be - * added to a feed container in order to be indexed. - * - * @param int $index - * @throws Exception\InvalidArgumentException - * @return Feed - */ - public function removeEntry($index) - { - if (!isset($this->entries[$index])) { - throw new Exception\InvalidArgumentException('Undefined index: ' . $index . '. Entry does not exist.'); - } - unset($this->entries[$index]); - - return $this; - } - - /** - * Retrieve a specific indexed entry from the internal queue. Entries must be - * added to a feed container in order to be indexed. - * - * @param int $index - * @throws Exception\InvalidArgumentException - */ - public function getEntry($index = 0) - { - if (isset($this->entries[$index])) { - return $this->entries[$index]; - } - throw new Exception\InvalidArgumentException('Undefined index: ' . $index . '. Entry does not exist.'); - } - - /** - * Orders all indexed entries by date, thus offering date ordered readable - * content where a parser (or Homo Sapien) ignores the generic rule that - * XML element order is irrelevant and has no intrinsic meaning. - * - * Using this method will alter the original indexation. - * - * @return Feed - */ - public function orderByDate() - { - /** - * Could do with some improvement for performance perhaps - */ - $timestamp = time(); - $entries = array(); - foreach ($this->entries as $entry) { - if ($entry->getDateModified()) { - $timestamp = (int) $entry->getDateModified()->getTimestamp(); - } elseif ($entry->getDateCreated()) { - $timestamp = (int) $entry->getDateCreated()->getTimestamp(); - } - $entries[$timestamp] = $entry; - } - krsort($entries, SORT_NUMERIC); - $this->entries = array_values($entries); - - return $this; - } - - /** - * Get the number of feed entries. - * Required by the Iterator interface. - * - * @return int - */ - public function count() - { - return count($this->entries); - } - - /** - * Return the current entry - * - * @return Entry - */ - public function current() - { - return $this->entries[$this->key()]; - } - - /** - * Return the current feed key - * - * @return mixed - */ - public function key() - { - return $this->entriesKey; - } - - /** - * Move the feed pointer forward - * - * @return void - */ - public function next() - { - ++$this->entriesKey; - } - - /** - * Reset the pointer in the feed object - * - * @return void - */ - public function rewind() - { - $this->entriesKey = 0; - } - - /** - * Check to see if the iterator is still valid - * - * @return bool - */ - public function valid() - { - return 0 <= $this->entriesKey && $this->entriesKey < $this->count(); - } - - /** - * Attempt to build and return the feed resulting from the data set - * - * @param string $type The feed type "rss" or "atom" to export as - * @param bool $ignoreExceptions - * @throws Exception\InvalidArgumentException - * @return string - */ - public function export($type, $ignoreExceptions = false) - { - $this->setType(strtolower($type)); - $type = ucfirst($this->getType()); - if ($type !== 'Rss' && $type !== 'Atom') { - throw new Exception\InvalidArgumentException('Invalid feed type specified: ' . $type . '.' - . ' Should be one of "rss" or "atom".'); - } - $renderClass = 'Zend\\Feed\\Writer\\Renderer\\Feed\\' . $type; - $renderer = new $renderClass($this); - if ($ignoreExceptions) { - $renderer->ignoreExceptions(); - } - return $renderer->render()->saveXml(); - } -} diff --git a/library/Zend/Feed/Writer/FeedFactory.php b/library/Zend/Feed/Writer/FeedFactory.php deleted file mode 100755 index 15e7a3468..000000000 --- a/library/Zend/Feed/Writer/FeedFactory.php +++ /dev/null @@ -1,127 +0,0 @@ - $value) { - // Setters - $key = static::convertKey($key); - $method = 'set' . $key; - if (method_exists($feed, $method)) { - switch ($method) { - case 'setfeedlink': - if (!is_array($value)) { - // Need an array - break; - } - if (!array_key_exists('link', $value) || !array_key_exists('type', $value)) { - // Need both keys to set this correctly - break; - } - $feed->setFeedLink($value['link'], $value['type']); - break; - default: - $feed->$method($value); - break; - } - continue; - } - - // Entries - if ('entries' == $key) { - static::createEntries($value, $feed); - continue; - } - } - - return $feed; - } - - /** - * Normalize a key - * - * @param string $key - * @return string - */ - protected static function convertKey($key) - { - $key = str_replace('_', '', strtolower($key)); - return $key; - } - - /** - * Create and attach entries to a feed - * - * @param array|Traversable $entries - * @param Feed $feed - * @throws Exception\InvalidArgumentException - * @return void - */ - protected static function createEntries($entries, Feed $feed) - { - if (!is_array($entries) && !$entries instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s::factory expects the "entries" value to be an array or Traversable; received "%s"', - get_called_class(), - (is_object($entries) ? get_class($entries) : gettype($entries)) - )); - } - - foreach ($entries as $data) { - if (!is_array($data) && !$data instanceof Traversable && !$data instanceof Entry) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, Traversable, or Zend\Feed\Writer\Entry argument; received "%s"', - __METHOD__, - (is_object($data) ? get_class($data) : gettype($data)) - )); - } - - // Use case 1: Entry item - if ($data instanceof Entry) { - $feed->addEntry($data); - continue; - } - - // Use case 2: iterate item and populate entry - $entry = $feed->createEntry(); - foreach ($data as $key => $value) { - $key = static::convertKey($key); - $method = 'set' . $key; - if (!method_exists($entry, $method)) { - continue; - } - $entry->$method($value); - } - $feed->addEntry($entry); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/AbstractRenderer.php b/library/Zend/Feed/Writer/Renderer/AbstractRenderer.php deleted file mode 100755 index e10450198..000000000 --- a/library/Zend/Feed/Writer/Renderer/AbstractRenderer.php +++ /dev/null @@ -1,233 +0,0 @@ -container = $container; - $this->setType($container->getType()); - $this->_loadExtensions(); - } - - /** - * Save XML to string - * - * @return string - */ - public function saveXml() - { - return $this->getDomDocument()->saveXml(); - } - - /** - * Get DOM document - * - * @return DOMDocument - */ - public function getDomDocument() - { - return $this->dom; - } - - /** - * Get document element from DOM - * - * @return DOMElement - */ - public function getElement() - { - return $this->getDomDocument()->documentElement; - } - - /** - * Get data container of items being rendered - * - * @return Writer\AbstractFeed - */ - public function getDataContainer() - { - return $this->container; - } - - /** - * Set feed encoding - * - * @param string $enc - * @return AbstractRenderer - */ - public function setEncoding($enc) - { - $this->encoding = $enc; - return $this; - } - - /** - * Get feed encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Indicate whether or not to ignore exceptions - * - * @param bool $bool - * @return AbstractRenderer - * @throws Writer\Exception\InvalidArgumentException - */ - public function ignoreExceptions($bool = true) - { - if (!is_bool($bool)) { - throw new Writer\Exception\InvalidArgumentException('Invalid parameter: $bool. Should be TRUE or FALSE (defaults to TRUE if null)'); - } - $this->ignoreExceptions = $bool; - return $this; - } - - /** - * Get exception list - * - * @return array - */ - public function getExceptions() - { - return $this->exceptions; - } - - /** - * Set the current feed type being exported to "rss" or "atom". This allows - * other objects to gracefully choose whether to execute or not, depending - * on their appropriateness for the current type, e.g. renderers. - * - * @param string $type - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * Retrieve the current or last feed type exported. - * - * @return string Value will be "rss" or "atom" - */ - public function getType() - { - return $this->type; - } - - /** - * Sets the absolute root element for the XML feed being generated. This - * helps simplify the appending of namespace declarations, but also ensures - * namespaces are added to the root element - not scattered across the entire - * XML file - may assist namespace unsafe parsers and looks pretty ;). - * - * @param DOMElement $root - */ - public function setRootElement(DOMElement $root) - { - $this->rootElement = $root; - } - - /** - * Retrieve the absolute root element for the XML feed being generated. - * - * @return DOMElement - */ - public function getRootElement() - { - return $this->rootElement; - } - - /** - * Load extensions from Zend\Feed\Writer\Writer - * - * @return void - */ - protected function _loadExtensions() - { - Writer\Writer::registerCoreExtensions(); - $manager = Writer\Writer::getExtensionManager(); - $all = Writer\Writer::getExtensions(); - if (stripos(get_class($this), 'entry')) { - $exts = $all['entryRenderer']; - } else { - $exts = $all['feedRenderer']; - } - foreach ($exts as $extension) { - $plugin = $manager->get($extension); - $plugin->setDataContainer($this->getDataContainer()); - $plugin->setEncoding($this->getEncoding()); - $this->extensions[$extension] = $plugin; - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Entry/Atom.php b/library/Zend/Feed/Writer/Renderer/Entry/Atom.php deleted file mode 100755 index 975aa7268..000000000 --- a/library/Zend/Feed/Writer/Renderer/Entry/Atom.php +++ /dev/null @@ -1,424 +0,0 @@ -dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $entry = $this->dom->createElementNS(Writer\Writer::NAMESPACE_ATOM_10, 'entry'); - $this->dom->appendChild($entry); - - $this->_setSource($this->dom, $entry); - $this->_setTitle($this->dom, $entry); - $this->_setDescription($this->dom, $entry); - $this->_setDateCreated($this->dom, $entry); - $this->_setDateModified($this->dom, $entry); - $this->_setLink($this->dom, $entry); - $this->_setId($this->dom, $entry); - $this->_setAuthors($this->dom, $entry); - $this->_setEnclosure($this->dom, $entry); - $this->_setContent($this->dom, $entry); - $this->_setCategories($this->dom, $entry); - - foreach ($this->extensions as $ext) { - $ext->setType($this->getType()); - $ext->setRootElement($this->getRootElement()); - $ext->setDOMDocument($this->getDOMDocument(), $entry); - $ext->render(); - } - - return $this; - } - - /** - * Set entry title - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setTitle(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getTitle()) { - $message = 'Atom 1.0 entry elements MUST contain exactly one' - . ' atom:title element but a title has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $title = $dom->createElement('title'); - $root->appendChild($title); - $title->setAttribute('type', 'html'); - $cdata = $dom->createCDATASection($this->getDataContainer()->getTitle()); - $title->appendChild($cdata); - } - - /** - * Set entry description - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDescription(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDescription()) { - return; // unless src content or base64 - } - $subtitle = $dom->createElement('summary'); - $root->appendChild($subtitle); - $subtitle->setAttribute('type', 'html'); - $cdata = $dom->createCDATASection( - $this->getDataContainer()->getDescription() - ); - $subtitle->appendChild($cdata); - } - - /** - * Set date entry was modified - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setDateModified(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateModified()) { - $message = 'Atom 1.0 entry elements MUST contain exactly one' - . ' atom:updated element but a modification date has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $updated = $dom->createElement('updated'); - $root->appendChild($updated); - $text = $dom->createTextNode( - $this->getDataContainer()->getDateModified()->format(DateTime::ISO8601) - ); - $updated->appendChild($text); - } - - /** - * Set date entry was created - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateCreated(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateCreated()) { - return; - } - $el = $dom->createElement('published'); - $root->appendChild($el); - $text = $dom->createTextNode( - $this->getDataContainer()->getDateCreated()->format(DateTime::ISO8601) - ); - $el->appendChild($text); - } - - /** - * Set entry authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->container->getAuthors(); - if ((!$authors || empty($authors))) { - /** - * This will actually trigger an Exception at the feed level if - * a feed level author is not set. - */ - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('author'); - $name = $this->dom->createElement('name'); - $author->appendChild($name); - $root->appendChild($author); - $text = $dom->createTextNode($data['name']); - $name->appendChild($text); - if (array_key_exists('email', $data)) { - $email = $this->dom->createElement('email'); - $author->appendChild($email); - $text = $dom->createTextNode($data['email']); - $email->appendChild($text); - } - if (array_key_exists('uri', $data)) { - $uri = $this->dom->createElement('uri'); - $author->appendChild($uri); - $text = $dom->createTextNode($data['uri']); - $uri->appendChild($text); - } - } - } - - /** - * Set entry enclosure - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setEnclosure(DOMDocument $dom, DOMElement $root) - { - $data = $this->container->getEnclosure(); - if ((!$data || empty($data))) { - return; - } - $enclosure = $this->dom->createElement('link'); - $enclosure->setAttribute('rel', 'enclosure'); - if (isset($data['type'])) { - $enclosure->setAttribute('type', $data['type']); - } - if (isset($data['length'])) { - $enclosure->setAttribute('length', $data['length']); - } - $enclosure->setAttribute('href', $data['uri']); - $root->appendChild($enclosure); - } - - protected function _setLink(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getLink()) { - return; - } - $link = $dom->createElement('link'); - $root->appendChild($link); - $link->setAttribute('rel', 'alternate'); - $link->setAttribute('type', 'text/html'); - $link->setAttribute('href', $this->getDataContainer()->getLink()); - } - - /** - * Set entry identifier - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setId(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getId() - && !$this->getDataContainer()->getLink()) { - $message = 'Atom 1.0 entry elements MUST contain exactly one ' - . 'atom:id element, or as an alternative, we can use the same ' - . 'value as atom:link however neither a suitable link nor an ' - . 'id have been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - if (!$this->getDataContainer()->getId()) { - $this->getDataContainer()->setId( - $this->getDataContainer()->getLink()); - } - if (!Uri::factory($this->getDataContainer()->getId())->isValid() - && !preg_match( - "#^urn:[a-zA-Z0-9][a-zA-Z0-9\-]{1,31}:([a-zA-Z0-9\(\)\+\,\.\:\=\@\;\$\_\!\*\-]|%[0-9a-fA-F]{2})*#", - $this->getDataContainer()->getId()) - && !$this->_validateTagUri($this->getDataContainer()->getId()) - ) { - throw new Writer\Exception\InvalidArgumentException('Atom 1.0 IDs must be a valid URI/IRI'); - } - $id = $dom->createElement('id'); - $root->appendChild($id); - $text = $dom->createTextNode($this->getDataContainer()->getId()); - $id->appendChild($text); - } - - /** - * Validate a URI using the tag scheme (RFC 4151) - * - * @param string $id - * @return bool - */ - protected function _validateTagUri($id) - { - if (preg_match('/^tag:(?P.*),(?P\d{4}-?\d{0,2}-?\d{0,2}):(?P.*)(.*:)*$/', $id, $matches)) { - $dvalid = false; - $date = $matches['date']; - $d6 = strtotime($date); - if ((strlen($date) == 4) && $date <= date('Y')) { - $dvalid = true; - } elseif ((strlen($date) == 7) && ($d6 < strtotime("now"))) { - $dvalid = true; - } elseif ((strlen($date) == 10) && ($d6 < strtotime("now"))) { - $dvalid = true; - } - $validator = new Validator\EmailAddress; - if ($validator->isValid($matches['name'])) { - $nvalid = true; - } else { - $nvalid = $validator->isValid('info@' . $matches['name']); - } - return $dvalid && $nvalid; - } - return false; - } - - /** - * Set entry content - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setContent(DOMDocument $dom, DOMElement $root) - { - $content = $this->getDataContainer()->getContent(); - if (!$content && !$this->getDataContainer()->getLink()) { - $message = 'Atom 1.0 entry elements MUST contain exactly one ' - . 'atom:content element, or as an alternative, at least one link ' - . 'with a rel attribute of "alternate" to indicate an alternate ' - . 'method to consume the content.'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - if (!$content) { - return; - } - $element = $dom->createElement('content'); - $element->setAttribute('type', 'xhtml'); - $xhtmlElement = $this->_loadXhtml($content); - $xhtml = $dom->importNode($xhtmlElement, true); - $element->appendChild($xhtml); - $root->appendChild($element); - } - - /** - * Load a HTML string and attempt to normalise to XML - */ - protected function _loadXhtml($content) - { - if (class_exists('tidy', false)) { - $tidy = new \tidy; - $config = array( - 'output-xhtml' => true, - 'show-body-only' => true, - 'quote-nbsp' => false - ); - $encoding = str_replace('-', '', $this->getEncoding()); - $tidy->parseString($content, $config, $encoding); - $tidy->cleanRepair(); - $xhtml = (string) $tidy; - } else { - $xhtml = $content; - } - $xhtml = preg_replace(array( - "/(<[\/]?)([a-zA-Z]+)/" - ), '$1xhtml:$2', $xhtml); - $dom = new DOMDocument('1.0', $this->getEncoding()); - $dom->loadXML('' - . $xhtml . ''); - return $dom->documentElement; - } - - /** - * Set entry categories - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCategories(DOMDocument $dom, DOMElement $root) - { - $categories = $this->getDataContainer()->getCategories(); - if (!$categories) { - return; - } - foreach ($categories as $cat) { - $category = $dom->createElement('category'); - $category->setAttribute('term', $cat['term']); - if (isset($cat['label'])) { - $category->setAttribute('label', $cat['label']); - } else { - $category->setAttribute('label', $cat['term']); - } - if (isset($cat['scheme'])) { - $category->setAttribute('scheme', $cat['scheme']); - } - $root->appendChild($category); - } - } - - /** - * Append Source element (Atom 1.0 Feed Metadata) - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setSource(DOMDocument $dom, DOMElement $root) - { - $source = $this->getDataContainer()->getSource(); - if (!$source) { - return; - } - $renderer = new Renderer\Feed\AtomSource($source); - $renderer->setType($this->getType()); - $element = $renderer->render()->getElement(); - $imported = $dom->importNode($element, true); - $root->appendChild($imported); - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Entry/Atom/Deleted.php b/library/Zend/Feed/Writer/Renderer/Entry/Atom/Deleted.php deleted file mode 100755 index 65ace00bd..000000000 --- a/library/Zend/Feed/Writer/Renderer/Entry/Atom/Deleted.php +++ /dev/null @@ -1,102 +0,0 @@ -dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $entry = $this->dom->createElement('at:deleted-entry'); - $this->dom->appendChild($entry); - - $entry->setAttribute('ref', $this->container->getReference()); - $entry->setAttribute('when', $this->container->getWhen()->format(DateTime::ISO8601)); - - $this->_setBy($this->dom, $entry); - $this->_setComment($this->dom, $entry); - - return $this; - } - - /** - * Set tombstone comment - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setComment(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getComment()) { - return; - } - $c = $dom->createElement('at:comment'); - $root->appendChild($c); - $c->setAttribute('type', 'html'); - $cdata = $dom->createCDATASection($this->getDataContainer()->getComment()); - $c->appendChild($cdata); - } - - /** - * Set entry authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBy(DOMDocument $dom, DOMElement $root) - { - $data = $this->container->getBy(); - if ((!$data || empty($data))) { - return; - } - $author = $this->dom->createElement('at:by'); - $name = $this->dom->createElement('name'); - $author->appendChild($name); - $root->appendChild($author); - $text = $dom->createTextNode($data['name']); - $name->appendChild($text); - if (array_key_exists('email', $data)) { - $email = $this->dom->createElement('email'); - $author->appendChild($email); - $text = $dom->createTextNode($data['email']); - $email->appendChild($text); - } - if (array_key_exists('uri', $data)) { - $uri = $this->dom->createElement('uri'); - $author->appendChild($uri); - $text = $dom->createTextNode($data['uri']); - $uri->appendChild($text); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Entry/AtomDeleted.php b/library/Zend/Feed/Writer/Renderer/Entry/AtomDeleted.php deleted file mode 100755 index 1ed4aa3d9..000000000 --- a/library/Zend/Feed/Writer/Renderer/Entry/AtomDeleted.php +++ /dev/null @@ -1,104 +0,0 @@ -dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $entry = $this->dom->createElement('at:deleted-entry'); - $this->dom->appendChild($entry); - - $entry->setAttribute('ref', $this->container->getReference()); - $entry->setAttribute('when', $this->container->getWhen()->format(DateTime::ISO8601)); - - $this->_setBy($this->dom, $entry); - $this->_setComment($this->dom, $entry); - - return $this; - } - - /** - * Set tombstone comment - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setComment(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getComment()) { - return; - } - $c = $dom->createElement('at:comment'); - $root->appendChild($c); - $c->setAttribute('type', 'html'); - $cdata = $dom->createCDATASection($this->getDataContainer()->getComment()); - $c->appendChild($cdata); - } - - /** - * Set entry authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBy(DOMDocument $dom, DOMElement $root) - { - $data = $this->container->getBy(); - if ((!$data || empty($data))) { - return; - } - $author = $this->dom->createElement('at:by'); - $name = $this->dom->createElement('name'); - $author->appendChild($name); - $root->appendChild($author); - $text = $dom->createTextNode($data['name']); - $name->appendChild($text); - if (array_key_exists('email', $data)) { - $email = $this->dom->createElement('email'); - $author->appendChild($email); - $text = $dom->createTextNode($data['email']); - $email->appendChild($text); - } - if (array_key_exists('uri', $data)) { - $uri = $this->dom->createElement('uri'); - $author->appendChild($uri); - $text = $dom->createTextNode($data['uri']); - $uri->appendChild($text); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Entry/Rss.php b/library/Zend/Feed/Writer/Renderer/Entry/Rss.php deleted file mode 100755 index 2338cdc21..000000000 --- a/library/Zend/Feed/Writer/Renderer/Entry/Rss.php +++ /dev/null @@ -1,329 +0,0 @@ -dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $this->dom->substituteEntities = false; - $entry = $this->dom->createElement('item'); - $this->dom->appendChild($entry); - - $this->_setTitle($this->dom, $entry); - $this->_setDescription($this->dom, $entry); - $this->_setDateCreated($this->dom, $entry); - $this->_setDateModified($this->dom, $entry); - $this->_setLink($this->dom, $entry); - $this->_setId($this->dom, $entry); - $this->_setAuthors($this->dom, $entry); - $this->_setEnclosure($this->dom, $entry); - $this->_setCommentLink($this->dom, $entry); - $this->_setCategories($this->dom, $entry); - foreach ($this->extensions as $ext) { - $ext->setType($this->getType()); - $ext->setRootElement($this->getRootElement()); - $ext->setDOMDocument($this->getDOMDocument(), $entry); - $ext->render(); - } - - return $this; - } - - /** - * Set entry title - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setTitle(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDescription() - && !$this->getDataContainer()->getTitle()) { - $message = 'RSS 2.0 entry elements SHOULD contain exactly one' - . ' title element but a title has not been set. In addition, there' - . ' is no description as required in the absence of a title.'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $title = $dom->createElement('title'); - $root->appendChild($title); - $text = $dom->createTextNode($this->getDataContainer()->getTitle()); - $title->appendChild($text); - } - - /** - * Set entry description - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setDescription(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDescription() - && !$this->getDataContainer()->getTitle()) { - $message = 'RSS 2.0 entry elements SHOULD contain exactly one' - . ' description element but a description has not been set. In' - . ' addition, there is no title element as required in the absence' - . ' of a description.'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - if (!$this->getDataContainer()->getDescription()) { - return; - } - $subtitle = $dom->createElement('description'); - $root->appendChild($subtitle); - $text = $dom->createCDATASection($this->getDataContainer()->getDescription()); - $subtitle->appendChild($text); - } - - /** - * Set date entry was last modified - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateModified(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateModified()) { - return; - } - - $updated = $dom->createElement('pubDate'); - $root->appendChild($updated); - $text = $dom->createTextNode( - $this->getDataContainer()->getDateModified()->format(DateTime::RSS) - ); - $updated->appendChild($text); - } - - /** - * Set date entry was created - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateCreated(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateCreated()) { - return; - } - if (!$this->getDataContainer()->getDateModified()) { - $this->getDataContainer()->setDateModified( - $this->getDataContainer()->getDateCreated() - ); - } - } - - /** - * Set entry authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->container->getAuthors(); - if ((!$authors || empty($authors))) { - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('author'); - $name = $data['name']; - if (array_key_exists('email', $data)) { - $name = $data['email'] . ' (' . $data['name'] . ')'; - } - $text = $dom->createTextNode($name); - $author->appendChild($text); - $root->appendChild($author); - } - } - - /** - * Set entry enclosure - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setEnclosure(DOMDocument $dom, DOMElement $root) - { - $data = $this->container->getEnclosure(); - if ((!$data || empty($data))) { - return; - } - if (!isset($data['type'])) { - $exception = new Writer\Exception\InvalidArgumentException('Enclosure "type" is not set'); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - if (!isset($data['length'])) { - $exception = new Writer\Exception\InvalidArgumentException('Enclosure "length" is not set'); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - if (isset($data['length']) && (int) $data['length'] <= 0) { - $exception = new Writer\Exception\InvalidArgumentException('Enclosure "length" must be an integer' - . ' indicating the content\'s length in bytes'); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $enclosure = $this->dom->createElement('enclosure'); - $enclosure->setAttribute('type', $data['type']); - $enclosure->setAttribute('length', $data['length']); - $enclosure->setAttribute('url', $data['uri']); - $root->appendChild($enclosure); - } - - /** - * Set link to entry - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setLink(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getLink()) { - return; - } - $link = $dom->createElement('link'); - $root->appendChild($link); - $text = $dom->createTextNode($this->getDataContainer()->getLink()); - $link->appendChild($text); - } - - /** - * Set entry identifier - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setId(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getId() - && !$this->getDataContainer()->getLink()) { - return; - } - - $id = $dom->createElement('guid'); - $root->appendChild($id); - if (!$this->getDataContainer()->getId()) { - $this->getDataContainer()->setId( - $this->getDataContainer()->getLink()); - } - $text = $dom->createTextNode($this->getDataContainer()->getId()); - $id->appendChild($text); - if (!Uri::factory($this->getDataContainer()->getId())->isValid()) { - $id->setAttribute('isPermaLink', 'false'); - } - } - - /** - * Set link to entry comments - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCommentLink(DOMDocument $dom, DOMElement $root) - { - $link = $this->getDataContainer()->getCommentLink(); - if (!$link) { - return; - } - $clink = $this->dom->createElement('comments'); - $text = $dom->createTextNode($link); - $clink->appendChild($text); - $root->appendChild($clink); - } - - /** - * Set entry categories - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCategories(DOMDocument $dom, DOMElement $root) - { - $categories = $this->getDataContainer()->getCategories(); - if (!$categories) { - return; - } - foreach ($categories as $cat) { - $category = $dom->createElement('category'); - if (isset($cat['scheme'])) { - $category->setAttribute('domain', $cat['scheme']); - } - $text = $dom->createCDATASection($cat['term']); - $category->appendChild($text); - $root->appendChild($category); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Feed/AbstractAtom.php b/library/Zend/Feed/Writer/Renderer/Feed/AbstractAtom.php deleted file mode 100755 index e7ad9f56b..000000000 --- a/library/Zend/Feed/Writer/Renderer/Feed/AbstractAtom.php +++ /dev/null @@ -1,403 +0,0 @@ -getDataContainer()->getLanguage()) { - $root->setAttribute('xml:lang', $this->getDataContainer() - ->getLanguage()); - } - } - - /** - * Set feed title - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setTitle(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getTitle()) { - $message = 'Atom 1.0 feed elements MUST contain exactly one' - . ' atom:title element but a title has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $title = $dom->createElement('title'); - $root->appendChild($title); - $title->setAttribute('type', 'text'); - $text = $dom->createTextNode($this->getDataContainer()->getTitle()); - $title->appendChild($text); - } - - /** - * Set feed description - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDescription(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDescription()) { - return; - } - $subtitle = $dom->createElement('subtitle'); - $root->appendChild($subtitle); - $subtitle->setAttribute('type', 'text'); - $text = $dom->createTextNode($this->getDataContainer()->getDescription()); - $subtitle->appendChild($text); - } - - /** - * Set date feed was last modified - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setDateModified(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateModified()) { - $message = 'Atom 1.0 feed elements MUST contain exactly one' - . ' atom:updated element but a modification date has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $updated = $dom->createElement('updated'); - $root->appendChild($updated); - $text = $dom->createTextNode( - $this->getDataContainer()->getDateModified()->format(DateTime::ISO8601) - ); - $updated->appendChild($text); - } - - /** - * Set feed generator string - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setGenerator(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getGenerator()) { - $this->getDataContainer()->setGenerator('Zend_Feed_Writer', - Version::VERSION, 'http://framework.zend.com'); - } - - $gdata = $this->getDataContainer()->getGenerator(); - $generator = $dom->createElement('generator'); - $root->appendChild($generator); - $text = $dom->createTextNode($gdata['name']); - $generator->appendChild($text); - if (array_key_exists('uri', $gdata)) { - $generator->setAttribute('uri', $gdata['uri']); - } - if (array_key_exists('version', $gdata)) { - $generator->setAttribute('version', $gdata['version']); - } - } - - /** - * Set link to feed - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setLink(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getLink()) { - return; - } - $link = $dom->createElement('link'); - $root->appendChild($link); - $link->setAttribute('rel', 'alternate'); - $link->setAttribute('type', 'text/html'); - $link->setAttribute('href', $this->getDataContainer()->getLink()); - } - - /** - * Set feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setFeedLinks(DOMDocument $dom, DOMElement $root) - { - $flinks = $this->getDataContainer()->getFeedLinks(); - if (!$flinks || !array_key_exists('atom', $flinks)) { - $message = 'Atom 1.0 feed elements SHOULD contain one atom:link ' - . 'element with a rel attribute value of "self". This is the ' - . 'preferred URI for retrieving Atom Feed Documents representing ' - . 'this Atom feed but a feed link has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - foreach ($flinks as $type => $href) { - $mime = 'application/' . strtolower($type) . '+xml'; - $flink = $dom->createElement('link'); - $root->appendChild($flink); - $flink->setAttribute('rel', 'self'); - $flink->setAttribute('type', $mime); - $flink->setAttribute('href', $href); - } - } - - /** - * Set feed authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->container->getAuthors(); - if (!$authors || empty($authors)) { - /** - * Technically we should defer an exception until we can check - * that all entries contain an author. If any entry is missing - * an author, then a missing feed author element is invalid - */ - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('author'); - $name = $this->dom->createElement('name'); - $author->appendChild($name); - $root->appendChild($author); - $text = $dom->createTextNode($data['name']); - $name->appendChild($text); - if (array_key_exists('email', $data)) { - $email = $this->dom->createElement('email'); - $author->appendChild($email); - $text = $dom->createTextNode($data['email']); - $email->appendChild($text); - } - if (array_key_exists('uri', $data)) { - $uri = $this->dom->createElement('uri'); - $author->appendChild($uri); - $text = $dom->createTextNode($data['uri']); - $uri->appendChild($text); - } - } - } - - /** - * Set feed identifier - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setId(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getId() - && !$this->getDataContainer()->getLink()) { - $message = 'Atom 1.0 feed elements MUST contain exactly one ' - . 'atom:id element, or as an alternative, we can use the same ' - . 'value as atom:link however neither a suitable link nor an ' - . 'id have been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - if (!$this->getDataContainer()->getId()) { - $this->getDataContainer()->setId( - $this->getDataContainer()->getLink()); - } - $id = $dom->createElement('id'); - $root->appendChild($id); - $text = $dom->createTextNode($this->getDataContainer()->getId()); - $id->appendChild($text); - } - - /** - * Set feed copyright - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCopyright(DOMDocument $dom, DOMElement $root) - { - $copyright = $this->getDataContainer()->getCopyright(); - if (!$copyright) { - return; - } - $copy = $dom->createElement('rights'); - $root->appendChild($copy); - $text = $dom->createTextNode($copyright); - $copy->appendChild($text); - } - - /** - * Set feed level logo (image) - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setImage(DOMDocument $dom, DOMElement $root) - { - $image = $this->getDataContainer()->getImage(); - if (!$image) { - return; - } - $img = $dom->createElement('logo'); - $root->appendChild($img); - $text = $dom->createTextNode($image['uri']); - $img->appendChild($text); - } - - /** - * Set date feed was created - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateCreated(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateCreated()) { - return; - } - if (!$this->getDataContainer()->getDateModified()) { - $this->getDataContainer()->setDateModified( - $this->getDataContainer()->getDateCreated() - ); - } - } - - /** - * Set base URL to feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBaseUrl(DOMDocument $dom, DOMElement $root) - { - $baseUrl = $this->getDataContainer()->getBaseUrl(); - if (!$baseUrl) { - return; - } - $root->setAttribute('xml:base', $baseUrl); - } - - /** - * Set hubs to which this feed pushes - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setHubs(DOMDocument $dom, DOMElement $root) - { - $hubs = $this->getDataContainer()->getHubs(); - if (!$hubs) { - return; - } - foreach ($hubs as $hubUrl) { - $hub = $dom->createElement('link'); - $hub->setAttribute('rel', 'hub'); - $hub->setAttribute('href', $hubUrl); - $root->appendChild($hub); - } - } - - /** - * Set feed categories - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCategories(DOMDocument $dom, DOMElement $root) - { - $categories = $this->getDataContainer()->getCategories(); - if (!$categories) { - return; - } - foreach ($categories as $cat) { - $category = $dom->createElement('category'); - $category->setAttribute('term', $cat['term']); - if (isset($cat['label'])) { - $category->setAttribute('label', $cat['label']); - } else { - $category->setAttribute('label', $cat['term']); - } - if (isset($cat['scheme'])) { - $category->setAttribute('scheme', $cat['scheme']); - } - $root->appendChild($category); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Atom.php b/library/Zend/Feed/Writer/Renderer/Feed/Atom.php deleted file mode 100755 index 87b6b94ac..000000000 --- a/library/Zend/Feed/Writer/Renderer/Feed/Atom.php +++ /dev/null @@ -1,96 +0,0 @@ -container->getEncoding()) { - $this->container->setEncoding('UTF-8'); - } - $this->dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $root = $this->dom->createElementNS( - Writer\Writer::NAMESPACE_ATOM_10, 'feed' - ); - $this->setRootElement($root); - $this->dom->appendChild($root); - $this->_setLanguage($this->dom, $root); - $this->_setBaseUrl($this->dom, $root); - $this->_setTitle($this->dom, $root); - $this->_setDescription($this->dom, $root); - $this->_setImage($this->dom, $root); - $this->_setDateCreated($this->dom, $root); - $this->_setDateModified($this->dom, $root); - $this->_setGenerator($this->dom, $root); - $this->_setLink($this->dom, $root); - $this->_setFeedLinks($this->dom, $root); - $this->_setId($this->dom, $root); - $this->_setAuthors($this->dom, $root); - $this->_setCopyright($this->dom, $root); - $this->_setCategories($this->dom, $root); - $this->_setHubs($this->dom, $root); - - foreach ($this->extensions as $ext) { - $ext->setType($this->getType()); - $ext->setRootElement($this->getRootElement()); - $ext->setDOMDocument($this->getDOMDocument(), $root); - $ext->render(); - } - - foreach ($this->container as $entry) { - if ($this->getDataContainer()->getEncoding()) { - $entry->setEncoding($this->getDataContainer()->getEncoding()); - } - if ($entry instanceof Writer\Entry) { - $renderer = new Renderer\Entry\Atom($entry); - } else { - if (!$this->dom->documentElement->hasAttribute('xmlns:at')) { - $this->dom->documentElement->setAttribute( - 'xmlns:at', 'http://purl.org/atompub/tombstones/1.0' - ); - } - $renderer = new Renderer\Entry\AtomDeleted($entry); - } - if ($this->ignoreExceptions === true) { - $renderer->ignoreExceptions(); - } - $renderer->setType($this->getType()); - $renderer->setRootElement($this->dom->documentElement); - $renderer->render(); - $element = $renderer->getElement(); - $imported = $this->dom->importNode($element, true); - $root->appendChild($imported); - } - return $this; - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Atom/AbstractAtom.php b/library/Zend/Feed/Writer/Renderer/Feed/Atom/AbstractAtom.php deleted file mode 100755 index 379cd5c9f..000000000 --- a/library/Zend/Feed/Writer/Renderer/Feed/Atom/AbstractAtom.php +++ /dev/null @@ -1,400 +0,0 @@ -getDataContainer()->getLanguage()) { - $root->setAttribute('xml:lang', $this->getDataContainer() - ->getLanguage()); - } - } - - /** - * Set feed title - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Feed\Exception\InvalidArgumentException - */ - protected function _setTitle(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getTitle()) { - $message = 'Atom 1.0 feed elements MUST contain exactly one' - . ' atom:title element but a title has not been set'; - $exception = new Feed\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $title = $dom->createElement('title'); - $root->appendChild($title); - $title->setAttribute('type', 'text'); - $text = $dom->createTextNode($this->getDataContainer()->getTitle()); - $title->appendChild($text); - } - - /** - * Set feed description - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDescription(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDescription()) { - return; - } - $subtitle = $dom->createElement('subtitle'); - $root->appendChild($subtitle); - $subtitle->setAttribute('type', 'text'); - $text = $dom->createTextNode($this->getDataContainer()->getDescription()); - $subtitle->appendChild($text); - } - - /** - * Set date feed was last modified - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Feed\Exception\InvalidArgumentException - */ - protected function _setDateModified(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateModified()) { - $message = 'Atom 1.0 feed elements MUST contain exactly one' - . ' atom:updated element but a modification date has not been set'; - $exception = new Feed\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $updated = $dom->createElement('updated'); - $root->appendChild($updated); - $text = $dom->createTextNode( - $this->getDataContainer()->getDateModified()->format(DateTime::ISO8601) - ); - $updated->appendChild($text); - } - - /** - * Set feed generator string - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setGenerator(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getGenerator()) { - $this->getDataContainer()->setGenerator('Zend_Feed_Writer', - Version::VERSION, 'http://framework.zend.com'); - } - - $gdata = $this->getDataContainer()->getGenerator(); - $generator = $dom->createElement('generator'); - $root->appendChild($generator); - $text = $dom->createTextNode($gdata['name']); - $generator->appendChild($text); - if (array_key_exists('uri', $gdata)) { - $generator->setAttribute('uri', $gdata['uri']); - } - if (array_key_exists('version', $gdata)) { - $generator->setAttribute('version', $gdata['version']); - } - } - - /** - * Set link to feed - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setLink(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getLink()) { - return; - } - $link = $dom->createElement('link'); - $root->appendChild($link); - $link->setAttribute('rel', 'alternate'); - $link->setAttribute('type', 'text/html'); - $link->setAttribute('href', $this->getDataContainer()->getLink()); - } - - /** - * Set feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Feed\Exception\InvalidArgumentException - */ - protected function _setFeedLinks(DOMDocument $dom, DOMElement $root) - { - $flinks = $this->getDataContainer()->getFeedLinks(); - if (!$flinks || !array_key_exists('atom', $flinks)) { - $message = 'Atom 1.0 feed elements SHOULD contain one atom:link ' - . 'element with a rel attribute value of "self". This is the ' - . 'preferred URI for retrieving Atom Feed Documents representing ' - . 'this Atom feed but a feed link has not been set'; - $exception = new Feed\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - foreach ($flinks as $type => $href) { - $mime = 'application/' . strtolower($type) . '+xml'; - $flink = $dom->createElement('link'); - $root->appendChild($flink); - $flink->setAttribute('rel', 'self'); - $flink->setAttribute('type', $mime); - $flink->setAttribute('href', $href); - } - } - - /** - * Set feed authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->container->getAuthors(); - if (!$authors || empty($authors)) { - /** - * Technically we should defer an exception until we can check - * that all entries contain an author. If any entry is missing - * an author, then a missing feed author element is invalid - */ - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('author'); - $name = $this->dom->createElement('name'); - $author->appendChild($name); - $root->appendChild($author); - $text = $dom->createTextNode($data['name']); - $name->appendChild($text); - if (array_key_exists('email', $data)) { - $email = $this->dom->createElement('email'); - $author->appendChild($email); - $text = $dom->createTextNode($data['email']); - $email->appendChild($text); - } - if (array_key_exists('uri', $data)) { - $uri = $this->dom->createElement('uri'); - $author->appendChild($uri); - $text = $dom->createTextNode($data['uri']); - $uri->appendChild($text); - } - } - } - - /** - * Set feed identifier - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Feed\Exception\InvalidArgumentException - */ - protected function _setId(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getId() - && !$this->getDataContainer()->getLink()) { - $message = 'Atom 1.0 feed elements MUST contain exactly one ' - . 'atom:id element, or as an alternative, we can use the same ' - . 'value as atom:link however neither a suitable link nor an ' - . 'id have been set'; - $exception = new Feed\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - if (!$this->getDataContainer()->getId()) { - $this->getDataContainer()->setId( - $this->getDataContainer()->getLink()); - } - $id = $dom->createElement('id'); - $root->appendChild($id); - $text = $dom->createTextNode($this->getDataContainer()->getId()); - $id->appendChild($text); - } - - /** - * Set feed copyright - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCopyright(DOMDocument $dom, DOMElement $root) - { - $copyright = $this->getDataContainer()->getCopyright(); - if (!$copyright) { - return; - } - $copy = $dom->createElement('rights'); - $root->appendChild($copy); - $text = $dom->createTextNode($copyright); - $copy->appendChild($text); - } - /** - * Set feed level logo (image) - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setImage(DOMDocument $dom, DOMElement $root) - { - $image = $this->getDataContainer()->getImage(); - if (!$image) { - return; - } - $img = $dom->createElement('logo'); - $root->appendChild($img); - $text = $dom->createTextNode($image['uri']); - $img->appendChild($text); - } - - - /** - * Set date feed was created - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateCreated(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateCreated()) { - return; - } - if (!$this->getDataContainer()->getDateModified()) { - $this->getDataContainer()->setDateModified( - $this->getDataContainer()->getDateCreated() - ); - } - } - - /** - * Set base URL to feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBaseUrl(DOMDocument $dom, DOMElement $root) - { - $baseUrl = $this->getDataContainer()->getBaseUrl(); - if (!$baseUrl) { - return; - } - $root->setAttribute('xml:base', $baseUrl); - } - - /** - * Set hubs to which this feed pushes - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setHubs(DOMDocument $dom, DOMElement $root) - { - $hubs = $this->getDataContainer()->getHubs(); - if (!$hubs) { - return; - } - foreach ($hubs as $hubUrl) { - $hub = $dom->createElement('link'); - $hub->setAttribute('rel', 'hub'); - $hub->setAttribute('href', $hubUrl); - $root->appendChild($hub); - } - } - - /** - * Set feed categories - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCategories(DOMDocument $dom, DOMElement $root) - { - $categories = $this->getDataContainer()->getCategories(); - if (!$categories) { - return; - } - foreach ($categories as $cat) { - $category = $dom->createElement('category'); - $category->setAttribute('term', $cat['term']); - if (isset($cat['label'])) { - $category->setAttribute('label', $cat['label']); - } else { - $category->setAttribute('label', $cat['term']); - } - if (isset($cat['scheme'])) { - $category->setAttribute('scheme', $cat['scheme']); - } - $root->appendChild($category); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Atom/Source.php b/library/Zend/Feed/Writer/Renderer/Feed/Atom/Source.php deleted file mode 100755 index 30f576a1f..000000000 --- a/library/Zend/Feed/Writer/Renderer/Feed/Atom/Source.php +++ /dev/null @@ -1,92 +0,0 @@ -container->getEncoding()) { - $this->container->setEncoding('UTF-8'); - } - $this->dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $root = $this->dom->createElement('source'); - $this->setRootElement($root); - $this->dom->appendChild($root); - $this->_setLanguage($this->dom, $root); - $this->_setBaseUrl($this->dom, $root); - $this->_setTitle($this->dom, $root); - $this->_setDescription($this->dom, $root); - $this->_setDateCreated($this->dom, $root); - $this->_setDateModified($this->dom, $root); - $this->_setGenerator($this->dom, $root); - $this->_setLink($this->dom, $root); - $this->_setFeedLinks($this->dom, $root); - $this->_setId($this->dom, $root); - $this->_setAuthors($this->dom, $root); - $this->_setCopyright($this->dom, $root); - $this->_setCategories($this->dom, $root); - - foreach ($this->extensions as $ext) { - $ext->setType($this->getType()); - $ext->setRootElement($this->getRootElement()); - $ext->setDomDocument($this->getDomDocument(), $root); - $ext->render(); - } - return $this; - } - - /** - * Set feed generator string - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setGenerator(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getGenerator()) { - return; - } - - $gdata = $this->getDataContainer()->getGenerator(); - $generator = $dom->createElement('generator'); - $root->appendChild($generator); - $text = $dom->createTextNode($gdata['name']); - $generator->appendChild($text); - if (array_key_exists('uri', $gdata)) { - $generator->setAttribute('uri', $gdata['uri']); - } - if (array_key_exists('version', $gdata)) { - $generator->setAttribute('version', $gdata['version']); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Feed/AtomSource.php b/library/Zend/Feed/Writer/Renderer/Feed/AtomSource.php deleted file mode 100755 index bdadd4db0..000000000 --- a/library/Zend/Feed/Writer/Renderer/Feed/AtomSource.php +++ /dev/null @@ -1,94 +0,0 @@ -container->getEncoding()) { - $this->container->setEncoding('UTF-8'); - } - $this->dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $root = $this->dom->createElement('source'); - $this->setRootElement($root); - $this->dom->appendChild($root); - $this->_setLanguage($this->dom, $root); - $this->_setBaseUrl($this->dom, $root); - $this->_setTitle($this->dom, $root); - $this->_setDescription($this->dom, $root); - $this->_setDateCreated($this->dom, $root); - $this->_setDateModified($this->dom, $root); - $this->_setGenerator($this->dom, $root); - $this->_setLink($this->dom, $root); - $this->_setFeedLinks($this->dom, $root); - $this->_setId($this->dom, $root); - $this->_setAuthors($this->dom, $root); - $this->_setCopyright($this->dom, $root); - $this->_setCategories($this->dom, $root); - - foreach ($this->extensions as $ext) { - $ext->setType($this->getType()); - $ext->setRootElement($this->getRootElement()); - $ext->setDOMDocument($this->getDOMDocument(), $root); - $ext->render(); - } - return $this; - } - - /** - * Set feed generator string - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setGenerator(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getGenerator()) { - return; - } - - $gdata = $this->getDataContainer()->getGenerator(); - $generator = $dom->createElement('generator'); - $root->appendChild($generator); - $text = $dom->createTextNode($gdata['name']); - $generator->appendChild($text); - if (array_key_exists('uri', $gdata)) { - $generator->setAttribute('uri', $gdata['uri']); - } - if (array_key_exists('version', $gdata)) { - $generator->setAttribute('version', $gdata['version']); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Rss.php b/library/Zend/Feed/Writer/Renderer/Feed/Rss.php deleted file mode 100755 index 75c502e32..000000000 --- a/library/Zend/Feed/Writer/Renderer/Feed/Rss.php +++ /dev/null @@ -1,484 +0,0 @@ -dom = new DOMDocument('1.0', $this->container->getEncoding()); - $this->dom->formatOutput = true; - $this->dom->substituteEntities = false; - $rss = $this->dom->createElement('rss'); - $this->setRootElement($rss); - $rss->setAttribute('version', '2.0'); - - $channel = $this->dom->createElement('channel'); - $rss->appendChild($channel); - $this->dom->appendChild($rss); - $this->_setLanguage($this->dom, $channel); - $this->_setBaseUrl($this->dom, $channel); - $this->_setTitle($this->dom, $channel); - $this->_setDescription($this->dom, $channel); - $this->_setImage($this->dom, $channel); - $this->_setDateCreated($this->dom, $channel); - $this->_setDateModified($this->dom, $channel); - $this->_setLastBuildDate($this->dom, $channel); - $this->_setGenerator($this->dom, $channel); - $this->_setLink($this->dom, $channel); - $this->_setAuthors($this->dom, $channel); - $this->_setCopyright($this->dom, $channel); - $this->_setCategories($this->dom, $channel); - - foreach ($this->extensions as $ext) { - $ext->setType($this->getType()); - $ext->setRootElement($this->getRootElement()); - $ext->setDOMDocument($this->getDOMDocument(), $channel); - $ext->render(); - } - - foreach ($this->container as $entry) { - if ($this->getDataContainer()->getEncoding()) { - $entry->setEncoding($this->getDataContainer()->getEncoding()); - } - if ($entry instanceof Writer\Entry) { - $renderer = new Renderer\Entry\Rss($entry); - } else { - continue; - } - if ($this->ignoreExceptions === true) { - $renderer->ignoreExceptions(); - } - $renderer->setType($this->getType()); - $renderer->setRootElement($this->dom->documentElement); - $renderer->render(); - $element = $renderer->getElement(); - $imported = $this->dom->importNode($element, true); - $channel->appendChild($imported); - } - return $this; - } - - /** - * Set feed language - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setLanguage(DOMDocument $dom, DOMElement $root) - { - $lang = $this->getDataContainer()->getLanguage(); - if (!$lang) { - return; - } - $language = $dom->createElement('language'); - $root->appendChild($language); - $language->nodeValue = $lang; - } - - /** - * Set feed title - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setTitle(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getTitle()) { - $message = 'RSS 2.0 feed elements MUST contain exactly one' - . ' title element but a title has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $title = $dom->createElement('title'); - $root->appendChild($title); - $text = $dom->createTextNode($this->getDataContainer()->getTitle()); - $title->appendChild($text); - } - - /** - * Set feed description - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setDescription(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDescription()) { - $message = 'RSS 2.0 feed elements MUST contain exactly one' - . ' description element but one has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $subtitle = $dom->createElement('description'); - $root->appendChild($subtitle); - $text = $dom->createTextNode($this->getDataContainer()->getDescription()); - $subtitle->appendChild($text); - } - - /** - * Set date feed was last modified - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateModified(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateModified()) { - return; - } - - $updated = $dom->createElement('pubDate'); - $root->appendChild($updated); - $text = $dom->createTextNode( - $this->getDataContainer()->getDateModified()->format(DateTime::RSS) - ); - $updated->appendChild($text); - } - - /** - * Set feed generator string - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setGenerator(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getGenerator()) { - $this->getDataContainer()->setGenerator('Zend_Feed_Writer', - Version::VERSION, 'http://framework.zend.com'); - } - - $gdata = $this->getDataContainer()->getGenerator(); - $generator = $dom->createElement('generator'); - $root->appendChild($generator); - $name = $gdata['name']; - if (array_key_exists('version', $gdata)) { - $name .= ' ' . $gdata['version']; - } - if (array_key_exists('uri', $gdata)) { - $name .= ' (' . $gdata['uri'] . ')'; - } - $text = $dom->createTextNode($name); - $generator->appendChild($text); - } - - /** - * Set link to feed - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setLink(DOMDocument $dom, DOMElement $root) - { - $value = $this->getDataContainer()->getLink(); - if (!$value) { - $message = 'RSS 2.0 feed elements MUST contain exactly one' - . ' link element but one has not been set'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $link = $dom->createElement('link'); - $root->appendChild($link); - $text = $dom->createTextNode($value); - $link->appendChild($text); - if (!Uri::factory($value)->isValid()) { - $link->setAttribute('isPermaLink', 'false'); - } - } - - /** - * Set feed authors - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setAuthors(DOMDocument $dom, DOMElement $root) - { - $authors = $this->getDataContainer()->getAuthors(); - if (!$authors || empty($authors)) { - return; - } - foreach ($authors as $data) { - $author = $this->dom->createElement('author'); - $name = $data['name']; - if (array_key_exists('email', $data)) { - $name = $data['email'] . ' (' . $data['name'] . ')'; - } - $text = $dom->createTextNode($name); - $author->appendChild($text); - $root->appendChild($author); - } - } - - /** - * Set feed copyright - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCopyright(DOMDocument $dom, DOMElement $root) - { - $copyright = $this->getDataContainer()->getCopyright(); - if (!$copyright) { - return; - } - $copy = $dom->createElement('copyright'); - $root->appendChild($copy); - $text = $dom->createTextNode($copyright); - $copy->appendChild($text); - } - - /** - * Set feed channel image - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - * @throws Writer\Exception\InvalidArgumentException - */ - protected function _setImage(DOMDocument $dom, DOMElement $root) - { - $image = $this->getDataContainer()->getImage(); - if (!$image) { - return; - } - - if (!isset($image['title']) || empty($image['title']) - || !is_string($image['title']) - ) { - $message = 'RSS 2.0 feed images must include a title'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - if (empty($image['link']) || !is_string($image['link']) - || !Uri::factory($image['link'])->isValid() - ) { - $message = 'Invalid parameter: parameter \'link\'' - . ' must be a non-empty string and valid URI/IRI'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - - $img = $dom->createElement('image'); - $root->appendChild($img); - - $url = $dom->createElement('url'); - $text = $dom->createTextNode($image['uri']); - $url->appendChild($text); - - $title = $dom->createElement('title'); - $text = $dom->createTextNode($image['title']); - $title->appendChild($text); - - $link = $dom->createElement('link'); - $text = $dom->createTextNode($image['link']); - $link->appendChild($text); - - $img->appendChild($url); - $img->appendChild($title); - $img->appendChild($link); - - if (isset($image['height'])) { - if (!ctype_digit((string) $image['height']) || $image['height'] > 400) { - $message = 'Invalid parameter: parameter \'height\'' - . ' must be an integer not exceeding 400'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $height = $dom->createElement('height'); - $text = $dom->createTextNode($image['height']); - $height->appendChild($text); - $img->appendChild($height); - } - if (isset($image['width'])) { - if (!ctype_digit((string) $image['width']) || $image['width'] > 144) { - $message = 'Invalid parameter: parameter \'width\'' - . ' must be an integer not exceeding 144'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $width = $dom->createElement('width'); - $text = $dom->createTextNode($image['width']); - $width->appendChild($text); - $img->appendChild($width); - } - if (isset($image['description'])) { - if (empty($image['description']) || !is_string($image['description'])) { - $message = 'Invalid parameter: parameter \'description\'' - . ' must be a non-empty string'; - $exception = new Writer\Exception\InvalidArgumentException($message); - if (!$this->ignoreExceptions) { - throw $exception; - } else { - $this->exceptions[] = $exception; - return; - } - } - $desc = $dom->createElement('description'); - $text = $dom->createTextNode($image['description']); - $desc->appendChild($text); - $img->appendChild($desc); - } - } - - /** - * Set date feed was created - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setDateCreated(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getDateCreated()) { - return; - } - if (!$this->getDataContainer()->getDateModified()) { - $this->getDataContainer()->setDateModified( - $this->getDataContainer()->getDateCreated() - ); - } - } - - /** - * Set date feed last build date - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setLastBuildDate(DOMDocument $dom, DOMElement $root) - { - if (!$this->getDataContainer()->getLastBuildDate()) { - return; - } - - $lastBuildDate = $dom->createElement('lastBuildDate'); - $root->appendChild($lastBuildDate); - $text = $dom->createTextNode( - $this->getDataContainer()->getLastBuildDate()->format(DateTime::RSS) - ); - $lastBuildDate->appendChild($text); - } - - /** - * Set base URL to feed links - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setBaseUrl(DOMDocument $dom, DOMElement $root) - { - $baseUrl = $this->getDataContainer()->getBaseUrl(); - if (!$baseUrl) { - return; - } - $root->setAttribute('xml:base', $baseUrl); - } - - /** - * Set feed categories - * - * @param DOMDocument $dom - * @param DOMElement $root - * @return void - */ - protected function _setCategories(DOMDocument $dom, DOMElement $root) - { - $categories = $this->getDataContainer()->getCategories(); - if (!$categories) { - return; - } - foreach ($categories as $cat) { - $category = $dom->createElement('category'); - if (isset($cat['scheme'])) { - $category->setAttribute('domain', $cat['scheme']); - } - $text = $dom->createTextNode($cat['term']); - $category->appendChild($text); - $root->appendChild($category); - } - } -} diff --git a/library/Zend/Feed/Writer/Renderer/RendererInterface.php b/library/Zend/Feed/Writer/Renderer/RendererInterface.php deleted file mode 100755 index b2e0e00a3..000000000 --- a/library/Zend/Feed/Writer/Renderer/RendererInterface.php +++ /dev/null @@ -1,100 +0,0 @@ - array(), - 'feed' => array(), - 'entryRenderer' => array(), - 'feedRenderer' => array(), - ); - - /** - * Set plugin loader for use with Extensions - * - * @param ExtensionManagerInterface - */ - public static function setExtensionManager(ExtensionManagerInterface $extensionManager) - { - static::$extensionManager = $extensionManager; - } - - /** - * Get plugin manager for use with Extensions - * - * @return ExtensionManagerInterface - */ - public static function getExtensionManager() - { - if (!isset(static::$extensionManager)) { - static::setExtensionManager(new ExtensionManager()); - } - return static::$extensionManager; - } - - /** - * Register an Extension by name - * - * @param string $name - * @return void - * @throws Exception\RuntimeException if unable to resolve Extension class - */ - public static function registerExtension($name) - { - $feedName = $name . '\Feed'; - $entryName = $name . '\Entry'; - $feedRendererName = $name . '\Renderer\Feed'; - $entryRendererName = $name . '\Renderer\Entry'; - $manager = static::getExtensionManager(); - if (static::isRegistered($name)) { - if ($manager->has($feedName) - || $manager->has($entryName) - || $manager->has($feedRendererName) - || $manager->has($entryRendererName) - ) { - return; - } - } - if (!$manager->has($feedName) - && !$manager->has($entryName) - && !$manager->has($feedRendererName) - && !$manager->has($entryRendererName) - ) { - throw new Exception\RuntimeException('Could not load extension: ' . $name - . 'using Plugin Loader. Check prefix paths are configured and extension exists.'); - } - if ($manager->has($feedName)) { - static::$extensions['feed'][] = $feedName; - } - if ($manager->has($entryName)) { - static::$extensions['entry'][] = $entryName; - } - if ($manager->has($feedRendererName)) { - static::$extensions['feedRenderer'][] = $feedRendererName; - } - if ($manager->has($entryRendererName)) { - static::$extensions['entryRenderer'][] = $entryRendererName; - } - } - - /** - * Is a given named Extension registered? - * - * @param string $extensionName - * @return bool - */ - public static function isRegistered($extensionName) - { - $feedName = $extensionName . '\Feed'; - $entryName = $extensionName . '\Entry'; - $feedRendererName = $extensionName . '\Renderer\Feed'; - $entryRendererName = $extensionName . '\Renderer\Entry'; - if (in_array($feedName, static::$extensions['feed']) - || in_array($entryName, static::$extensions['entry']) - || in_array($feedRendererName, static::$extensions['feedRenderer']) - || in_array($entryRendererName, static::$extensions['entryRenderer']) - ) { - return true; - } - return false; - } - - /** - * Get a list of extensions - * - * @return array - */ - public static function getExtensions() - { - return static::$extensions; - } - - /** - * Reset class state to defaults - * - * @return void - */ - public static function reset() - { - static::$extensionManager = null; - static::$extensions = array( - 'entry' => array(), - 'feed' => array(), - 'entryRenderer' => array(), - 'feedRenderer' => array(), - ); - } - - /** - * Register core (default) extensions - * - * @return void - */ - public static function registerCoreExtensions() - { - static::registerExtension('DublinCore'); - static::registerExtension('Content'); - static::registerExtension('Atom'); - static::registerExtension('Slash'); - static::registerExtension('WellFormedWeb'); - static::registerExtension('Threading'); - static::registerExtension('ITunes'); - } - - public static function lcfirst($str) - { - $str[0] = strtolower($str[0]); - return $str; - } -} diff --git a/library/Zend/Feed/composer.json b/library/Zend/Feed/composer.json deleted file mode 100755 index 0c4d7dc18..000000000 --- a/library/Zend/Feed/composer.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "zendframework/zend-feed", - "description": "provides functionality for consuming RSS and Atom feeds", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "feed" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\Feed\\": "" - } - }, - "target-dir": "Zend/Feed", - "require": { - "php": ">=5.3.23", - "zendframework/zend-escaper": "self.version", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-db": "self.version", - "zendframework/zend-cache": "self.version", - "zendframework/zend-http": "self.version", - "zendframework/zend-servicemanager": "self.version", - "zendframework/zend-validator": "self.version" - }, - "suggest": { - "zendframework/zend-cache": "Zend\\Cache component", - "zendframework/zend-db": "Zend\\Db component", - "zendframework/zend-http": "Zend\\Http for PubSubHubbub, and optionally for use with Zend\\Feed\\Reader", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component, for default/recommended ExtensionManager implementations", - "zendframework/zend-validator": "Zend\\Validator component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/File/CONTRIBUTING.md b/library/Zend/File/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/File/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/File/ClassFileLocator.php b/library/Zend/File/ClassFileLocator.php deleted file mode 100755 index 9ef7821a6..000000000 --- a/library/Zend/File/ClassFileLocator.php +++ /dev/null @@ -1,160 +0,0 @@ -setInfoClass('Zend\File\PhpClassFile'); - } - - /** - * Filter for files containing PHP classes, interfaces, or abstracts - * - * @return bool - */ - public function accept() - { - $file = $this->getInnerIterator()->current(); - // If we somehow have something other than an SplFileInfo object, just - // return false - if (!$file instanceof SplFileInfo) { - return false; - } - - // If we have a directory, it's not a file, so return false - if (!$file->isFile()) { - return false; - } - - // If not a PHP file, skip - if ($file->getBasename('.php') == $file->getBasename()) { - return false; - } - - $contents = file_get_contents($file->getRealPath()); - $tokens = token_get_all($contents); - $count = count($tokens); - $t_trait = defined('T_TRAIT') ? T_TRAIT : -1; // For preserve PHP 5.3 compatibility - for ($i = 0; $i < $count; $i++) { - $token = $tokens[$i]; - if (!is_array($token)) { - // single character token found; skip - $i++; - continue; - } - switch ($token[0]) { - case T_NAMESPACE: - // Namespace found; grab it for later - $namespace = ''; - for ($i++; $i < $count; $i++) { - $token = $tokens[$i]; - if (is_string($token)) { - if (';' === $token) { - $saveNamespace = false; - break; - } - if ('{' === $token) { - $saveNamespace = true; - break; - } - continue; - } - list($type, $content, $line) = $token; - switch ($type) { - case T_STRING: - case T_NS_SEPARATOR: - $namespace .= $content; - break; - } - } - if ($saveNamespace) { - $savedNamespace = $namespace; - } - break; - case $t_trait: - case T_CLASS: - case T_INTERFACE: - // Abstract class, class, interface or trait found - - // Get the classname - for ($i++; $i < $count; $i++) { - $token = $tokens[$i]; - if (is_string($token)) { - continue; - } - list($type, $content, $line) = $token; - if (T_STRING == $type) { - // If a classname was found, set it in the object, and - // return boolean true (found) - if (!isset($namespace) || null === $namespace) { - if (isset($saveNamespace) && $saveNamespace) { - $namespace = $savedNamespace; - } else { - $namespace = null; - } - } - $class = (null === $namespace) ? $content : $namespace . '\\' . $content; - $file->addClass($class); - if ($namespace) { - $file->addNamespace($namespace); - } - $namespace = null; - break; - } - } - break; - default: - break; - } - } - $classes = $file->getClasses(); - if (!empty($classes)) { - return true; - } - // No class-type tokens found; return false - return false; - } -} diff --git a/library/Zend/File/Exception/BadMethodCallException.php b/library/Zend/File/Exception/BadMethodCallException.php deleted file mode 100755 index 04be86936..000000000 --- a/library/Zend/File/Exception/BadMethodCallException.php +++ /dev/null @@ -1,15 +0,0 @@ -classes; - } - - /** - * Get namespaces - * - * @return array - */ - public function getNamespaces() - { - return $this->namespaces; - } - - /** - * Add class - * - * @param string $class - * @return self - */ - public function addClass($class) - { - $this->classes[] = $class; - return $this; - } - - /** - * Add namespace - * - * @param string $namespace - * @return self - */ - public function addNamespace($namespace) - { - if (in_array($namespace, $this->namespaces)) { - return $this; - } - $this->namespaces[] = $namespace; - return $this; - } -} diff --git a/library/Zend/File/README.md b/library/Zend/File/README.md deleted file mode 100755 index 8e1ab787f..000000000 --- a/library/Zend/File/README.md +++ /dev/null @@ -1,15 +0,0 @@ -File Component from ZF2 -======================= - -This is the File component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/File/Transfer/Adapter/AbstractAdapter.php b/library/Zend/File/Transfer/Adapter/AbstractAdapter.php deleted file mode 100755 index a46935f69..000000000 --- a/library/Zend/File/Transfer/Adapter/AbstractAdapter.php +++ /dev/null @@ -1,1504 +0,0 @@ - array( - Form is the name within the form or, if not set the filename - * name, - Original name of this file - * type, - Mime type of this file - * size, - Filesize in bytes - * tmp_name, - Internally temporary filename for uploaded files - * error, - Error which has occurred - * destination, - New destination for this file - * validators, - Set validator names for this file - * files - Set file names for this file - * )) - * - * @var array - */ - protected $files = array(); - - /** - * TMP directory - * @var string - */ - protected $tmpDir; - - /** - * Available options for file transfers - */ - protected $options = array( - 'ignoreNoFile' => false, - 'useByteString' => true, - 'magicFile' => null, - 'detectInfos' => true, - ); - - /** - * Send file - * - * @param mixed $options - * @return bool - */ - abstract public function send($options = null); - - /** - * Receive file - * - * @param mixed $options - * @return bool - */ - abstract public function receive($options = null); - - /** - * Is file sent? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isSent($files = null); - - /** - * Is file received? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isReceived($files = null); - - /** - * Has a file been uploaded ? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isUploaded($files = null); - - /** - * Has the file been filtered ? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isFiltered($files = null); - - /** - * Adds one or more files - * - * @param string|array $file File to add - * @param string|array $validator Validators to use for this file, must be set before - * @param string|array $filter Filters to use for this file, must be set before - * @return AbstractAdapter - * @throws Exception Not implemented - */ - //abstract public function addFile($file, $validator = null, $filter = null); - - /** - * Returns all set types - * - * @return array List of set types - * @throws Exception Not implemented - */ - //abstract public function getType(); - - /** - * Adds one or more type of files - * - * @param string|array $type Type of files to add - * @param string|array $validator Validators to use for this file, must be set before - * @param string|array $filter Filters to use for this file, must be set before - * @return AbstractAdapter - * @throws Exception Not implemented - */ - //abstract public function addType($type, $validator = null, $filter = null); - - /** - * Returns all set files - * - * @return array List of set files - */ - //abstract public function getFile(); - - /** - * Set the filter plugin manager instance - * - * @param FilterPluginManager $filterManager - * @return AbstractAdapter - */ - public function setFilterManager(FilterPluginManager $filterManager) - { - $this->filterManager = $filterManager; - return $this; - } - - /** - * Get the filter plugin manager instance - * - * @return FilterPluginManager - */ - public function getFilterManager() - { - if (!$this->filterManager instanceof FilterPluginManager) { - $this->setFilterManager(new FilterPluginManager()); - } - return $this->filterManager; - } - - /** - * Set the validator plugin manager instance - * - * @param ValidatorPluginManager $validatorManager - * @return AbstractAdapter - */ - public function setValidatorManager(ValidatorPluginManager $validatorManager) - { - $this->validatorManager = $validatorManager; - return $this; - } - - /** - * Get the validator plugin manager instance - * - * @return ValidatorPluginManager - */ - public function getValidatorManager() - { - if (!$this->validatorManager instanceof ValidatorPluginManager) { - $this->setValidatorManager(new ValidatorPluginManager()); - } - return $this->validatorManager; - } - - /** - * Adds a new validator for this class - * - * @param string|Validator\ValidatorInterface $validator Type of validator to add - * @param bool $breakChainOnFailure If the validation chain should stop a failure - * @param string|array $options Options to set for the validator - * @param string|array $files Files to limit this validator to - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException for invalid type - */ - public function addValidator($validator, $breakChainOnFailure = false, $options = null, $files = null) - { - if (is_string($validator)) { - $validator = $this->getValidatorManager()->get($validator, $options); - if (is_array($options) && isset($options['messages'])) { - if (is_array($options['messages'])) { - $validator->setMessages($options['messages']); - } elseif (is_string($options['messages'])) { - $validator->setMessage($options['messages']); - } - - unset($options['messages']); - } - } - - if (!$validator instanceof Validator\ValidatorInterface) { - throw new Exception\InvalidArgumentException( - 'Invalid validator provided to addValidator; ' . - 'must be string or Zend\Validator\ValidatorInterface' - ); - } - - $name = get_class($validator); - - $this->validators[$name] = $validator; - $this->break[$name] = $breakChainOnFailure; - $files = $this->getFiles($files, true, true); - foreach ($files as $file) { - if ($name == 'NotEmpty') { - $temp = $this->files[$file]['validators']; - $this->files[$file]['validators'] = array($name); - $this->files[$file]['validators'] += $temp; - } else { - $this->files[$file]['validators'][] = $name; - } - - $this->files[$file]['validated'] = false; - } - - return $this; - } - - /** - * Add Multiple validators at once - * - * @param array $validators - * @param string|array $files - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException for invalid type - */ - public function addValidators(array $validators, $files = null) - { - foreach ($validators as $name => $validatorInfo) { - if ($validatorInfo instanceof Validator\ValidatorInterface) { - $this->addValidator($validatorInfo, null, null, $files); - } elseif (is_string($validatorInfo)) { - if (!is_int($name)) { - $this->addValidator($name, null, $validatorInfo, $files); - } else { - $this->addValidator($validatorInfo, null, null, $files); - } - } elseif (is_array($validatorInfo)) { - $argc = count($validatorInfo); - $breakChainOnFailure = false; - $options = array(); - if (isset($validatorInfo['validator'])) { - $validator = $validatorInfo['validator']; - if (isset($validatorInfo['breakChainOnFailure'])) { - $breakChainOnFailure = $validatorInfo['breakChainOnFailure']; - } - - if (isset($validatorInfo['options'])) { - $options = $validatorInfo['options']; - } - - $this->addValidator($validator, $breakChainOnFailure, $options, $files); - } else { - if (is_string($name)) { - $validator = $name; - $options = $validatorInfo; - $this->addValidator($validator, $breakChainOnFailure, $options, $files); - } else { - $file = $files; - switch (true) { - case (0 == $argc): - break; - case (1 <= $argc): - $validator = array_shift($validatorInfo); - case (2 <= $argc): - $breakChainOnFailure = array_shift($validatorInfo); - case (3 <= $argc): - $options = array_shift($validatorInfo); - case (4 <= $argc): - if (!empty($validatorInfo)) { - $file = array_shift($validatorInfo); - } - default: - $this->addValidator($validator, $breakChainOnFailure, $options, $file); - break; - } - } - } - } else { - throw new Exception\InvalidArgumentException('Invalid validator passed to addValidators()'); - } - } - - return $this; - } - - /** - * Sets a validator for the class, erasing all previous set - * - * @param array $validators Validators to set - * @param string|array $files Files to limit this validator to - * @return AbstractAdapter - */ - public function setValidators(array $validators, $files = null) - { - $this->clearValidators(); - return $this->addValidators($validators, $files); - } - - /** - * Determine if a given validator has already been registered - * - * @param string $name - * @return bool - */ - public function hasValidator($name) - { - return (false !== $this->getValidatorIdentifier($name)); - } - - /** - * Retrieve individual validator - * - * @param string $name - * @return Validator\ValidatorInterface|null - */ - public function getValidator($name) - { - if (false === ($identifier = $this->getValidatorIdentifier($name))) { - return null; - } - return $this->validators[$identifier]; - } - - /** - * Returns all set validators - * - * @param string|array $files (Optional) Returns the validator for this files - * @return null|array List of set validators - */ - public function getValidators($files = null) - { - if ($files == null) { - return $this->validators; - } - - $files = $this->getFiles($files, true, true); - $validators = array(); - foreach ($files as $file) { - if (!empty($this->files[$file]['validators'])) { - $validators += $this->files[$file]['validators']; - } - } - - $validators = array_unique($validators); - $result = array(); - foreach ($validators as $validator) { - $result[$validator] = $this->validators[$validator]; - } - - return $result; - } - - /** - * Remove an individual validator - * - * @param string $name - * @return AbstractAdapter - */ - public function removeValidator($name) - { - if (false === ($key = $this->getValidatorIdentifier($name))) { - return $this; - } - - unset($this->validators[$key]); - foreach (array_keys($this->files) as $file) { - if (empty($this->files[$file]['validators'])) { - continue; - } - - $index = array_search($key, $this->files[$file]['validators']); - if ($index === false) { - continue; - } - - unset($this->files[$file]['validators'][$index]); - $this->files[$file]['validated'] = false; - } - - return $this; - } - - /** - * Remove all validators - * - * @return AbstractAdapter - */ - public function clearValidators() - { - $this->validators = array(); - foreach (array_keys($this->files) as $file) { - $this->files[$file]['validators'] = array(); - $this->files[$file]['validated'] = false; - } - - return $this; - } - - /** - * Sets Options for adapters - * - * @param array $options Options to set - * @param array $files (Optional) Files to set the options for - * @return AbstractAdapter - */ - public function setOptions($options = array(), $files = null) - { - $file = $this->getFiles($files, false, true); - - if (is_array($options)) { - if (empty($file)) { - $this->options = array_merge($this->options, $options); - } - - foreach ($options as $name => $value) { - foreach ($file as $key => $content) { - switch ($name) { - case 'magicFile' : - $this->files[$key]['options'][$name] = (string) $value; - break; - - case 'ignoreNoFile' : - case 'useByteString' : - case 'detectInfos' : - $this->files[$key]['options'][$name] = (bool) $value; - break; - - default: - continue; - } - } - } - } - - return $this; - } - - /** - * Returns set options for adapters or files - * - * @param array $files (Optional) Files to return the options for - * @return array Options for given files - */ - public function getOptions($files = null) - { - $file = $this->getFiles($files, false, true); - - foreach ($file as $key => $content) { - if (isset($this->files[$key]['options'])) { - $options[$key] = $this->files[$key]['options']; - } else { - $options[$key] = array(); - } - } - - return $options; - } - - /** - * Checks if the files are valid - * - * @param string|array $files (Optional) Files to check - * @return bool True if all checks are valid - */ - public function isValid($files = null) - { - $check = $this->getFiles($files, false, true); - if (empty($check)) { - return false; - } - - $translator = $this->getTranslator(); - $this->messages = array(); - $break = false; - foreach ($check as $content) { - if (array_key_exists('validators', $content) && - in_array('Zend\Validator\File\Count', $content['validators'])) { - $validator = $this->validators['Zend\Validator\File\Count']; - $count = $content; - if (empty($content['tmp_name'])) { - continue; - } - - if (array_key_exists('destination', $content)) { - $checkit = $content['destination']; - } else { - $checkit = dirname($content['tmp_name']); - } - - $checkit .= DIRECTORY_SEPARATOR . $content['name']; - $validator->addFile($checkit); - } - } - - if (isset($count)) { - if (!$validator->isValid($count['tmp_name'], $count)) { - $this->messages += $validator->getMessages(); - } - } - - foreach ($check as $key => $content) { - $fileerrors = array(); - if (array_key_exists('validators', $content) && $content['validated']) { - continue; - } - - if (array_key_exists('validators', $content)) { - foreach ($content['validators'] as $class) { - $validator = $this->validators[$class]; - if (method_exists($validator, 'setTranslator')) { - $validator->setTranslator($translator); - } - - if (($class === 'Zend\Validator\File\Upload') && (empty($content['tmp_name']))) { - $tocheck = $key; - } else { - $tocheck = $content['tmp_name']; - } - - if (!$validator->isValid($tocheck, $content)) { - $fileerrors += $validator->getMessages(); - } - - if (!empty($content['options']['ignoreNoFile']) && (isset($fileerrors['fileUploadErrorNoFile']))) { - unset($fileerrors['fileUploadErrorNoFile']); - break; - } - - if (($class === 'Zend\Validator\File\Upload') && (count($fileerrors) > 0)) { - break; - } - - if (($this->break[$class]) && (count($fileerrors) > 0)) { - $break = true; - break; - } - } - } - - if (count($fileerrors) > 0) { - $this->files[$key]['validated'] = false; - } else { - $this->files[$key]['validated'] = true; - } - - $this->messages += $fileerrors; - if ($break) { - break; - } - } - - if (count($this->messages) > 0) { - return false; - } - - return true; - } - - /** - * Returns found validation messages - * - * @return array - */ - public function getMessages() - { - return $this->messages; - } - - /** - * Retrieve error codes - * - * @return array - */ - public function getErrors() - { - return array_keys($this->messages); - } - - /** - * Are there errors registered? - * - * @return bool - */ - public function hasErrors() - { - return (!empty($this->messages)); - } - - /** - * Adds a new filter for this class - * - * @param string|Filter\FilterInterface $filter Type of filter to add - * @param string|array $options Options to set for the filter - * @param string|array $files Files to limit this filter to - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException for invalid type - */ - public function addFilter($filter, $options = null, $files = null) - { - if (is_string($filter)) { - $filter = $this->getFilterManager()->get($filter, $options); - } - - if (!$filter instanceof Filter\FilterInterface) { - throw new Exception\InvalidArgumentException('Invalid filter specified'); - } - - $class = get_class($filter); - $this->filters[$class] = $filter; - $files = $this->getFiles($files, true, true); - foreach ($files as $file) { - $this->files[$file]['filters'][] = $class; - } - - return $this; - } - - /** - * Add Multiple filters at once - * - * @param array $filters - * @param string|array $files - * @return AbstractAdapter - */ - public function addFilters(array $filters, $files = null) - { - foreach ($filters as $key => $spec) { - if ($spec instanceof Filter\FilterInterface) { - $this->addFilter($spec, null, $files); - continue; - } - - if (is_string($key)) { - $this->addFilter($key, $spec, $files); - continue; - } - - if (is_int($key)) { - if (is_string($spec)) { - $this->addFilter($spec, null, $files); - continue; - } - - if (is_array($spec)) { - if (!array_key_exists('filter', $spec)) { - continue; - } - - $filter = $spec['filter']; - unset($spec['filter']); - $this->addFilter($filter, $spec, $files); - continue; - } - - continue; - } - } - - return $this; - } - - /** - * Sets a filter for the class, erasing all previous set - * - * @param array $filters Filter to set - * @param string|array $files Files to limit this filter to - * @return Filter\AbstractFilter - */ - public function setFilters(array $filters, $files = null) - { - $this->clearFilters(); - return $this->addFilters($filters, $files); - } - - /** - * Determine if a given filter has already been registered - * - * @param string $name - * @return bool - */ - public function hasFilter($name) - { - return (false !== $this->getFilterIdentifier($name)); - } - - /** - * Retrieve individual filter - * - * @param string $name - * @return Filter\FilterInterface|null - */ - public function getFilter($name) - { - if (false === ($identifier = $this->getFilterIdentifier($name))) { - return null; - } - - return $this->filters[$identifier]; - } - - /** - * Returns all set filters - * - * @param string|array $files (Optional) Returns the filter for this files - * @return array List of set filters - * @throws Exception\RuntimeException When file not found - */ - public function getFilters($files = null) - { - if ($files === null) { - return $this->filters; - } - - $files = $this->getFiles($files, true, true); - $filters = array(); - foreach ($files as $file) { - if (!empty($this->files[$file]['filters'])) { - $filters += $this->files[$file]['filters']; - } - } - - $filters = array_unique($filters); - $result = array(); - foreach ($filters as $filter) { - $result[] = $this->filters[$filter]; - } - - return $result; - } - - /** - * Remove an individual filter - * - * @param string $name - * @return AbstractAdapter - */ - public function removeFilter($name) - { - if (false === ($key = $this->getFilterIdentifier($name))) { - return $this; - } - - unset($this->filters[$key]); - foreach (array_keys($this->files) as $file) { - if (empty($this->files[$file]['filters'])) { - continue; - } - - $index = array_search($key, $this->files[$file]['filters']); - if ($index === false) { - continue; - } - - unset($this->files[$file]['filters'][$index]); - } - return $this; - } - - /** - * Remove all filters - * - * @return AbstractAdapter - */ - public function clearFilters() - { - $this->filters = array(); - foreach (array_keys($this->files) as $file) { - $this->files[$file]['filters'] = array(); - } - - return $this; - } - - /** - * Retrieves the filename of transferred files. - * - * @param string $file (Optional) Element to return the filename for - * @param bool $path (Optional) Should the path also be returned ? - * @return string|array - */ - public function getFileName($file = null, $path = true) - { - $files = $this->getFiles($file, true, true); - $result = array(); - $directory = ""; - foreach ($files as $file) { - if (empty($this->files[$file]['name'])) { - continue; - } - - if ($path === true) { - $directory = $this->getDestination($file) . DIRECTORY_SEPARATOR; - } - - $result[$file] = $directory . $this->files[$file]['name']; - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Retrieve additional internal file informations for files - * - * @param string $file (Optional) File to get informations for - * @return array - */ - public function getFileInfo($file = null) - { - return $this->getFiles($file); - } - - /** - * Sets a new destination for the given files - * - * @deprecated Will be changed to be a filter!!! - * @param string $destination New destination directory - * @param string|array $files Files to set the new destination for - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException when the given destination is not a directory or does not exist - */ - public function setDestination($destination, $files = null) - { - $orig = $files; - $destination = rtrim($destination, "/\\"); - if (!is_dir($destination)) { - throw new Exception\InvalidArgumentException('The given destination is not a directory or does not exist'); - } - - if (!is_writable($destination)) { - throw new Exception\InvalidArgumentException('The given destination is not writeable'); - } - - if ($files === null) { - foreach ($this->files as $file => $content) { - $this->files[$file]['destination'] = $destination; - } - } else { - $files = $this->getFiles($files, true, true); - if (empty($files) and is_string($orig)) { - $this->files[$orig]['destination'] = $destination; - } - - foreach ($files as $file) { - $this->files[$file]['destination'] = $destination; - } - } - - return $this; - } - - /** - * Retrieve destination directory value - * - * @param null|string|array $files - * @throws Exception\InvalidArgumentException - * @return null|string|array - */ - public function getDestination($files = null) - { - $orig = $files; - $files = $this->getFiles($files, false, true); - $destinations = array(); - if (empty($files) and is_string($orig)) { - if (isset($this->files[$orig]['destination'])) { - $destinations[$orig] = $this->files[$orig]['destination']; - } else { - throw new Exception\InvalidArgumentException( - sprintf('The file transfer adapter can not find "%s"', $orig) - ); - } - } - - foreach ($files as $key => $content) { - if (isset($this->files[$key]['destination'])) { - $destinations[$key] = $this->files[$key]['destination']; - } else { - $tmpdir = $this->getTmpDir(); - $this->setDestination($tmpdir, $key); - $destinations[$key] = $tmpdir; - } - } - - if (empty($destinations)) { - $destinations = $this->getTmpDir(); - } elseif (count($destinations) == 1) { - $destinations = current($destinations); - } - - return $destinations; - } - - /** - * Sets translator to use in helper - * - * @param Translator $translator [optional] translator. - * Default is null, which sets no translator. - * @param string $textDomain [optional] text domain - * Default is null, which skips setTranslatorTextDomain - * @return AbstractAdapter - */ - public function setTranslator(Translator $translator = null, $textDomain = null) - { - $this->translator = $translator; - if (null !== $textDomain) { - $this->setTranslatorTextDomain($textDomain); - } - return $this; - } - - /** - * Retrieve localization translator object - * - * @return Translator|null - */ - public function getTranslator() - { - if ($this->isTranslatorEnabled()) { - return null; - } - - return $this->translator; - } - - /** - * Checks if the helper has a translator - * - * @return bool - */ - public function hasTranslator() - { - return (bool) $this->getTranslator(); - } - - /** - * Indicate whether or not translation should be enabled - * - * @param bool $flag - * @return AbstractAdapter - */ - public function setTranslatorEnabled($flag = true) - { - $this->translatorEnabled = (bool) $flag; - return $this; - } - - /** - * Is translation enabled? - * - * @return bool - */ - public function isTranslatorEnabled() - { - return $this->translatorEnabled; - } - - /** - * Set translation text domain - * - * @param string $textDomain - * @return AbstractAdapter - */ - public function setTranslatorTextDomain($textDomain = 'default') - { - $this->translatorTextDomain = $textDomain; - return $this; - } - - /** - * Return the translation text domain - * - * @return string - */ - public function getTranslatorTextDomain() - { - return $this->translatorTextDomain; - } - - /** - * Returns the hash for a given file - * - * @param string $hash Hash algorithm to use - * @param string|array $files Files to return the hash for - * @return string|array Hashstring - * @throws Exception\InvalidArgumentException On unknown hash algorithm - */ - public function getHash($hash = 'crc32', $files = null) - { - if (!in_array($hash, hash_algos())) { - throw new Exception\InvalidArgumentException('Unknown hash algorithm'); - } - - $files = $this->getFiles($files); - $result = array(); - foreach ($files as $key => $value) { - if (file_exists($value['name'])) { - $result[$key] = hash_file($hash, $value['name']); - } elseif (file_exists($value['tmp_name'])) { - $result[$key] = hash_file($hash, $value['tmp_name']); - } elseif (empty($value['options']['ignoreNoFile'])) { - throw new Exception\InvalidArgumentException("The file '{$value['name']}' does not exist"); - } - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Returns the real filesize of the file - * - * @param string|array $files Files to get the filesize from - * @return string|array Filesize - * @throws Exception\InvalidArgumentException When the file does not exist - */ - public function getFileSize($files = null) - { - $files = $this->getFiles($files); - $result = array(); - foreach ($files as $key => $value) { - if (file_exists($value['name']) || file_exists($value['tmp_name'])) { - if ($value['options']['useByteString']) { - $result[$key] = static::toByteString($value['size']); - } else { - $result[$key] = $value['size']; - } - } elseif (empty($value['options']['ignoreNoFile'])) { - throw new Exception\InvalidArgumentException("The file '{$value['name']}' does not exist"); - } else { - continue; - } - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Internal method to detect the size of a file - * - * @param array $value File infos - * @return string Filesize of given file - */ - protected function detectFileSize($value) - { - if (file_exists($value['name'])) { - $filename = $value['name']; - } elseif (file_exists($value['tmp_name'])) { - $filename = $value['tmp_name']; - } else { - return null; - } - - ErrorHandler::start(); - $filesize = filesize($filename); - $return = ErrorHandler::stop(); - if ($return instanceof ErrorException) { - $filesize = 0; - } - - return sprintf("%u", $filesize); - } - - /** - * Returns the real mimetype of the file - * Uses fileinfo, when not available mime_magic and as last fallback a manual given mimetype - * - * @param string|array $files Files to get the mimetype from - * @return string|array MimeType - * @throws Exception\InvalidArgumentException When the file does not exist - */ - public function getMimeType($files = null) - { - $files = $this->getFiles($files); - $result = array(); - foreach ($files as $key => $value) { - if (file_exists($value['name']) || file_exists($value['tmp_name'])) { - $result[$key] = $value['type']; - } elseif (empty($value['options']['ignoreNoFile'])) { - throw new Exception\InvalidArgumentException("the file '{$value['name']}' does not exist"); - } else { - continue; - } - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Internal method to detect the mime type of a file - * - * @param array $value File infos - * @return string Mimetype of given file - */ - protected function detectMimeType($value) - { - if (file_exists($value['name'])) { - $file = $value['name']; - } elseif (file_exists($value['tmp_name'])) { - $file = $value['tmp_name']; - } else { - return null; - } - - if (class_exists('finfo', false)) { - if (!empty($value['options']['magicFile'])) { - ErrorHandler::start(); - $mime = finfo_open(FILEINFO_MIME_TYPE, $value['options']['magicFile']); - ErrorHandler::stop(); - } - - if (empty($mime)) { - ErrorHandler::start(); - $mime = finfo_open(FILEINFO_MIME_TYPE); - ErrorHandler::stop(); - } - - if (!empty($mime)) { - $result = finfo_file($mime, $file); - } - - unset($mime); - } - - if (empty($result) && (function_exists('mime_content_type') - && ini_get('mime_magic.magicfile'))) { - $result = mime_content_type($file); - } - - if (empty($result)) { - $result = 'application/octet-stream'; - } - - return $result; - } - - /** - * Returns the formatted size - * - * @param int $size - * @return string - */ - protected static function toByteString($size) - { - $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - for ($i=0; $size >= 1024 && $i < 9; $i++) { - $size /= 1024; - } - - return round($size, 2) . $sizes[$i]; - } - - /** - * Internal function to filter all given files - * - * @param string|array $files (Optional) Files to check - * @return bool False on error - */ - protected function filter($files = null) - { - $check = $this->getFiles($files); - foreach ($check as $name => $content) { - if (array_key_exists('filters', $content)) { - foreach ($content['filters'] as $class) { - $filter = $this->filters[$class]; - try { - $result = $filter->filter($this->getFileName($name)); - - $this->files[$name]['destination'] = dirname($result); - $this->files[$name]['name'] = basename($result); - } catch (FilterException\ExceptionInterface $e) { - $this->messages += array($e->getMessage()); - } - } - } - } - - if (count($this->messages) > 0) { - return false; - } - - return true; - } - - /** - * Determine system TMP directory and detect if we have read access - * - * @return string - * @throws Exception\RuntimeException if unable to determine directory - */ - protected function getTmpDir() - { - if (null === $this->tmpDir) { - $tmpdir = array(); - if (function_exists('sys_get_temp_dir')) { - $tmpdir[] = sys_get_temp_dir(); - } - - if (!empty($_ENV['TMP'])) { - $tmpdir[] = realpath($_ENV['TMP']); - } - - if (!empty($_ENV['TMPDIR'])) { - $tmpdir[] = realpath($_ENV['TMPDIR']); - } - - if (!empty($_ENV['TEMP'])) { - $tmpdir[] = realpath($_ENV['TEMP']); - } - - $upload = ini_get('upload_tmp_dir'); - if ($upload) { - $tmpdir[] = realpath($upload); - } - - foreach ($tmpdir as $directory) { - if ($this->isPathWriteable($directory)) { - $this->tmpDir = $directory; - } - } - - if (empty($this->tmpDir)) { - // Attemp to detect by creating a temporary file - $tempFile = tempnam(md5(uniqid(rand(), true)), ''); - if ($tempFile) { - $this->tmpDir = realpath(dirname($tempFile)); - unlink($tempFile); - } else { - throw new Exception\RuntimeException('Could not determine a temporary directory'); - } - } - - $this->tmpDir = rtrim($this->tmpDir, "/\\"); - } - return $this->tmpDir; - } - - /** - * Tries to detect if we can read and write to the given path - * - * @param string $path - * @return bool - */ - protected function isPathWriteable($path) - { - $tempFile = rtrim($path, "/\\"); - $tempFile .= '/' . 'test.1'; - - ErrorHandler::start(); - $result = file_put_contents($tempFile, 'TEST'); - ErrorHandler::stop(); - - if ($result == false) { - return false; - } - - ErrorHandler::start(); - $result = unlink($tempFile); - ErrorHandler::stop(); - - if ($result == false) { - return false; - } - - return true; - } - - /** - * Returns found files based on internal file array and given files - * - * @param string|array $files (Optional) Files to return - * @param bool $names (Optional) Returns only names on true, else complete info - * @param bool $noexception (Optional) Allows throwing an exception, otherwise returns an empty array - * @return array Found files - * @throws Exception\RuntimeException On false filename - */ - protected function getFiles($files, $names = false, $noexception = false) - { - $check = array(); - - if (is_string($files)) { - $files = array($files); - } - - if (is_array($files)) { - foreach ($files as $find) { - $found = array(); - foreach ($this->files as $file => $content) { - if (!isset($content['name'])) { - continue; - } - - if (($content['name'] === $find) && isset($content['multifiles'])) { - foreach ($content['multifiles'] as $multifile) { - $found[] = $multifile; - } - break; - } - - if ($file === $find) { - $found[] = $file; - break; - } - - if ($content['name'] === $find) { - $found[] = $file; - break; - } - } - - if (empty($found)) { - if ($noexception !== false) { - return array(); - } - - throw new Exception\RuntimeException(sprintf('The file transfer adapter can not find "%s"', $find)); - } - - foreach ($found as $checked) { - $check[$checked] = $this->files[$checked]; - } - } - } - - if ($files === null) { - $check = $this->files; - $keys = array_keys($check); - foreach ($keys as $key) { - if (isset($check[$key]['multifiles'])) { - unset($check[$key]); - } - } - } - - if ($names) { - $check = array_keys($check); - } - - return $check; - } - - /** - * Retrieve internal identifier for a named validator - * - * @param string $name - * @return string - */ - protected function getValidatorIdentifier($name) - { - if (array_key_exists($name, $this->validators)) { - return $name; - } - - foreach (array_keys($this->validators) as $test) { - if (preg_match('/' . preg_quote($name) . '$/i', $test)) { - return $test; - } - } - - return false; - } - - /** - * Retrieve internal identifier for a named filter - * - * @param string $name - * @return string - */ - protected function getFilterIdentifier($name) - { - if (array_key_exists($name, $this->filters)) { - return $name; - } - - foreach (array_keys($this->filters) as $test) { - if (preg_match('/' . preg_quote($name) . '$/i', $test)) { - return $test; - } - } - - return false; - } -} diff --git a/library/Zend/File/Transfer/Adapter/FilterPluginManager.php b/library/Zend/File/Transfer/Adapter/FilterPluginManager.php deleted file mode 100755 index 28da7ee4a..000000000 --- a/library/Zend/File/Transfer/Adapter/FilterPluginManager.php +++ /dev/null @@ -1,35 +0,0 @@ - 'filedecrypt', - 'encrypt' => 'fileencrypt', - 'lowercase' => 'filelowercase', - 'rename' => 'filerename', - 'uppercase' => 'fileuppercase', - ); -} diff --git a/library/Zend/File/Transfer/Adapter/Http.php b/library/Zend/File/Transfer/Adapter/Http.php deleted file mode 100755 index 3cba2184d..000000000 --- a/library/Zend/File/Transfer/Adapter/Http.php +++ /dev/null @@ -1,464 +0,0 @@ -setOptions($options); - $this->prepareFiles(); - $this->addValidator('Upload', false, $this->files); - } - - /** - * Sets a validator for the class, erasing all previous set - * - * @param array $validators Validator to set - * @param string|array $files Files to limit this validator to - * @return AbstractAdapter - */ - public function setValidators(array $validators, $files = null) - { - $this->clearValidators(); - return $this->addValidators($validators, $files); - } - - /** - * Remove an individual validator - * - * @param string $name - * @return AbstractAdapter - */ - public function removeValidator($name) - { - if ($name == 'Upload') { - return $this; - } - - return parent::removeValidator($name); - } - - /** - * Clear the validators - * - * @return AbstractAdapter - */ - public function clearValidators() - { - parent::clearValidators(); - $this->addValidator('Upload', false, $this->files); - - return $this; - } - - /** - * Send the file to the client (Download) - * - * @param string|array $options Options for the file(s) to send - * @return void - * @throws Exception\BadMethodCallException Not implemented - */ - public function send($options = null) - { - throw new Exception\BadMethodCallException('Method not implemented'); - } - - /** - * Checks if the files are valid - * - * @param string|array $files (Optional) Files to check - * @return bool True if all checks are valid - */ - public function isValid($files = null) - { - // Workaround for WebServer not conforming HTTP and omitting CONTENT_LENGTH - $content = 0; - if (isset($_SERVER['CONTENT_LENGTH'])) { - $content = $_SERVER['CONTENT_LENGTH']; - } elseif (!empty($_POST)) { - $content = serialize($_POST); - } - - // Workaround for a PHP error returning empty $_FILES when form data exceeds php settings - if (empty($this->files) && ($content > 0)) { - if (is_array($files)) { - $files = current($files); - } - - $temp = array($files => array( - 'name' => $files, - 'error' => 1)); - $validator = $this->validators['Zend\Validator\File\Upload']; - $validator->setTranslator($this->getTranslator()) - ->setFiles($temp) - ->isValid($files, null); - $this->messages += $validator->getMessages(); - return false; - } - - return parent::isValid($files); - } - - /** - * Receive the file from the client (Upload) - * - * @param string|array $files (Optional) Files to receive - * @return bool - */ - public function receive($files = null) - { - if (!$this->isValid($files)) { - return false; - } - - $check = $this->getFiles($files); - foreach ($check as $file => $content) { - if (!$content['received']) { - $directory = ''; - $destination = $this->getDestination($file); - if ($destination !== null) { - $directory = $destination . DIRECTORY_SEPARATOR; - } - - $filename = $directory . $content['name']; - $rename = $this->getFilter('Rename'); - if ($rename !== null) { - $tmp = $rename->getNewName($content['tmp_name']); - if ($tmp != $content['tmp_name']) { - $filename = $tmp; - } - - if (dirname($filename) == '.') { - $filename = $directory . $filename; - } - - $key = array_search(get_class($rename), $this->files[$file]['filters']); - unset($this->files[$file]['filters'][$key]); - } - - // Should never return false when it's tested by the upload validator - if (!move_uploaded_file($content['tmp_name'], $filename)) { - if ($content['options']['ignoreNoFile']) { - $this->files[$file]['received'] = true; - $this->files[$file]['filtered'] = true; - continue; - } - - $this->files[$file]['received'] = false; - return false; - } - - if ($rename !== null) { - $this->files[$file]['destination'] = dirname($filename); - $this->files[$file]['name'] = basename($filename); - } - - $this->files[$file]['tmp_name'] = $filename; - $this->files[$file]['received'] = true; - } - - if (!$content['filtered']) { - if (!$this->filter($file)) { - $this->files[$file]['filtered'] = false; - return false; - } - - $this->files[$file]['filtered'] = true; - } - } - - return true; - } - - /** - * Checks if the file was already sent - * - * @param string|array $files Files to check - * @return bool - * @throws Exception\BadMethodCallException Not implemented - */ - public function isSent($files = null) - { - throw new Exception\BadMethodCallException('Method not implemented'); - } - - /** - * Checks if the file was already received - * - * @param string|array $files (Optional) Files to check - * @return bool - */ - public function isReceived($files = null) - { - $files = $this->getFiles($files, false, true); - if (empty($files)) { - return false; - } - - foreach ($files as $content) { - if ($content['received'] !== true) { - return false; - } - } - - return true; - } - - /** - * Checks if the file was already filtered - * - * @param string|array $files (Optional) Files to check - * @return bool - */ - public function isFiltered($files = null) - { - $files = $this->getFiles($files, false, true); - if (empty($files)) { - return false; - } - - foreach ($files as $content) { - if ($content['filtered'] !== true) { - return false; - } - } - - return true; - } - - /** - * Has a file been uploaded ? - * - * @param array|string|null $files - * @return bool - */ - public function isUploaded($files = null) - { - $files = $this->getFiles($files, false, true); - if (empty($files)) { - return false; - } - - foreach ($files as $file) { - if (empty($file['name'])) { - return false; - } - } - - return true; - } - - /** - * Returns the actual progress of file up-/downloads - * - * @param string|array $id The upload to get the progress for - * @return array|null - * @throws Exception\PhpEnvironmentException whether APC nor UploadProgress extension installed - * @throws Exception\RuntimeException - */ - public static function getProgress($id = null) - { - if (!static::isApcAvailable() && !static::isUploadProgressAvailable()) { - throw new Exception\PhpEnvironmentException('Neither APC nor UploadProgress extension installed'); - } - - $session = 'Zend\File\Transfer\Adapter\Http\ProgressBar'; - $status = array( - 'total' => 0, - 'current' => 0, - 'rate' => 0, - 'message' => '', - 'done' => false - ); - - if (is_array($id)) { - if (isset($id['progress'])) { - $adapter = $id['progress']; - } - - if (isset($id['session'])) { - $session = $id['session']; - } - - if (isset($id['id'])) { - $id = $id['id']; - } else { - unset($id); - } - } - - if (!empty($id) && (($id instanceof Adapter\AbstractAdapter) || ($id instanceof ProgressBar\ProgressBar))) { - $adapter = $id; - unset($id); - } - - if (empty($id)) { - if (!isset($_GET['progress_key'])) { - $status['message'] = 'No upload in progress'; - $status['done'] = true; - } else { - $id = $_GET['progress_key']; - } - } - - if (!empty($id)) { - if (static::isApcAvailable()) { - $call = call_user_func(static::$callbackApc, ini_get('apc.rfc1867_prefix') . $id); - if (is_array($call)) { - $status = $call + $status; - } - } elseif (static::isUploadProgressAvailable()) { - $call = call_user_func(static::$callbackUploadProgress, $id); - if (is_array($call)) { - $status = $call + $status; - $status['total'] = $status['bytes_total']; - $status['current'] = $status['bytes_uploaded']; - $status['rate'] = $status['speed_average']; - if ($status['total'] == $status['current']) { - $status['done'] = true; - } - } - } - - if (!is_array($call)) { - $status['done'] = true; - $status['message'] = 'Failure while retrieving the upload progress'; - } elseif (!empty($status['cancel_upload'])) { - $status['done'] = true; - $status['message'] = 'The upload has been canceled'; - } else { - $status['message'] = static::toByteString($status['current']) . " - " . static::toByteString($status['total']); - } - - $status['id'] = $id; - } - - if (isset($adapter) && isset($status['id'])) { - if ($adapter instanceof Adapter\AbstractAdapter) { - $adapter = new ProgressBar\ProgressBar($adapter, 0, $status['total'], $session); - } - - if (!($adapter instanceof ProgressBar\ProgressBar)) { - throw new Exception\RuntimeException('Unknown Adapter given'); - } - - if ($status['done']) { - $adapter->finish(); - } else { - $adapter->update($status['current'], $status['message']); - } - - $status['progress'] = $adapter; - } - - return $status; - } - - /** - * Checks the APC extension for progress information - * - * @return bool - */ - public static function isApcAvailable() - { - return (bool) ini_get('apc.enabled') && (bool) ini_get('apc.rfc1867') && is_callable(static::$callbackApc); - } - - /** - * Checks the UploadProgress extension for progress information - * - * @return bool - */ - public static function isUploadProgressAvailable() - { - return is_callable(static::$callbackUploadProgress); - } - - /** - * Prepare the $_FILES array to match the internal syntax of one file per entry - * - * @return Http - */ - protected function prepareFiles() - { - $this->files = array(); - foreach ($_FILES as $form => $content) { - if (is_array($content['name'])) { - foreach ($content as $param => $file) { - foreach ($file as $number => $target) { - $this->files[$form . '_' . $number . '_'][$param] = $target; - $this->files[$form]['multifiles'][$number] = $form . '_' . $number . '_'; - } - } - - $this->files[$form]['name'] = $form; - foreach ($this->files[$form]['multifiles'] as $key => $value) { - $this->files[$value]['options'] = $this->options; - $this->files[$value]['validated'] = false; - $this->files[$value]['received'] = false; - $this->files[$value]['filtered'] = false; - - $mimetype = $this->detectMimeType($this->files[$value]); - $this->files[$value]['type'] = $mimetype; - - $filesize = $this->detectFileSize($this->files[$value]); - $this->files[$value]['size'] = $filesize; - - if ($this->options['detectInfos']) { - $_FILES[$form]['type'][$key] = $mimetype; - $_FILES[$form]['size'][$key] = $filesize; - } - } - } else { - $this->files[$form] = $content; - $this->files[$form]['options'] = $this->options; - $this->files[$form]['validated'] = false; - $this->files[$form]['received'] = false; - $this->files[$form]['filtered'] = false; - - $mimetype = $this->detectMimeType($this->files[$form]); - $this->files[$form]['type'] = $mimetype; - - $filesize = $this->detectFileSize($this->files[$form]); - $this->files[$form]['size'] = $filesize; - - if ($this->options['detectInfos']) { - $_FILES[$form]['type'] = $mimetype; - $_FILES[$form]['size'] = $filesize; - } - } - } - - return $this; - } -} diff --git a/library/Zend/File/Transfer/Adapter/ValidatorPluginManager.php b/library/Zend/File/Transfer/Adapter/ValidatorPluginManager.php deleted file mode 100755 index f24f5d459..000000000 --- a/library/Zend/File/Transfer/Adapter/ValidatorPluginManager.php +++ /dev/null @@ -1,36 +0,0 @@ - 'filecount', - 'crc32' => 'filecrc32', - 'excludeextension' => 'fileexcludeextension', - 'excludemimetype' => 'fileexcludemimetype', - 'exists' => 'fileexists', - 'extension' => 'fileextension', - 'filessize' => 'filefilessize', - 'hash' => 'filehash', - 'imagesize' => 'fileimagesize', - 'iscompressed' => 'fileiscompressed', - 'isimage' => 'fileisimage', - 'md5' => 'filemd5', - 'mimetype' => 'filemimetype', - 'notexists' => 'filenotexists', - 'sha1' => 'filesha1', - 'size' => 'filesize', - 'upload' => 'fileupload', - 'wordcount' => 'filewordcount', - ); -} diff --git a/library/Zend/File/Transfer/Exception/BadMethodCallException.php b/library/Zend/File/Transfer/Exception/BadMethodCallException.php deleted file mode 100755 index 0d47a905b..000000000 --- a/library/Zend/File/Transfer/Exception/BadMethodCallException.php +++ /dev/null @@ -1,17 +0,0 @@ -setAdapter($adapter, $direction, $options); - } - - /** - * Sets a new adapter - * - * @param string $adapter Adapter to use - * @param bool $direction OPTIONAL False means Download, true means upload - * @param array $options OPTIONAL Options to set for this adapter - * @return Transfer - * @throws Exception\InvalidArgumentException - */ - public function setAdapter($adapter, $direction = false, $options = array()) - { - if (!is_string($adapter)) { - throw new Exception\InvalidArgumentException('Adapter must be a string'); - } - - if ($adapter[0] != '\\') { - $adapter = '\Zend\File\Transfer\Adapter\\' . ucfirst($adapter); - } - - $direction = (int) $direction; - $this->adapter[$direction] = new $adapter($options); - if (!$this->adapter[$direction] instanceof Adapter\AbstractAdapter) { - throw new Exception\InvalidArgumentException( - 'Adapter ' . $adapter . ' does not extend Zend\File\Transfer\Adapter\AbstractAdapter' - ); - } - - return $this; - } - - /** - * Returns all set adapters - * - * @param bool $direction On null, all directions are returned - * On false, download direction is returned - * On true, upload direction is returned - * @return array|Adapter\AbstractAdapter - */ - public function getAdapter($direction = null) - { - if ($direction === null) { - return $this->adapter; - } - - $direction = (int) $direction; - return $this->adapter[$direction]; - } - - /** - * Calls all methods from the adapter - * - * @param string $method Method to call - * @param array $options Options for this method - * @throws Exception\BadMethodCallException if unknown method - * @return mixed - */ - public function __call($method, array $options) - { - if (array_key_exists('direction', $options)) { - $direction = (int) $options['direction']; - } else { - $direction = 0; - } - - if (method_exists($this->adapter[$direction], $method)) { - return call_user_func_array(array($this->adapter[$direction], $method), $options); - } - - throw new Exception\BadMethodCallException("Unknown method '" . $method . "' called!"); - } -} diff --git a/library/Zend/File/composer.json b/library/Zend/File/composer.json deleted file mode 100755 index d3d86cea9..000000000 --- a/library/Zend/File/composer.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "zendframework/zend-file", - "description": " ", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "file" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\File\\": "" - } - }, - "target-dir": "Zend/File", - "require": { - "php": ">=5.3.23", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-filter": "self.version", - "zendframework/zend-i18n": "self.version", - "zendframework/zend-validator": "self.version" - }, - "suggest": { - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-i18n": "Zend\\I18n component", - "zendframework/zend-validator": "Zend\\Validator component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/Filter/AbstractFilter.php b/library/Zend/Filter/AbstractFilter.php deleted file mode 100755 index a52bcfa73..000000000 --- a/library/Zend/Filter/AbstractFilter.php +++ /dev/null @@ -1,96 +0,0 @@ - $value) { - $setter = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key))); - if (method_exists($this, $setter)) { - $this->{$setter}($value); - } elseif (array_key_exists($key, $this->options)) { - $this->options[$key] = $value; - } else { - throw new Exception\InvalidArgumentException(sprintf( - 'The option "%s" does not have a matching %s setter method or options[%s] array key', - $key, $setter, $key - )); - } - } - return $this; - } - - /** - * Retrieve options representing object state - * - * @return array - */ - public function getOptions() - { - return $this->options; - } - - /** - * Invoke filter as a command - * - * Proxies to {@link filter()} - * - * @param mixed $value - * @throws Exception\ExceptionInterface If filtering $value is impossible - * @return mixed - */ - public function __invoke($value) - { - return $this->filter($value); - } - - /** - * @param mixed $options - * @return bool - */ - protected static function isOptions($options) - { - return (is_array($options) || $options instanceof Traversable); - } -} diff --git a/library/Zend/Filter/AbstractUnicode.php b/library/Zend/Filter/AbstractUnicode.php deleted file mode 100755 index 685608f7d..000000000 --- a/library/Zend/Filter/AbstractUnicode.php +++ /dev/null @@ -1,59 +0,0 @@ -options['encoding'] = $encoding; - return $this; - } - - /** - * Returns the set encoding - * - * @return string - */ - public function getEncoding() - { - if ($this->options['encoding'] === null && function_exists('mb_internal_encoding')) { - $this->options['encoding'] = mb_internal_encoding(); - } - - return $this->options['encoding']; - } -} diff --git a/library/Zend/Filter/BaseName.php b/library/Zend/Filter/BaseName.php deleted file mode 100755 index 48807ca41..000000000 --- a/library/Zend/Filter/BaseName.php +++ /dev/null @@ -1,33 +0,0 @@ - 'boolean', - self::TYPE_INTEGER => 'integer', - self::TYPE_FLOAT => 'float', - self::TYPE_STRING => 'string', - self::TYPE_ZERO_STRING => 'zero', - self::TYPE_EMPTY_ARRAY => 'array', - self::TYPE_NULL => 'null', - self::TYPE_PHP => 'php', - self::TYPE_FALSE_STRING => 'false', - self::TYPE_LOCALIZED => 'localized', - self::TYPE_ALL => 'all', - ); - - /** - * @var array - */ - protected $options = array( - 'type' => self::TYPE_PHP, - 'casting' => true, - 'translations' => array(), - ); - - /** - * Constructor - * - * @param array|Traversable|int|null $typeOrOptions - * @param bool $casting - * @param array $translations - */ - public function __construct($typeOrOptions = null, $casting = true, $translations = array()) - { - if ($typeOrOptions !== null) { - if ($typeOrOptions instanceof Traversable) { - $typeOrOptions = ArrayUtils::iteratorToArray($typeOrOptions); - } - - if (is_array($typeOrOptions)) { - if (isset($typeOrOptions['type']) - || isset($typeOrOptions['casting']) - || isset($typeOrOptions['translations']) - ) { - $this->setOptions($typeOrOptions); - } else { - $this->setType($typeOrOptions); - $this->setCasting($casting); - $this->setTranslations($translations); - } - } else { - $this->setType($typeOrOptions); - $this->setCasting($casting); - $this->setTranslations($translations); - } - } - } - - /** - * Set boolean types - * - * @param int|array $type - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setType($type = null) - { - if (is_array($type)) { - $detected = 0; - foreach ($type as $value) { - if (is_int($value)) { - $detected += $value; - } elseif (in_array($value, $this->constants)) { - $detected += array_search($value, $this->constants); - } - } - - $type = $detected; - } elseif (is_string($type) && in_array($type, $this->constants)) { - $type = array_search($type, $this->constants); - } - - if (!is_int($type) || ($type < 0) || ($type > self::TYPE_ALL)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Unknown type value "%s" (%s)', - $type, - gettype($type) - )); - } - - $this->options['type'] = $type; - return $this; - } - - /** - * Returns defined boolean types - * - * @return int - */ - public function getType() - { - return $this->options['type']; - } - - /** - * Set the working mode - * - * @param bool $flag When true this filter works like cast - * When false it recognises only true and false - * and all other values are returned as is - * @return self - */ - public function setCasting($flag = true) - { - $this->options['casting'] = (bool) $flag; - return $this; - } - - /** - * Returns the casting option - * - * @return bool - */ - public function getCasting() - { - return $this->options['casting']; - } - - /** - * @param array|Traversable $translations - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setTranslations($translations) - { - if (!is_array($translations) && !$translations instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '"%s" expects an array or Traversable; received "%s"', - __METHOD__, - (is_object($translations) ? get_class($translations) : gettype($translations)) - )); - } - - foreach ($translations as $message => $flag) { - $this->options['translations'][$message] = (bool) $flag; - } - - return $this; - } - - /** - * @return array - */ - public function getTranslations() - { - return $this->options['translations']; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns a boolean representation of $value - * - * @param string $value - * @return string - */ - public function filter($value) - { - $type = $this->getType(); - $casting = $this->getCasting(); - - // LOCALIZED - if ($type >= self::TYPE_LOCALIZED) { - $type -= self::TYPE_LOCALIZED; - if (is_string($value)) { - if (isset($this->options['translations'][$value])) { - return (bool) $this->options['translations'][$value]; - } - } - } - - // FALSE_STRING ('false') - if ($type >= self::TYPE_FALSE_STRING) { - $type -= self::TYPE_FALSE_STRING; - if (is_string($value) && (strtolower($value) == 'false')) { - return false; - } - - if (!$casting && is_string($value) && (strtolower($value) == 'true')) { - return true; - } - } - - // NULL (null) - if ($type >= self::TYPE_NULL) { - $type -= self::TYPE_NULL; - if ($value === null) { - return false; - } - } - - // EMPTY_ARRAY (array()) - if ($type >= self::TYPE_EMPTY_ARRAY) { - $type -= self::TYPE_EMPTY_ARRAY; - if (is_array($value) && ($value == array())) { - return false; - } - } - - // ZERO_STRING ('0') - if ($type >= self::TYPE_ZERO_STRING) { - $type -= self::TYPE_ZERO_STRING; - if (is_string($value) && ($value == '0')) { - return false; - } - - if (!$casting && (is_string($value)) && ($value == '1')) { - return true; - } - } - - // STRING ('') - if ($type >= self::TYPE_STRING) { - $type -= self::TYPE_STRING; - if (is_string($value) && ($value == '')) { - return false; - } - } - - // FLOAT (0.0) - if ($type >= self::TYPE_FLOAT) { - $type -= self::TYPE_FLOAT; - if (is_float($value) && ($value == 0.0)) { - return false; - } - - if (!$casting && is_float($value) && ($value == 1.0)) { - return true; - } - } - - // INTEGER (0) - if ($type >= self::TYPE_INTEGER) { - $type -= self::TYPE_INTEGER; - if (is_int($value) && ($value == 0)) { - return false; - } - - if (!$casting && is_int($value) && ($value == 1)) { - return true; - } - } - - // BOOLEAN (false) - if ($type >= self::TYPE_BOOLEAN) { - $type -= self::TYPE_BOOLEAN; - if (is_bool($value)) { - return $value; - } - } - - if ($casting) { - return true; - } - - return $value; - } -} diff --git a/library/Zend/Filter/CONTRIBUTING.md b/library/Zend/Filter/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/Filter/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/Filter/Callback.php b/library/Zend/Filter/Callback.php deleted file mode 100755 index 51392e166..000000000 --- a/library/Zend/Filter/Callback.php +++ /dev/null @@ -1,102 +0,0 @@ - null, - 'callback_params' => array() - ); - - /** - * @param callable|array|Traversable $callbackOrOptions - * @param array $callbackParams - */ - public function __construct($callbackOrOptions, $callbackParams = array()) - { - if (is_callable($callbackOrOptions)) { - $this->setCallback($callbackOrOptions); - $this->setCallbackParams($callbackParams); - } else { - $this->setOptions($callbackOrOptions); - } - } - - /** - * Sets a new callback for this filter - * - * @param callable $callback - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setCallback($callback) - { - if (!is_callable($callback)) { - throw new Exception\InvalidArgumentException( - 'Invalid parameter for callback: must be callable' - ); - } - - $this->options['callback'] = $callback; - return $this; - } - - /** - * Returns the set callback - * - * @return callable - */ - public function getCallback() - { - return $this->options['callback']; - } - - /** - * Sets parameters for the callback - * - * @param array $params - * @return self - */ - public function setCallbackParams($params) - { - $this->options['callback_params'] = (array) $params; - return $this; - } - - /** - * Get parameters for the callback - * - * @return array - */ - public function getCallbackParams() - { - return $this->options['callback_params']; - } - - /** - * Calls the filter per callback - * - * @param mixed $value Options for the set callable - * @return mixed Result from the filter which was called - */ - public function filter($value) - { - $params = (array) $this->options['callback_params']; - array_unshift($params, $value); - - return call_user_func_array($this->options['callback'], $params); - } -} diff --git a/library/Zend/Filter/Compress.php b/library/Zend/Filter/Compress.php deleted file mode 100755 index f6a49e779..000000000 --- a/library/Zend/Filter/Compress.php +++ /dev/null @@ -1,210 +0,0 @@ -setAdapter($options); - } elseif ($options instanceof Compress\CompressionAlgorithmInterface) { - $this->setAdapter($options); - } elseif (is_array($options)) { - $this->setOptions($options); - } - } - - /** - * Set filter setate - * - * @param array $options - * @throws Exception\InvalidArgumentException if options is not an array or Traversable - * @return self - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '"%s" expects an array or Traversable; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $key => $value) { - if ($key == 'options') { - $key = 'adapterOptions'; - } - $method = 'set' . ucfirst($key); - if (method_exists($this, $method)) { - $this->$method($value); - } - } - return $this; - } - - /** - * Returns the current adapter, instantiating it if necessary - * - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - * @return Compress\CompressionAlgorithmInterface - */ - public function getAdapter() - { - if ($this->adapter instanceof Compress\CompressionAlgorithmInterface) { - return $this->adapter; - } - - $adapter = $this->adapter; - $options = $this->getAdapterOptions(); - if (!class_exists($adapter)) { - $adapter = 'Zend\\Filter\\Compress\\' . ucfirst($adapter); - if (!class_exists($adapter)) { - throw new Exception\RuntimeException(sprintf( - '%s unable to load adapter; class "%s" not found', - __METHOD__, - $this->adapter - )); - } - } - - $this->adapter = new $adapter($options); - if (!$this->adapter instanceof Compress\CompressionAlgorithmInterface) { - throw new Exception\InvalidArgumentException("Compression adapter '" . $adapter . "' does not implement Zend\\Filter\\Compress\\CompressionAlgorithmInterface"); - } - return $this->adapter; - } - - /** - * Retrieve adapter name - * - * @return string - */ - public function getAdapterName() - { - return $this->getAdapter()->toString(); - } - - /** - * Sets compression adapter - * - * @param string|Compress\CompressionAlgorithmInterface $adapter Adapter to use - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setAdapter($adapter) - { - if ($adapter instanceof Compress\CompressionAlgorithmInterface) { - $this->adapter = $adapter; - return $this; - } - if (!is_string($adapter)) { - throw new Exception\InvalidArgumentException('Invalid adapter provided; must be string or instance of Zend\\Filter\\Compress\\CompressionAlgorithmInterface'); - } - $this->adapter = $adapter; - - return $this; - } - - /** - * Retrieve adapter options - * - * @return array - */ - public function getAdapterOptions() - { - return $this->adapterOptions; - } - - /** - * Set adapter options - * - * @param array $options - * @return self - */ - public function setAdapterOptions(array $options) - { - $this->adapterOptions = $options; - return $this; - } - - /** - * Get individual or all options from underlying adapter - * - * @param null|string $option - * @return mixed - */ - public function getOptions($option = null) - { - $adapter = $this->getAdapter(); - return $adapter->getOptions($option); - } - - /** - * Calls adapter methods - * - * @param string $method Method to call - * @param string|array $options Options for this method - * @return mixed - * @throws Exception\BadMethodCallException - */ - public function __call($method, $options) - { - $adapter = $this->getAdapter(); - if (!method_exists($adapter, $method)) { - throw new Exception\BadMethodCallException("Unknown method '{$method}'"); - } - - return call_user_func_array(array($adapter, $method), $options); - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Compresses the content $value with the defined settings - * - * @param string $value Content to compress - * @return string The compressed content - */ - public function filter($value) - { - if (!is_string($value)) { - return $value; - } - - return $this->getAdapter()->compress($value); - } -} diff --git a/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php b/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php deleted file mode 100755 index b97e68cf1..000000000 --- a/library/Zend/Filter/Compress/AbstractCompressionAlgorithm.php +++ /dev/null @@ -1,77 +0,0 @@ -setOptions($options); - } - } - - /** - * Returns one or all set options - * - * @param string $option (Optional) Option to return - * @return mixed - */ - public function getOptions($option = null) - { - if ($option === null) { - return $this->options; - } - - if (!array_key_exists($option, $this->options)) { - return null; - } - - return $this->options[$option]; - } - - /** - * Sets all or one option - * - * @param array $options - * @return self - */ - public function setOptions(array $options) - { - foreach ($options as $key => $option) { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($option); - } - } - - return $this; - } -} diff --git a/library/Zend/Filter/Compress/Bz2.php b/library/Zend/Filter/Compress/Bz2.php deleted file mode 100755 index 79716118b..000000000 --- a/library/Zend/Filter/Compress/Bz2.php +++ /dev/null @@ -1,170 +0,0 @@ - Blocksize to use from 0-9 - * 'archive' => Archive to use - * ) - * - * @var array - */ - protected $options = array( - 'blocksize' => 4, - 'archive' => null, - ); - - /** - * Class constructor - * - * @param null|array|\Traversable $options (Optional) Options to set - * @throws Exception\ExtensionNotLoadedException if bz2 extension not loaded - */ - public function __construct($options = null) - { - if (!extension_loaded('bz2')) { - throw new Exception\ExtensionNotLoadedException('This filter needs the bz2 extension'); - } - parent::__construct($options); - } - - /** - * Returns the set blocksize - * - * @return int - */ - public function getBlocksize() - { - return $this->options['blocksize']; - } - - /** - * Sets a new blocksize - * - * @param int $blocksize - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setBlocksize($blocksize) - { - if (($blocksize < 0) || ($blocksize > 9)) { - throw new Exception\InvalidArgumentException('Blocksize must be between 0 and 9'); - } - - $this->options['blocksize'] = (int) $blocksize; - return $this; - } - - /** - * Returns the set archive - * - * @return string - */ - public function getArchive() - { - return $this->options['archive']; - } - - /** - * Sets the archive to use for de-/compression - * - * @param string $archive Archive to use - * @return self - */ - public function setArchive($archive) - { - $this->options['archive'] = (string) $archive; - return $this; - } - - /** - * Compresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException - */ - public function compress($content) - { - $archive = $this->getArchive(); - if (!empty($archive)) { - $file = bzopen($archive, 'w'); - if (!$file) { - throw new Exception\RuntimeException("Error opening the archive '" . $archive . "'"); - } - - bzwrite($file, $content); - bzclose($file); - $compressed = true; - } else { - $compressed = bzcompress($content, $this->getBlocksize()); - } - - if (is_int($compressed)) { - throw new Exception\RuntimeException('Error during compression'); - } - - return $compressed; - } - - /** - * Decompresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException - */ - public function decompress($content) - { - $archive = $this->getArchive(); - - //check if there are null byte characters before doing a file_exists check - if (!strstr($content, "\0") && file_exists($content)) { - $archive = $content; - } - - if (file_exists($archive)) { - $file = bzopen($archive, 'r'); - if (!$file) { - throw new Exception\RuntimeException("Error opening the archive '" . $content . "'"); - } - - $compressed = bzread($file); - bzclose($file); - } else { - $compressed = bzdecompress($content); - } - - if (is_int($compressed)) { - throw new Exception\RuntimeException('Error during decompression'); - } - - return $compressed; - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'Bz2'; - } -} diff --git a/library/Zend/Filter/Compress/CompressionAlgorithmInterface.php b/library/Zend/Filter/Compress/CompressionAlgorithmInterface.php deleted file mode 100755 index cf4e5f3cb..000000000 --- a/library/Zend/Filter/Compress/CompressionAlgorithmInterface.php +++ /dev/null @@ -1,39 +0,0 @@ - Compression level 0-9 - * 'mode' => Compression mode, can be 'compress', 'deflate' - * 'archive' => Archive to use - * ) - * - * @var array - */ - protected $options = array( - 'level' => 9, - 'mode' => 'compress', - 'archive' => null, - ); - - /** - * Class constructor - * - * @param null|array|\Traversable $options (Optional) Options to set - * @throws Exception\ExtensionNotLoadedException if zlib extension not loaded - */ - public function __construct($options = null) - { - if (!extension_loaded('zlib')) { - throw new Exception\ExtensionNotLoadedException('This filter needs the zlib extension'); - } - parent::__construct($options); - } - - /** - * Returns the set compression level - * - * @return int - */ - public function getLevel() - { - return $this->options['level']; - } - - /** - * Sets a new compression level - * - * @param int $level - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setLevel($level) - { - if (($level < 0) || ($level > 9)) { - throw new Exception\InvalidArgumentException('Level must be between 0 and 9'); - } - - $this->options['level'] = (int) $level; - return $this; - } - - /** - * Returns the set compression mode - * - * @return string - */ - public function getMode() - { - return $this->options['mode']; - } - - /** - * Sets a new compression mode - * - * @param string $mode Supported are 'compress', 'deflate' and 'file' - * @return self - * @throws Exception\InvalidArgumentException for invalid $mode value - */ - public function setMode($mode) - { - if (($mode != 'compress') && ($mode != 'deflate')) { - throw new Exception\InvalidArgumentException('Given compression mode not supported'); - } - - $this->options['mode'] = $mode; - return $this; - } - - /** - * Returns the set archive - * - * @return string - */ - public function getArchive() - { - return $this->options['archive']; - } - - /** - * Sets the archive to use for de-/compression - * - * @param string $archive Archive to use - * @return self - */ - public function setArchive($archive) - { - $this->options['archive'] = (string) $archive; - return $this; - } - - /** - * Compresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException if unable to open archive or error during decompression - */ - public function compress($content) - { - $archive = $this->getArchive(); - if (!empty($archive)) { - $file = gzopen($archive, 'w' . $this->getLevel()); - if (!$file) { - throw new Exception\RuntimeException("Error opening the archive '" . $this->options['archive'] . "'"); - } - - gzwrite($file, $content); - gzclose($file); - $compressed = true; - } elseif ($this->options['mode'] == 'deflate') { - $compressed = gzdeflate($content, $this->getLevel()); - } else { - $compressed = gzcompress($content, $this->getLevel()); - } - - if (!$compressed) { - throw new Exception\RuntimeException('Error during compression'); - } - - return $compressed; - } - - /** - * Decompresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException if unable to open archive or error during decompression - */ - public function decompress($content) - { - $archive = $this->getArchive(); - $mode = $this->getMode(); - - //check if there are null byte characters before doing a file_exists check - if (!strstr($content, "\0") && file_exists($content)) { - $archive = $content; - } - - if (file_exists($archive)) { - $handler = fopen($archive, "rb"); - if (!$handler) { - throw new Exception\RuntimeException("Error opening the archive '" . $archive . "'"); - } - - fseek($handler, -4, SEEK_END); - $packet = fread($handler, 4); - $bytes = unpack("V", $packet); - $size = end($bytes); - fclose($handler); - - $file = gzopen($archive, 'r'); - $compressed = gzread($file, $size); - gzclose($file); - } elseif ($mode == 'deflate') { - $compressed = gzinflate($content); - } else { - $compressed = gzuncompress($content); - } - - if ($compressed === false) { - throw new Exception\RuntimeException('Error during decompression'); - } - - return $compressed; - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'Gz'; - } -} diff --git a/library/Zend/Filter/Compress/Lzf.php b/library/Zend/Filter/Compress/Lzf.php deleted file mode 100755 index ea4fd0c60..000000000 --- a/library/Zend/Filter/Compress/Lzf.php +++ /dev/null @@ -1,75 +0,0 @@ - Callback for compression - * 'archive' => Archive to use - * 'password' => Password to use - * 'target' => Target to write the files to - * ) - * - * @var array - */ - protected $options = array( - 'callback' => null, - 'archive' => null, - 'password' => null, - 'target' => '.', - ); - - /** - * Class constructor - * - * @param array $options (Optional) Options to set - * @throws Exception\ExtensionNotLoadedException if rar extension not loaded - */ - public function __construct($options = null) - { - if (!extension_loaded('rar')) { - throw new Exception\ExtensionNotLoadedException('This filter needs the rar extension'); - } - parent::__construct($options); - } - - /** - * Returns the set callback for compression - * - * @return string - */ - public function getCallback() - { - return $this->options['callback']; - } - - /** - * Sets the callback to use - * - * @param string $callback - * @return self - * @throws Exception\InvalidArgumentException if invalid callback provided - */ - public function setCallback($callback) - { - if (!is_callable($callback)) { - throw new Exception\InvalidArgumentException('Invalid callback provided'); - } - - $this->options['callback'] = $callback; - return $this; - } - - /** - * Returns the set archive - * - * @return string - */ - public function getArchive() - { - return $this->options['archive']; - } - - /** - * Sets the archive to use for de-/compression - * - * @param string $archive Archive to use - * @return self - */ - public function setArchive($archive) - { - $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $archive); - $this->options['archive'] = (string) $archive; - - return $this; - } - - /** - * Returns the set password - * - * @return string - */ - public function getPassword() - { - return $this->options['password']; - } - - /** - * Sets the password to use - * - * @param string $password - * @return self - */ - public function setPassword($password) - { - $this->options['password'] = (string) $password; - return $this; - } - - /** - * Returns the set targetpath - * - * @return string - */ - public function getTarget() - { - return $this->options['target']; - } - - /** - * Sets the targetpath to use - * - * @param string $target - * @return self - * @throws Exception\InvalidArgumentException if specified target directory does not exist - */ - public function setTarget($target) - { - if (!file_exists(dirname($target))) { - throw new Exception\InvalidArgumentException("The directory '$target' does not exist"); - } - - $target = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $target); - $this->options['target'] = $target; - return $this; - } - - /** - * Compresses the given content - * - * @param string|array $content - * @return string - * @throws Exception\RuntimeException if no callback available, or error during compression - */ - public function compress($content) - { - $callback = $this->getCallback(); - if ($callback === null) { - throw new Exception\RuntimeException('No compression callback available'); - } - - $options = $this->getOptions(); - unset($options['callback']); - - $result = call_user_func($callback, $options, $content); - if ($result !== true) { - throw new Exception\RuntimeException('Error compressing the RAR Archive'); - } - - return $this->getArchive(); - } - - /** - * Decompresses the given content - * - * @param string $content - * @return bool - * @throws Exception\RuntimeException if archive not found, cannot be opened, - * or error during decompression - */ - public function decompress($content) - { - if (!file_exists($content)) { - throw new Exception\RuntimeException('RAR Archive not found'); - } - - $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, realpath($content)); - $password = $this->getPassword(); - if ($password !== null) { - $archive = rar_open($archive, $password); - } else { - $archive = rar_open($archive); - } - - if (!$archive) { - throw new Exception\RuntimeException("Error opening the RAR Archive"); - } - - $target = $this->getTarget(); - if (!is_dir($target)) { - $target = dirname($target); - } - - $filelist = rar_list($archive); - if (!$filelist) { - throw new Exception\RuntimeException("Error reading the RAR Archive"); - } - - foreach ($filelist as $file) { - $file->extract($target); - } - - rar_close($archive); - return true; - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'Rar'; - } -} diff --git a/library/Zend/Filter/Compress/Snappy.php b/library/Zend/Filter/Compress/Snappy.php deleted file mode 100755 index 33a9c6162..000000000 --- a/library/Zend/Filter/Compress/Snappy.php +++ /dev/null @@ -1,77 +0,0 @@ - Archive to use - * 'target' => Target to write the files to - * ) - * - * @var array - */ - protected $options = array( - 'archive' => null, - 'target' => '.', - 'mode' => null, - ); - - /** - * Class constructor - * - * @param array $options (Optional) Options to set - * @throws Exception\ExtensionNotLoadedException if Archive_Tar component not available - */ - public function __construct($options = null) - { - if (!class_exists('Archive_Tar')) { - throw new Exception\ExtensionNotLoadedException( - 'This filter needs PEAR\'s Archive_Tar component. ' - . 'Ensure loading Archive_Tar (registering autoload or require_once)'); - } - - parent::__construct($options); - } - - /** - * Returns the set archive - * - * @return string - */ - public function getArchive() - { - return $this->options['archive']; - } - - /** - * Sets the archive to use for de-/compression - * - * @param string $archive Archive to use - * @return self - */ - public function setArchive($archive) - { - $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $archive); - $this->options['archive'] = $archive; - - return $this; - } - - /** - * Returns the set target path - * - * @return string - */ - public function getTarget() - { - return $this->options['target']; - } - - /** - * Sets the target path to use - * - * @param string $target - * @return self - * @throws Exception\InvalidArgumentException if target path does not exist - */ - public function setTarget($target) - { - if (!file_exists(dirname($target))) { - throw new Exception\InvalidArgumentException("The directory '$target' does not exist"); - } - - $target = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $target); - $this->options['target'] = $target; - return $this; - } - - /** - * Returns the set compression mode - * - * @return string - */ - public function getMode() - { - return $this->options['mode']; - } - - /** - * Compression mode to use - * - * Either Gz or Bz2. - * - * @param string $mode - * @return self - * @throws Exception\InvalidArgumentException for invalid $mode values - * @throws Exception\ExtensionNotLoadedException if bz2 mode selected but extension not loaded - * @throws Exception\ExtensionNotLoadedException if gz mode selected but extension not loaded - */ - public function setMode($mode) - { - $mode = strtolower($mode); - if (($mode != 'bz2') && ($mode != 'gz')) { - throw new Exception\InvalidArgumentException("The mode '$mode' is unknown"); - } - - if (($mode == 'bz2') && (!extension_loaded('bz2'))) { - throw new Exception\ExtensionNotLoadedException('This mode needs the bz2 extension'); - } - - if (($mode == 'gz') && (!extension_loaded('zlib'))) { - throw new Exception\ExtensionNotLoadedException('This mode needs the zlib extension'); - } - - $this->options['mode'] = $mode; - return $this; - } - - /** - * Compresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException if unable to create temporary file - * @throws Exception\RuntimeException if unable to create archive - */ - public function compress($content) - { - $archive = new Archive_Tar($this->getArchive(), $this->getMode()); - if (!file_exists($content)) { - $file = $this->getTarget(); - if (is_dir($file)) { - $file .= DIRECTORY_SEPARATOR . "tar.tmp"; - } - - $result = file_put_contents($file, $content); - if ($result === false) { - throw new Exception\RuntimeException('Error creating the temporary file'); - } - - $content = $file; - } - - if (is_dir($content)) { - // collect all file infos - foreach (new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($content, RecursiveDirectoryIterator::KEY_AS_PATHNAME), - RecursiveIteratorIterator::SELF_FIRST - ) as $directory => $info - ) { - if ($info->isFile()) { - $file[] = $directory; - } - } - - $content = $file; - } - - $result = $archive->create($content); - if ($result === false) { - throw new Exception\RuntimeException('Error creating the Tar archive'); - } - - return $this->getArchive(); - } - - /** - * Decompresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException if unable to find archive - * @throws Exception\RuntimeException if error occurs decompressing archive - */ - public function decompress($content) - { - $archive = $this->getArchive(); - if (empty($archive) || !file_exists($archive)) { - throw new Exception\RuntimeException('Tar Archive not found'); - } - - $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, realpath($content)); - $archive = new Archive_Tar($archive, $this->getMode()); - $target = $this->getTarget(); - if (!is_dir($target)) { - $target = dirname($target) . DIRECTORY_SEPARATOR; - } - - $result = $archive->extract($target); - if ($result === false) { - throw new Exception\RuntimeException('Error while extracting the Tar archive'); - } - - return $target; - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'Tar'; - } -} diff --git a/library/Zend/Filter/Compress/Zip.php b/library/Zend/Filter/Compress/Zip.php deleted file mode 100755 index 5a6f01a09..000000000 --- a/library/Zend/Filter/Compress/Zip.php +++ /dev/null @@ -1,314 +0,0 @@ - Archive to use - * 'password' => Password to use - * 'target' => Target to write the files to - * ) - * - * @var array - */ - protected $options = array( - 'archive' => null, - 'target' => null, - ); - - /** - * Class constructor - * - * @param null|array|\Traversable $options (Optional) Options to set - * @throws Exception\ExtensionNotLoadedException if zip extension not loaded - */ - public function __construct($options = null) - { - if (!extension_loaded('zip')) { - throw new Exception\ExtensionNotLoadedException('This filter needs the zip extension'); - } - parent::__construct($options); - } - - /** - * Returns the set archive - * - * @return string - */ - public function getArchive() - { - return $this->options['archive']; - } - - /** - * Sets the archive to use for de-/compression - * - * @param string $archive Archive to use - * @return self - */ - public function setArchive($archive) - { - $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $archive); - $this->options['archive'] = $archive; - - return $this; - } - - /** - * Returns the set targetpath - * - * @return string - */ - public function getTarget() - { - return $this->options['target']; - } - - /** - * Sets the target to use - * - * @param string $target - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setTarget($target) - { - if (!file_exists(dirname($target))) { - throw new Exception\InvalidArgumentException("The directory '$target' does not exist"); - } - - $target = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $target); - $this->options['target'] = $target; - return $this; - } - - /** - * Compresses the given content - * - * @param string $content - * @return string Compressed archive - * @throws Exception\RuntimeException if unable to open zip archive, or error during compression - */ - public function compress($content) - { - $zip = new ZipArchive(); - $res = $zip->open($this->getArchive(), ZipArchive::CREATE | ZipArchive::OVERWRITE); - - if ($res !== true) { - throw new Exception\RuntimeException($this->errorString($res)); - } - - if (file_exists($content)) { - $content = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, realpath($content)); - $basename = substr($content, strrpos($content, DIRECTORY_SEPARATOR) + 1); - if (is_dir($content)) { - $index = strrpos($content, DIRECTORY_SEPARATOR) + 1; - $content .= DIRECTORY_SEPARATOR; - $stack = array($content); - while (!empty($stack)) { - $current = array_pop($stack); - $files = array(); - - $dir = dir($current); - while (false !== ($node = $dir->read())) { - if (($node == '.') || ($node == '..')) { - continue; - } - - if (is_dir($current . $node)) { - array_push($stack, $current . $node . DIRECTORY_SEPARATOR); - } - - if (is_file($current . $node)) { - $files[] = $node; - } - } - - $local = substr($current, $index); - $zip->addEmptyDir(substr($local, 0, -1)); - - foreach ($files as $file) { - $zip->addFile($current . $file, $local . $file); - if ($res !== true) { - throw new Exception\RuntimeException($this->errorString($res)); - } - } - } - } else { - $res = $zip->addFile($content, $basename); - if ($res !== true) { - throw new Exception\RuntimeException($this->errorString($res)); - } - } - } else { - $file = $this->getTarget(); - if (!is_dir($file)) { - $file = basename($file); - } else { - $file = "zip.tmp"; - } - - $res = $zip->addFromString($file, $content); - if ($res !== true) { - throw new Exception\RuntimeException($this->errorString($res)); - } - } - - $zip->close(); - return $this->options['archive']; - } - - /** - * Decompresses the given content - * - * @param string $content - * @return string - * @throws Exception\RuntimeException If archive file not found, target directory not found, - * or error during decompression - */ - public function decompress($content) - { - $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, realpath($content)); - - if (empty($archive) || !file_exists($archive)) { - throw new Exception\RuntimeException('ZIP Archive not found'); - } - - $zip = new ZipArchive(); - $res = $zip->open($archive); - - $target = $this->getTarget(); - if (!empty($target) && !is_dir($target)) { - $target = dirname($target); - } - - if (!empty($target)) { - $target = rtrim($target, '/\\') . DIRECTORY_SEPARATOR; - } - - if (empty($target) || !is_dir($target)) { - throw new Exception\RuntimeException('No target for ZIP decompression set'); - } - - if ($res !== true) { - throw new Exception\RuntimeException($this->errorString($res)); - } - - $res = $zip->extractTo($target); - if ($res !== true) { - throw new Exception\RuntimeException($this->errorString($res)); - } - - $zip->close(); - return $target; - } - - /** - * Returns the proper string based on the given error constant - * - * @param string $error - * @return string - */ - public function errorString($error) - { - switch ($error) { - case ZipArchive::ER_MULTIDISK : - return 'Multidisk ZIP Archives not supported'; - - case ZipArchive::ER_RENAME : - return 'Failed to rename the temporary file for ZIP'; - - case ZipArchive::ER_CLOSE : - return 'Failed to close the ZIP Archive'; - - case ZipArchive::ER_SEEK : - return 'Failure while seeking the ZIP Archive'; - - case ZipArchive::ER_READ : - return 'Failure while reading the ZIP Archive'; - - case ZipArchive::ER_WRITE : - return 'Failure while writing the ZIP Archive'; - - case ZipArchive::ER_CRC : - return 'CRC failure within the ZIP Archive'; - - case ZipArchive::ER_ZIPCLOSED : - return 'ZIP Archive already closed'; - - case ZipArchive::ER_NOENT : - return 'No such file within the ZIP Archive'; - - case ZipArchive::ER_EXISTS : - return 'ZIP Archive already exists'; - - case ZipArchive::ER_OPEN : - return 'Can not open ZIP Archive'; - - case ZipArchive::ER_TMPOPEN : - return 'Failure creating temporary ZIP Archive'; - - case ZipArchive::ER_ZLIB : - return 'ZLib Problem'; - - case ZipArchive::ER_MEMORY : - return 'Memory allocation problem while working on a ZIP Archive'; - - case ZipArchive::ER_CHANGED : - return 'ZIP Entry has been changed'; - - case ZipArchive::ER_COMPNOTSUPP : - return 'Compression method not supported within ZLib'; - - case ZipArchive::ER_EOF : - return 'Premature EOF within ZIP Archive'; - - case ZipArchive::ER_INVAL : - return 'Invalid argument for ZLIB'; - - case ZipArchive::ER_NOZIP : - return 'Given file is no zip archive'; - - case ZipArchive::ER_INTERNAL : - return 'Internal error while working on a ZIP Archive'; - - case ZipArchive::ER_INCONS : - return 'Inconsistent ZIP archive'; - - case ZipArchive::ER_REMOVE : - return 'Can not remove ZIP Archive'; - - case ZipArchive::ER_DELETED : - return 'ZIP Entry has been deleted'; - - default : - return 'Unknown error within ZIP Archive'; - } - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'Zip'; - } -} diff --git a/library/Zend/Filter/DateTimeFormatter.php b/library/Zend/Filter/DateTimeFormatter.php deleted file mode 100755 index b24897b2f..000000000 --- a/library/Zend/Filter/DateTimeFormatter.php +++ /dev/null @@ -1,96 +0,0 @@ -setOptions($options); - } - } - - /** - * Set the format string accepted by date() to use when formatting a string - * - * @param string $format - * @return self - */ - public function setFormat($format) - { - $this->format = $format; - - return $this; - } - - /** - * Filter a datetime string by normalizing it to the filters specified format - * - * @param DateTime|string|integer $value - * @throws Exception\InvalidArgumentException - * @return string - */ - public function filter($value) - { - try { - $result = $this->normalizeDateTime($value); - } catch (\Exception $e) { - // DateTime threw an exception, an invalid date string was provided - throw new Exception\InvalidArgumentException('Invalid date string provided', $e->getCode(), $e); - } - - if ($result === false) { - return $value; - } - - return $result; - } - - /** - * Normalize the provided value to a formatted string - * - * @param string|int|DateTime $value - * @return string - */ - protected function normalizeDateTime($value) - { - if ($value === '' || $value === null) { - return $value; - } - - if (!is_string($value) && !is_int($value) && !$value instanceof DateTime) { - return $value; - } - - if (is_int($value)) { - //timestamp - $value = new DateTime('@' . $value); - } elseif (!$value instanceof DateTime) { - $value = new DateTime($value); - } - - return $value->format($this->format); - } -} diff --git a/library/Zend/Filter/Decompress.php b/library/Zend/Filter/Decompress.php deleted file mode 100755 index 3489c70c1..000000000 --- a/library/Zend/Filter/Decompress.php +++ /dev/null @@ -1,46 +0,0 @@ -filter($value); - } - - /** - * Defined by FilterInterface - * - * Decompresses the content $value with the defined settings - * - * @param string $value Content to decompress - * @return string The decompressed content - */ - public function filter($value) - { - if (!is_string($value) && $value !== null) { - return $value; - } - - return $this->getAdapter()->decompress($value); - } -} diff --git a/library/Zend/Filter/Decrypt.php b/library/Zend/Filter/Decrypt.php deleted file mode 100755 index 9c8e8492b..000000000 --- a/library/Zend/Filter/Decrypt.php +++ /dev/null @@ -1,33 +0,0 @@ -adapter->decrypt($value); - } -} diff --git a/library/Zend/Filter/Digits.php b/library/Zend/Filter/Digits.php deleted file mode 100755 index c5e856fbd..000000000 --- a/library/Zend/Filter/Digits.php +++ /dev/null @@ -1,49 +0,0 @@ -setAdapter($options); - } - - /** - * Returns the name of the set adapter - * @todo inconsitent: get adapter should return the adapter and not the name - * - * @return string - */ - public function getAdapter() - { - return $this->adapter->toString(); - } - - /** - * Sets new encryption options - * - * @param string|array $options (Optional) Encryption options - * @return self - * @throws Exception\DomainException - * @throws Exception\InvalidArgumentException - */ - public function setAdapter($options = null) - { - if (is_string($options)) { - $adapter = $options; - } elseif (isset($options['adapter'])) { - $adapter = $options['adapter']; - unset($options['adapter']); - } else { - $adapter = 'BlockCipher'; - } - - if (!is_array($options)) { - $options = array(); - } - - if (class_exists('Zend\Filter\Encrypt\\' . ucfirst($adapter))) { - $adapter = 'Zend\Filter\Encrypt\\' . ucfirst($adapter); - } elseif (!class_exists($adapter)) { - throw new Exception\DomainException( - sprintf('%s expects a valid registry class name; received "%s", which did not resolve', - __METHOD__, - $adapter - )); - } - - $this->adapter = new $adapter($options); - if (!$this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) { - throw new Exception\InvalidArgumentException( - "Encoding adapter '" . $adapter - . "' does not implement Zend\\Filter\\Encrypt\\EncryptionAlgorithmInterface"); - } - - return $this; - } - - /** - * Calls adapter methods - * - * @param string $method Method to call - * @param string|array $options Options for this method - * @return mixed - * @throws Exception\BadMethodCallException - */ - public function __call($method, $options) - { - $part = substr($method, 0, 3); - if ((($part != 'get') && ($part != 'set')) || !method_exists($this->adapter, $method)) { - throw new Exception\BadMethodCallException("Unknown method '{$method}'"); - } - - return call_user_func_array(array($this->adapter, $method), $options); - } - - /** - * Defined by Zend\Filter\Filter - * - * Encrypts the content $value with the defined settings - * - * @param string $value Content to encrypt - * @return string The encrypted content - */ - public function filter($value) - { - if (!is_string($value)) { - return $value; - } - - return $this->adapter->encrypt($value); - } -} diff --git a/library/Zend/Filter/Encrypt/BlockCipher.php b/library/Zend/Filter/Encrypt/BlockCipher.php deleted file mode 100755 index 5b7c13664..000000000 --- a/library/Zend/Filter/Encrypt/BlockCipher.php +++ /dev/null @@ -1,288 +0,0 @@ - encryption key string - * 'key_iteration' => the number of iterations for the PBKDF2 key generation - * 'algorithm => cipher algorithm to use - * 'hash' => algorithm to use for the authentication - * 'vector' => initialization vector - * ) - */ - protected $encryption = array( - 'key_iteration' => 5000, - 'algorithm' => 'aes', - 'hash' => 'sha256', - ); - - /** - * BlockCipher - * - * @var BlockCipher - */ - protected $blockCipher; - - /** - * Internal compression - * - * @var array - */ - protected $compression; - - /** - * Class constructor - * - * @param string|array|Traversable $options Encryption Options - * @throws Exception\RuntimeException - * @throws Exception\InvalidArgumentException - */ - public function __construct($options) - { - try { - $this->blockCipher = CryptBlockCipher::factory('mcrypt', $this->encryption); - } catch (SymmetricException\RuntimeException $e) { - throw new Exception\RuntimeException('The BlockCipher cannot be used without the Mcrypt extension'); - } - - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } elseif (is_string($options)) { - $options = array('key' => $options); - } elseif (!is_array($options)) { - throw new Exception\InvalidArgumentException('Invalid options argument provided to filter'); - } - - if (array_key_exists('compression', $options)) { - $this->setCompression($options['compression']); - unset($options['compress']); - } - - $this->setEncryption($options); - } - - /** - * Returns the set encryption options - * - * @return array - */ - public function getEncryption() - { - return $this->encryption; - } - - /** - * Sets new encryption options - * - * @param string|array $options Encryption options - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setEncryption($options) - { - if (is_string($options)) { - $this->blockCipher->setKey($options); - $this->encryption['key'] = $options; - return $this; - } - - if (!is_array($options)) { - throw new Exception\InvalidArgumentException('Invalid options argument provided to filter'); - } - - $options = $options + $this->encryption; - - if (isset($options['key'])) { - $this->blockCipher->setKey($options['key']); - } - - if (isset($options['algorithm'])) { - try { - $this->blockCipher->setCipherAlgorithm($options['algorithm']); - } catch (CryptException\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException("The algorithm '{$options['algorithm']}' is not supported"); - } - } - - if (isset($options['hash'])) { - try { - $this->blockCipher->setHashAlgorithm($options['hash']); - } catch (CryptException\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException("The algorithm '{$options['hash']}' is not supported"); - } - } - - if (isset($options['vector'])) { - $this->setVector($options['vector']); - } - - if (isset($options['key_iteration'])) { - $this->blockCipher->setKeyIteration($options['key_iteration']); - } - - $this->encryption = $options; - - return $this; - } - - /** - * Returns the initialization vector - * - * @return string - */ - public function getVector() - { - return $this->encryption['vector']; - } - - /** - * Set the inizialization vector - * - * @param string $vector - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setVector($vector) - { - try { - $this->blockCipher->setSalt($vector); - } catch (CryptException\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException($e->getMessage()); - } - $this->encryption['vector'] = $vector; - return $this; - } - - /** - * Set the encryption key - * - * @param string $key - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setKey($key) - { - try { - $this->blockCipher->setKey($key); - } catch (CryptException\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException($e->getMessage()); - } - $this->encryption['key'] = $key; - return $this; - } - - /** - * Get the encryption key - * - * @return string - */ - public function getKey() - { - return $this->encryption['key']; - } - - /** - * Returns the compression - * - * @return array - */ - public function getCompression() - { - return $this->compression; - } - - /** - * Sets an internal compression for values to encrypt - * - * @param string|array $compression - * @return self - */ - public function setCompression($compression) - { - if (is_string($this->compression)) { - $compression = array('adapter' => $compression); - } - - $this->compression = $compression; - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Encrypts $value with the defined settings - * - * @param string $value The content to encrypt - * @throws Exception\InvalidArgumentException - * @return string The encrypted content - */ - public function encrypt($value) - { - // compress prior to encryption - if (!empty($this->compression)) { - $compress = new Compress($this->compression); - $value = $compress($value); - } - - try { - $encrypted = $this->blockCipher->encrypt($value); - } catch (CryptException\InvalidArgumentException $e) { - throw new Exception\InvalidArgumentException($e->getMessage()); - } - return $encrypted; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Decrypts $value with the defined settings - * - * @param string $value Content to decrypt - * @return string The decrypted content - */ - public function decrypt($value) - { - $decrypted = $this->blockCipher->decrypt($value); - - // decompress after decryption - if (!empty($this->compression)) { - $decompress = new Decompress($this->compression); - $decrypted = $decompress($decrypted); - } - - return $decrypted; - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'BlockCipher'; - } -} diff --git a/library/Zend/Filter/Encrypt/EncryptionAlgorithmInterface.php b/library/Zend/Filter/Encrypt/EncryptionAlgorithmInterface.php deleted file mode 100755 index faf0c518c..000000000 --- a/library/Zend/Filter/Encrypt/EncryptionAlgorithmInterface.php +++ /dev/null @@ -1,39 +0,0 @@ - public keys - * 'private' => private keys - * 'envelope' => resulting envelope keys - * ) - */ - protected $keys = array( - 'public' => array(), - 'private' => array(), - 'envelope' => array(), - ); - - /** - * Internal passphrase - * - * @var string - */ - protected $passphrase; - - /** - * Internal compression - * - * @var array - */ - protected $compression; - - /** - * Internal create package - * - * @var bool - */ - protected $package = false; - - /** - * Class constructor - * Available options - * 'public' => public key - * 'private' => private key - * 'envelope' => envelope key - * 'passphrase' => passphrase - * 'compression' => compress value with this compression adapter - * 'package' => pack envelope keys into encrypted string, simplifies decryption - * - * @param string|array|Traversable $options Options for this adapter - * @throws Exception\ExtensionNotLoadedException - */ - public function __construct($options = array()) - { - if (!extension_loaded('openssl')) { - throw new Exception\ExtensionNotLoadedException('This filter needs the openssl extension'); - } - - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (!is_array($options)) { - $options = array('public' => $options); - } - - if (array_key_exists('passphrase', $options)) { - $this->setPassphrase($options['passphrase']); - unset($options['passphrase']); - } - - if (array_key_exists('compression', $options)) { - $this->setCompression($options['compression']); - unset($options['compress']); - } - - if (array_key_exists('package', $options)) { - $this->setPackage($options['package']); - unset($options['package']); - } - - $this->_setKeys($options); - } - - /** - * Sets the encryption keys - * - * @param string|array $keys Key with type association - * @return self - * @throws Exception\InvalidArgumentException - */ - protected function _setKeys($keys) - { - if (!is_array($keys)) { - throw new Exception\InvalidArgumentException('Invalid options argument provided to filter'); - } - - foreach ($keys as $type => $key) { - if (is_file($key) and is_readable($key)) { - $file = fopen($key, 'r'); - $cert = fread($file, 8192); - fclose($file); - } else { - $cert = $key; - $key = count($this->keys[$type]); - } - - switch ($type) { - case 'public': - $test = openssl_pkey_get_public($cert); - if ($test === false) { - throw new Exception\InvalidArgumentException("Public key '{$cert}' not valid"); - } - - openssl_free_key($test); - $this->keys['public'][$key] = $cert; - break; - case 'private': - $test = openssl_pkey_get_private($cert, $this->passphrase); - if ($test === false) { - throw new Exception\InvalidArgumentException("Private key '{$cert}' not valid"); - } - - openssl_free_key($test); - $this->keys['private'][$key] = $cert; - break; - case 'envelope': - $this->keys['envelope'][$key] = $cert; - break; - default: - break; - } - } - - return $this; - } - - /** - * Returns all public keys - * - * @return array - */ - public function getPublicKey() - { - $key = $this->keys['public']; - return $key; - } - - /** - * Sets public keys - * - * @param string|array $key Public keys - * @return self - */ - public function setPublicKey($key) - { - if (is_array($key)) { - foreach ($key as $type => $option) { - if ($type !== 'public') { - $key['public'] = $option; - unset($key[$type]); - } - } - } else { - $key = array('public' => $key); - } - - return $this->_setKeys($key); - } - - /** - * Returns all private keys - * - * @return array - */ - public function getPrivateKey() - { - $key = $this->keys['private']; - return $key; - } - - /** - * Sets private keys - * - * @param string $key Private key - * @param string $passphrase - * @return self - */ - public function setPrivateKey($key, $passphrase = null) - { - if (is_array($key)) { - foreach ($key as $type => $option) { - if ($type !== 'private') { - $key['private'] = $option; - unset($key[$type]); - } - } - } else { - $key = array('private' => $key); - } - - if ($passphrase !== null) { - $this->setPassphrase($passphrase); - } - - return $this->_setKeys($key); - } - - /** - * Returns all envelope keys - * - * @return array - */ - public function getEnvelopeKey() - { - $key = $this->keys['envelope']; - return $key; - } - - /** - * Sets envelope keys - * - * @param string|array $key Envelope keys - * @return self - */ - public function setEnvelopeKey($key) - { - if (is_array($key)) { - foreach ($key as $type => $option) { - if ($type !== 'envelope') { - $key['envelope'] = $option; - unset($key[$type]); - } - } - } else { - $key = array('envelope' => $key); - } - - return $this->_setKeys($key); - } - - /** - * Returns the passphrase - * - * @return string - */ - public function getPassphrase() - { - return $this->passphrase; - } - - /** - * Sets a new passphrase - * - * @param string $passphrase - * @return self - */ - public function setPassphrase($passphrase) - { - $this->passphrase = $passphrase; - return $this; - } - - /** - * Returns the compression - * - * @return array - */ - public function getCompression() - { - return $this->compression; - } - - /** - * Sets an internal compression for values to encrypt - * - * @param string|array $compression - * @return self - */ - public function setCompression($compression) - { - if (is_string($this->compression)) { - $compression = array('adapter' => $compression); - } - - $this->compression = $compression; - return $this; - } - - /** - * Returns if header should be packaged - * - * @return bool - */ - public function getPackage() - { - return $this->package; - } - - /** - * Sets if the envelope keys should be included in the encrypted value - * - * @param bool $package - * @return self - */ - public function setPackage($package) - { - $this->package = (bool) $package; - return $this; - } - - /** - * Encrypts $value with the defined settings - * Note that you also need the "encrypted" keys to be able to decrypt - * - * @param string $value Content to encrypt - * @return string The encrypted content - * @throws Exception\RuntimeException - */ - public function encrypt($value) - { - $encrypted = array(); - $encryptedkeys = array(); - - if (count($this->keys['public']) == 0) { - throw new Exception\RuntimeException('Openssl can not encrypt without public keys'); - } - - $keys = array(); - $fingerprints = array(); - $count = -1; - foreach ($this->keys['public'] as $key => $cert) { - $keys[$key] = openssl_pkey_get_public($cert); - if ($this->package) { - $details = openssl_pkey_get_details($keys[$key]); - if ($details === false) { - $details = array('key' => 'ZendFramework'); - } - - ++$count; - $fingerprints[$count] = md5($details['key']); - } - } - - // compress prior to encryption - if (!empty($this->compression)) { - $compress = new Compress($this->compression); - $value = $compress($value); - } - - $crypt = openssl_seal($value, $encrypted, $encryptedkeys, $keys); - foreach ($keys as $key) { - openssl_free_key($key); - } - - if ($crypt === false) { - throw new Exception\RuntimeException('Openssl was not able to encrypt your content with the given options'); - } - - $this->keys['envelope'] = $encryptedkeys; - - // Pack data and envelope keys into single string - if ($this->package) { - $header = pack('n', count($this->keys['envelope'])); - foreach ($this->keys['envelope'] as $key => $envKey) { - $header .= pack('H32n', $fingerprints[$key], strlen($envKey)) . $envKey; - } - - $encrypted = $header . $encrypted; - } - - return $encrypted; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Decrypts $value with the defined settings - * - * @param string $value Content to decrypt - * @return string The decrypted content - * @throws Exception\RuntimeException - */ - public function decrypt($value) - { - $decrypted = ""; - $envelope = current($this->getEnvelopeKey()); - - if (count($this->keys['private']) !== 1) { - throw new Exception\RuntimeException('Please give a private key for decryption with Openssl'); - } - - if (!$this->package && empty($envelope)) { - throw new Exception\RuntimeException('Please give an envelope key for decryption with Openssl'); - } - - foreach ($this->keys['private'] as $cert) { - $keys = openssl_pkey_get_private($cert, $this->getPassphrase()); - } - - if ($this->package) { - $details = openssl_pkey_get_details($keys); - if ($details !== false) { - $fingerprint = md5($details['key']); - } else { - $fingerprint = md5("ZendFramework"); - } - - $count = unpack('ncount', $value); - $count = $count['count']; - $length = 2; - for ($i = $count; $i > 0; --$i) { - $header = unpack('H32print/nsize', substr($value, $length, 18)); - $length += 18; - if ($header['print'] == $fingerprint) { - $envelope = substr($value, $length, $header['size']); - } - - $length += $header['size']; - } - - // remainder of string is the value to decrypt - $value = substr($value, $length); - } - - $crypt = openssl_open($value, $decrypted, $envelope, $keys); - openssl_free_key($keys); - - if ($crypt === false) { - throw new Exception\RuntimeException('Openssl was not able to decrypt you content with the given options'); - } - - // decompress after decryption - if (!empty($this->compression)) { - $decompress = new Decompress($this->compression); - $decrypted = $decompress($decrypted); - } - - return $decrypted; - } - - /** - * Returns the adapter name - * - * @return string - */ - public function toString() - { - return 'Openssl'; - } -} diff --git a/library/Zend/Filter/Exception/BadMethodCallException.php b/library/Zend/Filter/Exception/BadMethodCallException.php deleted file mode 100755 index ae0d3f843..000000000 --- a/library/Zend/Filter/Exception/BadMethodCallException.php +++ /dev/null @@ -1,14 +0,0 @@ -filename; - } - - /** - * Sets the new filename where the content will be stored - * - * @param string $filename (Optional) New filename to set - * @return self - */ - public function setFilename($filename = null) - { - $this->filename = $filename; - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Decrypts the file $value with the defined settings - * - * @param string|array $value Full path of file to change or $_FILES data array - * @return string|array The filename which has been set - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public function filter($value) - { - if (!is_scalar($value) && !is_array($value)) { - return $value; - } - - // An uploaded file? Retrieve the 'tmp_name' - $isFileUpload = false; - if (is_array($value)) { - if (!isset($value['tmp_name'])) { - return $value; - } - - $isFileUpload = true; - $uploadData = $value; - $value = $value['tmp_name']; - } - - - if (!file_exists($value)) { - throw new Exception\InvalidArgumentException("File '$value' not found"); - } - - if (!isset($this->filename)) { - $this->filename = $value; - } - - if (file_exists($this->filename) and !is_writable($this->filename)) { - throw new Exception\RuntimeException("File '{$this->filename}' is not writable"); - } - - $content = file_get_contents($value); - if (!$content) { - throw new Exception\RuntimeException("Problem while reading file '$value'"); - } - - $decrypted = parent::filter($content); - $result = file_put_contents($this->filename, $decrypted); - - if (!$result) { - throw new Exception\RuntimeException("Problem while writing file '{$this->filename}'"); - } - - if ($isFileUpload) { - $uploadData['tmp_name'] = $this->filename; - return $uploadData; - } - return $this->filename; - } -} diff --git a/library/Zend/Filter/File/Encrypt.php b/library/Zend/Filter/File/Encrypt.php deleted file mode 100755 index 9e32b4ce7..000000000 --- a/library/Zend/Filter/File/Encrypt.php +++ /dev/null @@ -1,107 +0,0 @@ -filename; - } - - /** - * Sets the new filename where the content will be stored - * - * @param string $filename (Optional) New filename to set - * @return self - */ - public function setFilename($filename = null) - { - $this->filename = $filename; - return $this; - } - - /** - * Defined by Zend\Filter\Filter - * - * Encrypts the file $value with the defined settings - * - * @param string|array $value Full path of file to change or $_FILES data array - * @return string|array The filename which has been set, or false when there were errors - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException - */ - public function filter($value) - { - if (!is_scalar($value) && !is_array($value)) { - return $value; - } - - // An uploaded file? Retrieve the 'tmp_name' - $isFileUpload = false; - if (is_array($value)) { - if (!isset($value['tmp_name'])) { - return $value; - } - - $isFileUpload = true; - $uploadData = $value; - $value = $value['tmp_name']; - } - - if (!file_exists($value)) { - throw new Exception\InvalidArgumentException("File '$value' not found"); - } - - if (!isset($this->filename)) { - $this->filename = $value; - } - - if (file_exists($this->filename) and !is_writable($this->filename)) { - throw new Exception\RuntimeException("File '{$this->filename}' is not writable"); - } - - $content = file_get_contents($value); - if (!$content) { - throw new Exception\RuntimeException("Problem while reading file '$value'"); - } - - $encrypted = parent::filter($content); - $result = file_put_contents($this->filename, $encrypted); - - if (!$result) { - throw new Exception\RuntimeException("Problem while writing file '{$this->filename}'"); - } - - if ($isFileUpload) { - $uploadData['tmp_name'] = $this->filename; - return $uploadData; - } - return $this->filename; - } -} diff --git a/library/Zend/Filter/File/LowerCase.php b/library/Zend/Filter/File/LowerCase.php deleted file mode 100755 index 15d31482e..000000000 --- a/library/Zend/Filter/File/LowerCase.php +++ /dev/null @@ -1,70 +0,0 @@ - Source filename or directory which will be renamed - * 'target' => Target filename or directory, the new name of the source file - * 'overwrite' => Shall existing files be overwritten ? - * 'randomize' => Shall target files have a random postfix attached? - * - * @param string|array|Traversable $options Target file or directory to be renamed - * @throws Exception\InvalidArgumentException - */ - public function __construct($options) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } elseif (is_string($options)) { - $options = array('target' => $options); - } elseif (!is_array($options)) { - throw new Exception\InvalidArgumentException( - 'Invalid options argument provided to filter' - ); - } - - $this->setFile($options); - } - - /** - * Returns the files to rename and their new name and location - * - * @return array - */ - public function getFile() - { - return $this->files; - } - - /** - * Sets a new file or directory as target, deleting existing ones - * - * Array accepts the following keys: - * 'source' => Source filename or directory which will be renamed - * 'target' => Target filename or directory, the new name of the sourcefile - * 'overwrite' => Shall existing files be overwritten? - * 'randomize' => Shall target files have a random postfix attached? - * - * @param string|array $options Old file or directory to be rewritten - * @return self - */ - public function setFile($options) - { - $this->files = array(); - $this->addFile($options); - - return $this; - } - - /** - * Adds a new file or directory as target to the existing ones - * - * Array accepts the following keys: - * 'source' => Source filename or directory which will be renamed - * 'target' => Target filename or directory, the new name of the sourcefile - * 'overwrite' => Shall existing files be overwritten? - * 'randomize' => Shall target files have a random postfix attached? - * - * @param string|array $options Old file or directory to be rewritten - * @return Rename - * @throws Exception\InvalidArgumentException - */ - public function addFile($options) - { - if (is_string($options)) { - $options = array('target' => $options); - } elseif (!is_array($options)) { - throw new Exception\InvalidArgumentException( - 'Invalid options to rename filter provided' - ); - } - - $this->_convertOptions($options); - - return $this; - } - - /** - * Returns only the new filename without moving it - * But existing files will be erased when the overwrite option is true - * - * @param string $value Full path of file to change - * @param bool $source Return internal informations - * @return string The new filename which has been set - * @throws Exception\InvalidArgumentException If the target file already exists. - */ - public function getNewName($value, $source = false) - { - $file = $this->_getFileName($value); - if (!is_array($file)) { - return $file; - } - - if ($file['source'] == $file['target']) { - return $value; - } - - if (!file_exists($file['source'])) { - return $value; - } - - if ($file['overwrite'] && file_exists($file['target'])) { - unlink($file['target']); - } - - if (file_exists($file['target'])) { - throw new Exception\InvalidArgumentException( - sprintf("File '%s' could not be renamed. It already exists.", $value) - ); - } - - if ($source) { - return $file; - } - - return $file['target']; - } - - /** - * Defined by Zend\Filter\Filter - * - * Renames the file $value to the new name set before - * Returns the file $value, removing all but digit characters - * - * @param string|array $value Full path of file to change or $_FILES data array - * @throws Exception\RuntimeException - * @return string|array The new filename which has been set - */ - public function filter($value) - { - if (!is_scalar($value) && !is_array($value)) { - return $value; - } - - // An uploaded file? Retrieve the 'tmp_name' - $isFileUpload = false; - if (is_array($value)) { - if (!isset($value['tmp_name'])) { - return $value; - } - - $isFileUpload = true; - $uploadData = $value; - $value = $value['tmp_name']; - } - - $file = $this->getNewName($value, true); - if (is_string($file)) { - if ($isFileUpload) { - return $uploadData; - } else { - return $file; - } - } - - $result = rename($file['source'], $file['target']); - - if ($result !== true) { - throw new Exception\RuntimeException( - sprintf( - "File '%s' could not be renamed. " . - "An error occurred while processing the file.", - $value - ) - ); - } - - if ($isFileUpload) { - $uploadData['tmp_name'] = $file['target']; - return $uploadData; - } - return $file['target']; - } - - /** - * Internal method for creating the file array - * Supports single and nested arrays - * - * @param array $options - * @return array - */ - protected function _convertOptions($options) - { - $files = array(); - foreach ($options as $key => $value) { - if (is_array($value)) { - $this->_convertOptions($value); - continue; - } - - switch ($key) { - case "source": - $files['source'] = (string) $value; - break; - - case 'target' : - $files['target'] = (string) $value; - break; - - case 'overwrite' : - $files['overwrite'] = (bool) $value; - break; - - case 'randomize' : - $files['randomize'] = (bool) $value; - break; - - default: - break; - } - } - - if (empty($files)) { - return $this; - } - - if (empty($files['source'])) { - $files['source'] = '*'; - } - - if (empty($files['target'])) { - $files['target'] = '*'; - } - - if (empty($files['overwrite'])) { - $files['overwrite'] = false; - } - - if (empty($files['randomize'])) { - $files['randomize'] = false; - } - - $found = false; - foreach ($this->files as $key => $value) { - if ($value['source'] == $files['source']) { - $this->files[$key] = $files; - $found = true; - } - } - - if (!$found) { - $count = count($this->files); - $this->files[$count] = $files; - } - - return $this; - } - - /** - * Internal method to resolve the requested source - * and return all other related parameters - * - * @param string $file Filename to get the informations for - * @return array|string - */ - protected function _getFileName($file) - { - $rename = array(); - foreach ($this->files as $value) { - if ($value['source'] == '*') { - if (!isset($rename['source'])) { - $rename = $value; - $rename['source'] = $file; - } - } - - if ($value['source'] == $file) { - $rename = $value; - break; - } - } - - if (!isset($rename['source'])) { - return $file; - } - - if (!isset($rename['target']) || $rename['target'] == '*') { - $rename['target'] = $rename['source']; - } - - if (is_dir($rename['target'])) { - $name = basename($rename['source']); - $last = $rename['target'][strlen($rename['target']) - 1]; - if (($last != '/') && ($last != '\\')) { - $rename['target'] .= DIRECTORY_SEPARATOR; - } - - $rename['target'] .= $name; - } - - if ($rename['randomize']) { - $info = pathinfo($rename['target']); - $newTarget = $info['dirname'] . DIRECTORY_SEPARATOR . - $info['filename'] . uniqid('_'); - if (isset($info['extension'])) { - $newTarget .= '.' . $info['extension']; - } - $rename['target'] = $newTarget; - } - - return $rename; - } -} diff --git a/library/Zend/Filter/File/RenameUpload.php b/library/Zend/Filter/File/RenameUpload.php deleted file mode 100755 index e0b5d0b5e..000000000 --- a/library/Zend/Filter/File/RenameUpload.php +++ /dev/null @@ -1,313 +0,0 @@ - null, - 'use_upload_name' => false, - 'use_upload_extension' => false, - 'overwrite' => false, - 'randomize' => false, - ); - - /** - * Store already filtered values, so we can filter multiple - * times the same file without being block by move_uploaded_file - * internal checks - * - * @var array - */ - protected $alreadyFiltered = array(); - - /** - * Constructor - * - * @param array|string $targetOrOptions The target file path or an options array - */ - public function __construct($targetOrOptions) - { - if (is_array($targetOrOptions)) { - $this->setOptions($targetOrOptions); - } else { - $this->setTarget($targetOrOptions); - } - } - - /** - * @param string $target Target file path or directory - * @return self - */ - public function setTarget($target) - { - if (!is_string($target)) { - throw new Exception\InvalidArgumentException( - 'Invalid target, must be a string' - ); - } - $this->options['target'] = $target; - return $this; - } - - /** - * @return string Target file path or directory - */ - public function getTarget() - { - return $this->options['target']; - } - - /** - * @param bool $flag When true, this filter will use the $_FILES['name'] - * as the target filename. - * Otherwise, it uses the default 'target' rules. - * @return self - */ - public function setUseUploadName($flag = true) - { - $this->options['use_upload_name'] = (bool) $flag; - return $this; - } - - /** - * @return bool - */ - public function getUseUploadName() - { - return $this->options['use_upload_name']; - } - - /** - * @param bool $flag When true, this filter will use the original file - * extension for the target filename - * @return self - */ - public function setUseUploadExtension($flag = true) - { - $this->options['use_upload_extension'] = (bool) $flag; - return $this; - } - - /** - * @return bool - */ - public function getUseUploadExtension() - { - return $this->options['use_upload_extension']; - } - - /** - * @param bool $flag Shall existing files be overwritten? - * @return self - */ - public function setOverwrite($flag = true) - { - $this->options['overwrite'] = (bool) $flag; - return $this; - } - - /** - * @return bool - */ - public function getOverwrite() - { - return $this->options['overwrite']; - } - - /** - * @param bool $flag Shall target files have a random postfix attached? - * @return self - */ - public function setRandomize($flag = true) - { - $this->options['randomize'] = (bool) $flag; - return $this; - } - - /** - * @return bool - */ - public function getRandomize() - { - return $this->options['randomize']; - } - - /** - * Defined by Zend\Filter\Filter - * - * Renames the file $value to the new name set before - * Returns the file $value, removing all but digit characters - * - * @param string|array $value Full path of file to change or $_FILES data array - * @throws Exception\RuntimeException - * @return string|array The new filename which has been set, or false when there were errors - */ - public function filter($value) - { - if (!is_scalar($value) && !is_array($value)) { - return $value; - } - - // An uploaded file? Retrieve the 'tmp_name' - $isFileUpload = false; - if (is_array($value)) { - if (!isset($value['tmp_name'])) { - return $value; - } - - $isFileUpload = true; - $uploadData = $value; - $sourceFile = $value['tmp_name']; - } else { - $uploadData = array( - 'tmp_name' => $value, - 'name' => $value, - ); - $sourceFile = $value; - } - - if (isset($this->alreadyFiltered[$sourceFile])) { - return $this->alreadyFiltered[$sourceFile]; - } - - $targetFile = $this->getFinalTarget($uploadData); - if (!file_exists($sourceFile) || $sourceFile == $targetFile) { - return $value; - } - - $this->checkFileExists($targetFile); - $this->moveUploadedFile($sourceFile, $targetFile); - - $return = $targetFile; - if ($isFileUpload) { - $return = $uploadData; - $return['tmp_name'] = $targetFile; - } - - $this->alreadyFiltered[$sourceFile] = $return; - - return $return; - } - - /** - * @param string $sourceFile Source file path - * @param string $targetFile Target file path - * @throws Exception\RuntimeException - * @return bool - */ - protected function moveUploadedFile($sourceFile, $targetFile) - { - ErrorHandler::start(); - $result = move_uploaded_file($sourceFile, $targetFile); - $warningException = ErrorHandler::stop(); - if (!$result || null !== $warningException) { - throw new Exception\RuntimeException( - sprintf("File '%s' could not be renamed. An error occurred while processing the file.", $sourceFile), - 0, $warningException - ); - } - - return $result; - } - - /** - * @param string $targetFile Target file path - * @throws Exception\InvalidArgumentException - */ - protected function checkFileExists($targetFile) - { - if (file_exists($targetFile)) { - if ($this->getOverwrite()) { - unlink($targetFile); - } else { - throw new Exception\InvalidArgumentException( - sprintf("File '%s' could not be renamed. It already exists.", $targetFile) - ); - } - } - } - - /** - * @param array $uploadData $_FILES array - * @return string - */ - protected function getFinalTarget($uploadData) - { - $source = $uploadData['tmp_name']; - $target = $this->getTarget(); - if (!isset($target) || $target == '*') { - $target = $source; - } - - // Get the target directory - if (is_dir($target)) { - $targetDir = $target; - $last = $target[strlen($target) - 1]; - if (($last != '/') && ($last != '\\')) { - $targetDir .= DIRECTORY_SEPARATOR; - } - } else { - $info = pathinfo($target); - $targetDir = $info['dirname'] . DIRECTORY_SEPARATOR; - } - - // Get the target filename - if ($this->getUseUploadName()) { - $targetFile = basename($uploadData['name']); - } elseif (!is_dir($target)) { - $targetFile = basename($target); - if ($this->getUseUploadExtension() && !$this->getRandomize()) { - $targetInfo = pathinfo($targetFile); - $sourceinfo = pathinfo($uploadData['name']); - if (isset($sourceinfo['extension'])) { - $targetFile = $targetInfo['filename'] . '.' . $sourceinfo['extension']; - } - } - } else { - $targetFile = basename($source); - } - - if ($this->getRandomize()) { - $targetFile = $this->applyRandomToFilename($uploadData['name'], $targetFile); - } - - return $targetDir . $targetFile; - } - - /** - * @param string $source - * @param string $filename - * @return string - */ - protected function applyRandomToFilename($source, $filename) - { - $info = pathinfo($filename); - $filename = $info['filename'] . uniqid('_'); - - $sourceinfo = pathinfo($source); - - $extension = ''; - if ($this->getUseUploadExtension() === true && isset($sourceinfo['extension'])) { - $extension .= '.' . $sourceinfo['extension']; - } elseif (isset($info['extension'])) { - $extension .= '.' . $info['extension']; - } - - return $filename . $extension; - } -} diff --git a/library/Zend/Filter/File/UpperCase.php b/library/Zend/Filter/File/UpperCase.php deleted file mode 100755 index 22bf09279..000000000 --- a/library/Zend/Filter/File/UpperCase.php +++ /dev/null @@ -1,70 +0,0 @@ -filters = new PriorityQueue(); - - if (null !== $options) { - $this->setOptions($options); - } - } - - /** - * @param array|Traversable $options - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - 'Expected array or Traversable; received "%s"', - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $key => $value) { - switch (strtolower($key)) { - case 'callbacks': - foreach ($value as $spec) { - $callback = isset($spec['callback']) ? $spec['callback'] : false; - $priority = isset($spec['priority']) ? $spec['priority'] : static::DEFAULT_PRIORITY; - if ($callback) { - $this->attach($callback, $priority); - } - } - break; - case 'filters': - foreach ($value as $spec) { - $name = isset($spec['name']) ? $spec['name'] : false; - $options = isset($spec['options']) ? $spec['options'] : array(); - $priority = isset($spec['priority']) ? $spec['priority'] : static::DEFAULT_PRIORITY; - if ($name) { - $this->attachByName($name, $options, $priority); - } - } - break; - default: - // ignore other options - break; - } - } - - return $this; - } - - /** - * Return the count of attached filters - * - * @return int - */ - public function count() - { - return count($this->filters); - } - - /** - * Get plugin manager instance - * - * @return FilterPluginManager - */ - public function getPluginManager() - { - if (!$this->plugins) { - $this->setPluginManager(new FilterPluginManager()); - } - return $this->plugins; - } - - /** - * Set plugin manager instance - * - * @param FilterPluginManager $plugins - * @return self - */ - public function setPluginManager(FilterPluginManager $plugins) - { - $this->plugins = $plugins; - return $this; - } - - /** - * Retrieve a filter plugin by name - * - * @param mixed $name - * @param array $options - * @return FilterInterface - */ - public function plugin($name, array $options = array()) - { - $plugins = $this->getPluginManager(); - return $plugins->get($name, $options); - } - - /** - * Attach a filter to the chain - * - * @param callable|FilterInterface $callback A Filter implementation or valid PHP callback - * @param int $priority Priority at which to enqueue filter; defaults to 1000 (higher executes earlier) - * @throws Exception\InvalidArgumentException - * @return self - */ - public function attach($callback, $priority = self::DEFAULT_PRIORITY) - { - if (!is_callable($callback)) { - if (!$callback instanceof FilterInterface) { - throw new Exception\InvalidArgumentException(sprintf( - 'Expected a valid PHP callback; received "%s"', - (is_object($callback) ? get_class($callback) : gettype($callback)) - )); - } - $callback = array($callback, 'filter'); - } - $this->filters->insert($callback, $priority); - return $this; - } - - /** - * Attach a filter to the chain using a short name - * - * Retrieves the filter from the attached plugin manager, and then calls attach() - * with the retrieved instance. - * - * @param string $name - * @param mixed $options - * @param int $priority Priority at which to enqueue filter; defaults to 1000 (higher executes earlier) - * @return self - */ - public function attachByName($name, $options = array(), $priority = self::DEFAULT_PRIORITY) - { - if (!is_array($options)) { - $options = (array) $options; - } elseif (empty($options)) { - $options = null; - } - $filter = $this->getPluginManager()->get($name, $options); - return $this->attach($filter, $priority); - } - - /** - * Merge the filter chain with the one given in parameter - * - * @param FilterChain $filterChain - * @return self - */ - public function merge(FilterChain $filterChain) - { - foreach ($filterChain->filters->toArray(PriorityQueue::EXTR_BOTH) as $item) { - $this->attach($item['data'], $item['priority']); - } - - return $this; - } - - /** - * Get all the filters - * - * @return PriorityQueue - */ - public function getFilters() - { - return $this->filters; - } - - /** - * Returns $value filtered through each filter in the chain - * - * Filters are run in the order in which they were added to the chain (FIFO) - * - * @param mixed $value - * @return mixed - */ - public function filter($value) - { - $chain = clone $this->filters; - - $valueFiltered = $value; - foreach ($chain as $filter) { - $valueFiltered = call_user_func($filter, $valueFiltered); - } - - return $valueFiltered; - } - - /** - * Clone filters - */ - public function __clone() - { - $this->filters = clone $this->filters; - } - - /** - * Prepare filter chain for serialization - * - * Plugin manager (property 'plugins') cannot - * be serialized. On wakeup the property remains unset - * and next invocation to getPluginManager() sets - * the default plugin manager instance (FilterPluginManager). - */ - public function __sleep() - { - return array('filters'); - } -} diff --git a/library/Zend/Filter/FilterInterface.php b/library/Zend/Filter/FilterInterface.php deleted file mode 100755 index 2b3c16353..000000000 --- a/library/Zend/Filter/FilterInterface.php +++ /dev/null @@ -1,22 +0,0 @@ - 'Zend\I18n\Filter\Alnum', - 'alpha' => 'Zend\I18n\Filter\Alpha', - 'basename' => 'Zend\Filter\BaseName', - 'boolean' => 'Zend\Filter\Boolean', - 'callback' => 'Zend\Filter\Callback', - 'compress' => 'Zend\Filter\Compress', - 'compressbz2' => 'Zend\Filter\Compress\Bz2', - 'compressgz' => 'Zend\Filter\Compress\Gz', - 'compresslzf' => 'Zend\Filter\Compress\Lzf', - 'compressrar' => 'Zend\Filter\Compress\Rar', - 'compresssnappy' => 'Zend\Filter\Compress\Snappy', - 'compresstar' => 'Zend\Filter\Compress\Tar', - 'compresszip' => 'Zend\Filter\Compress\Zip', - 'datetimeformatter' => 'Zend\Filter\DateTimeFormatter', - 'decompress' => 'Zend\Filter\Decompress', - 'decrypt' => 'Zend\Filter\Decrypt', - 'digits' => 'Zend\Filter\Digits', - 'dir' => 'Zend\Filter\Dir', - 'encrypt' => 'Zend\Filter\Encrypt', - 'encryptblockcipher' => 'Zend\Filter\Encrypt\BlockCipher', - 'encryptopenssl' => 'Zend\Filter\Encrypt\Openssl', - 'filedecrypt' => 'Zend\Filter\File\Decrypt', - 'fileencrypt' => 'Zend\Filter\File\Encrypt', - 'filelowercase' => 'Zend\Filter\File\LowerCase', - 'filerename' => 'Zend\Filter\File\Rename', - 'filerenameupload' => 'Zend\Filter\File\RenameUpload', - 'fileuppercase' => 'Zend\Filter\File\UpperCase', - 'htmlentities' => 'Zend\Filter\HtmlEntities', - 'inflector' => 'Zend\Filter\Inflector', - 'int' => 'Zend\Filter\Int', - 'null' => 'Zend\Filter\Null', - 'numberformat' => 'Zend\I18n\Filter\NumberFormat', - 'numberparse' => 'Zend\I18n\Filter\NumberParse', - 'pregreplace' => 'Zend\Filter\PregReplace', - 'realpath' => 'Zend\Filter\RealPath', - 'stringtolower' => 'Zend\Filter\StringToLower', - 'stringtoupper' => 'Zend\Filter\StringToUpper', - 'stringtrim' => 'Zend\Filter\StringTrim', - 'stripnewlines' => 'Zend\Filter\StripNewlines', - 'striptags' => 'Zend\Filter\StripTags', - 'urinormalize' => 'Zend\Filter\UriNormalize', - 'wordcamelcasetodash' => 'Zend\Filter\Word\CamelCaseToDash', - 'wordcamelcasetoseparator' => 'Zend\Filter\Word\CamelCaseToSeparator', - 'wordcamelcasetounderscore' => 'Zend\Filter\Word\CamelCaseToUnderscore', - 'worddashtocamelcase' => 'Zend\Filter\Word\DashToCamelCase', - 'worddashtoseparator' => 'Zend\Filter\Word\DashToSeparator', - 'worddashtounderscore' => 'Zend\Filter\Word\DashToUnderscore', - 'wordseparatortocamelcase' => 'Zend\Filter\Word\SeparatorToCamelCase', - 'wordseparatortodash' => 'Zend\Filter\Word\SeparatorToDash', - 'wordseparatortoseparator' => 'Zend\Filter\Word\SeparatorToSeparator', - 'wordunderscoretocamelcase' => 'Zend\Filter\Word\UnderscoreToCamelCase', - 'wordunderscoretodash' => 'Zend\Filter\Word\UnderscoreToDash', - 'wordunderscoretoseparator' => 'Zend\Filter\Word\UnderscoreToSeparator', - ); - - /** - * Whether or not to share by default; default to false - * - * @var bool - */ - protected $shareByDefault = false; - - /** - * Validate the plugin - * - * Checks that the filter loaded is either a valid callback or an instance - * of FilterInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\RuntimeException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof FilterInterface) { - // we're okay - return; - } - if (is_callable($plugin)) { - // also okay - return; - } - - throw new Exception\RuntimeException(sprintf( - 'Plugin of type %s is invalid; must implement %s\FilterInterface or be callable', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/Filter/HtmlEntities.php b/library/Zend/Filter/HtmlEntities.php deleted file mode 100755 index 2abff010b..000000000 --- a/library/Zend/Filter/HtmlEntities.php +++ /dev/null @@ -1,203 +0,0 @@ -setQuoteStyle($options['quotestyle']); - $this->setEncoding($options['encoding']); - $this->setDoubleQuote($options['doublequote']); - } - - /** - * Returns the quoteStyle option - * - * @return int - */ - public function getQuoteStyle() - { - return $this->quoteStyle; - } - - /** - * Sets the quoteStyle option - * - * @param int $quoteStyle - * @return self Provides a fluent interface - */ - public function setQuoteStyle($quoteStyle) - { - $this->quoteStyle = $quoteStyle; - return $this; - } - - - /** - * Get encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set encoding - * - * @param string $value - * @return self - */ - public function setEncoding($value) - { - $this->encoding = (string) $value; - return $this; - } - - /** - * Returns the charSet option - * - * Proxies to {@link getEncoding()} - * - * @return string - */ - public function getCharSet() - { - return $this->getEncoding(); - } - - /** - * Sets the charSet option - * - * Proxies to {@link setEncoding()} - * - * @param string $charSet - * @return self Provides a fluent interface - */ - public function setCharSet($charSet) - { - return $this->setEncoding($charSet); - } - - /** - * Returns the doubleQuote option - * - * @return bool - */ - public function getDoubleQuote() - { - return $this->doubleQuote; - } - - /** - * Sets the doubleQuote option - * - * @param bool $doubleQuote - * @return self Provides a fluent interface - */ - public function setDoubleQuote($doubleQuote) - { - $this->doubleQuote = (bool) $doubleQuote; - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns the string $value, converting characters to their corresponding HTML entity - * equivalents where they exist - * - * If the value provided is non-scalar, the value will remain unfiltered - * - * @param string $value - * @return string|mixed - * @throws Exception\DomainException on encoding mismatches - */ - public function filter($value) - { - if (!is_scalar($value)) { - return $value; - } - $value = (string) $value; - - $filtered = htmlentities($value, $this->getQuoteStyle(), $this->getEncoding(), $this->getDoubleQuote()); - if (strlen($value) && !strlen($filtered)) { - if (!function_exists('iconv')) { - throw new Exception\DomainException('Encoding mismatch has resulted in htmlentities errors'); - } - $enc = $this->getEncoding(); - $value = iconv('', $this->getEncoding() . '//IGNORE', $value); - $filtered = htmlentities($value, $this->getQuoteStyle(), $enc, $this->getDoubleQuote()); - if (!strlen($filtered)) { - throw new Exception\DomainException('Encoding mismatch has resulted in htmlentities errors'); - } - } - return $filtered; - } -} diff --git a/library/Zend/Filter/Inflector.php b/library/Zend/Filter/Inflector.php deleted file mode 100755 index 4120a68f2..000000000 --- a/library/Zend/Filter/Inflector.php +++ /dev/null @@ -1,472 +0,0 @@ -setOptions($options); - } - - /** - * Retrieve plugin manager - * - * @return FilterPluginManager - */ - public function getPluginManager() - { - if (!$this->pluginManager instanceof FilterPluginManager) { - $this->setPluginManager(new FilterPluginManager()); - } - - return $this->pluginManager; - } - - /** - * Set plugin manager - * - * @param FilterPluginManager $manager - * @return self - */ - public function setPluginManager(FilterPluginManager $manager) - { - $this->pluginManager = $manager; - return $this; - } - - /** - * Set options - * - * @param array|Traversable $options - * @return self - */ - public function setOptions($options) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - // Set plugin manager - if (array_key_exists('pluginManager', $options)) { - if (is_scalar($options['pluginManager']) && class_exists($options['pluginManager'])) { - $options['pluginManager'] = new $options['pluginManager']; - } - $this->setPluginManager($options['pluginManager']); - } - - if (array_key_exists('throwTargetExceptionsOn', $options)) { - $this->setThrowTargetExceptionsOn($options['throwTargetExceptionsOn']); - } - - if (array_key_exists('targetReplacementIdentifier', $options)) { - $this->setTargetReplacementIdentifier($options['targetReplacementIdentifier']); - } - - if (array_key_exists('target', $options)) { - $this->setTarget($options['target']); - } - - if (array_key_exists('rules', $options)) { - $this->addRules($options['rules']); - } - - return $this; - } - - /** - * Set Whether or not the inflector should throw an exception when a replacement - * identifier is still found within an inflected target. - * - * @param bool $throwTargetExceptionsOn - * @return self - */ - public function setThrowTargetExceptionsOn($throwTargetExceptionsOn) - { - $this->throwTargetExceptionsOn = ($throwTargetExceptionsOn == true) ? true : false; - return $this; - } - - /** - * Will exceptions be thrown? - * - * @return bool - */ - public function isThrowTargetExceptionsOn() - { - return $this->throwTargetExceptionsOn; - } - - /** - * Set the Target Replacement Identifier, by default ':' - * - * @param string $targetReplacementIdentifier - * @return self - */ - public function setTargetReplacementIdentifier($targetReplacementIdentifier) - { - if ($targetReplacementIdentifier) { - $this->targetReplacementIdentifier = (string) $targetReplacementIdentifier; - } - - return $this; - } - - /** - * Get Target Replacement Identifier - * - * @return string - */ - public function getTargetReplacementIdentifier() - { - return $this->targetReplacementIdentifier; - } - - /** - * Set a Target - * ex: 'scripts/:controller/:action.:suffix' - * - * @param string $target - * @return self - */ - public function setTarget($target) - { - $this->target = (string) $target; - return $this; - } - - /** - * Retrieve target - * - * @return string - */ - public function getTarget() - { - return $this->target; - } - - /** - * Set Target Reference - * - * @param string $target - * @return self - */ - public function setTargetReference(&$target) - { - $this->target =& $target; - return $this; - } - - /** - * Is the same as calling addRules() with the exception that it - * clears the rules before adding them. - * - * @param array $rules - * @return self - */ - public function setRules(array $rules) - { - $this->clearRules(); - $this->addRules($rules); - return $this; - } - - /** - * Multi-call to setting filter rules. - * - * If prefixed with a ":" (colon), a filter rule will be added. If not - * prefixed, a static replacement will be added. - * - * ex: - * array( - * ':controller' => array('CamelCaseToUnderscore', 'StringToLower'), - * ':action' => array('CamelCaseToUnderscore', 'StringToLower'), - * 'suffix' => 'phtml' - * ); - * - * @param array $rules - * @return self - */ - public function addRules(array $rules) - { - $keys = array_keys($rules); - foreach ($keys as $spec) { - if ($spec[0] == ':') { - $this->addFilterRule($spec, $rules[$spec]); - } else { - $this->setStaticRule($spec, $rules[$spec]); - } - } - - return $this; - } - - /** - * Get rules - * - * By default, returns all rules. If a $spec is provided, will return those - * rules if found, false otherwise. - * - * @param string $spec - * @return array|false - */ - public function getRules($spec = null) - { - if (null !== $spec) { - $spec = $this->_normalizeSpec($spec); - if (isset($this->rules[$spec])) { - return $this->rules[$spec]; - } - return false; - } - - return $this->rules; - } - - /** - * Returns a rule set by setFilterRule(), a numeric index must be provided - * - * @param string $spec - * @param int $index - * @return FilterInterface|false - */ - public function getRule($spec, $index) - { - $spec = $this->_normalizeSpec($spec); - if (isset($this->rules[$spec]) && is_array($this->rules[$spec])) { - if (isset($this->rules[$spec][$index])) { - return $this->rules[$spec][$index]; - } - } - return false; - } - - /** - * Clears the rules currently in the inflector - * - * @return self - */ - public function clearRules() - { - $this->rules = array(); - return $this; - } - - /** - * Set a filtering rule for a spec. $ruleSet can be a string, Filter object - * or an array of strings or filter objects. - * - * @param string $spec - * @param array|string|\Zend\Filter\FilterInterface $ruleSet - * @return self - */ - public function setFilterRule($spec, $ruleSet) - { - $spec = $this->_normalizeSpec($spec); - $this->rules[$spec] = array(); - return $this->addFilterRule($spec, $ruleSet); - } - - /** - * Add a filter rule for a spec - * - * @param mixed $spec - * @param mixed $ruleSet - * @return self - */ - public function addFilterRule($spec, $ruleSet) - { - $spec = $this->_normalizeSpec($spec); - if (!isset($this->rules[$spec])) { - $this->rules[$spec] = array(); - } - - if (!is_array($ruleSet)) { - $ruleSet = array($ruleSet); - } - - if (is_string($this->rules[$spec])) { - $temp = $this->rules[$spec]; - $this->rules[$spec] = array(); - $this->rules[$spec][] = $temp; - } - - foreach ($ruleSet as $rule) { - $this->rules[$spec][] = $this->_getRule($rule); - } - - return $this; - } - - /** - * Set a static rule for a spec. This is a single string value - * - * @param string $name - * @param string $value - * @return self - */ - public function setStaticRule($name, $value) - { - $name = $this->_normalizeSpec($name); - $this->rules[$name] = (string) $value; - return $this; - } - - /** - * Set Static Rule Reference. - * - * This allows a consuming class to pass a property or variable - * in to be referenced when its time to build the output string from the - * target. - * - * @param string $name - * @param mixed $reference - * @return self - */ - public function setStaticRuleReference($name, &$reference) - { - $name = $this->_normalizeSpec($name); - $this->rules[$name] =& $reference; - return $this; - } - - /** - * Inflect - * - * @param string|array $source - * @throws Exception\RuntimeException - * @return string - */ - public function filter($source) - { - // clean source - foreach ((array) $source as $sourceName => $sourceValue) { - $source[ltrim($sourceName, ':')] = $sourceValue; - } - - $pregQuotedTargetReplacementIdentifier = preg_quote($this->targetReplacementIdentifier, '#'); - $processedParts = array(); - - foreach ($this->rules as $ruleName => $ruleValue) { - if (isset($source[$ruleName])) { - if (is_string($ruleValue)) { - // overriding the set rule - $processedParts['#' . $pregQuotedTargetReplacementIdentifier . $ruleName . '#'] = str_replace('\\', '\\\\', $source[$ruleName]); - } elseif (is_array($ruleValue)) { - $processedPart = $source[$ruleName]; - foreach ($ruleValue as $ruleFilter) { - $processedPart = $ruleFilter($processedPart); - } - $processedParts['#' . $pregQuotedTargetReplacementIdentifier . $ruleName . '#'] = str_replace('\\', '\\\\', $processedPart); - } - } elseif (is_string($ruleValue)) { - $processedParts['#' . $pregQuotedTargetReplacementIdentifier . $ruleName . '#'] = str_replace('\\', '\\\\', $ruleValue); - } - } - - // all of the values of processedParts would have been str_replace('\\', '\\\\', ..)'d to disable preg_replace backreferences - $inflectedTarget = preg_replace(array_keys($processedParts), array_values($processedParts), $this->target); - - if ($this->throwTargetExceptionsOn && (preg_match('#(?=' . $pregQuotedTargetReplacementIdentifier.'[A-Za-z]{1})#', $inflectedTarget) == true)) { - throw new Exception\RuntimeException('A replacement identifier ' . $this->targetReplacementIdentifier . ' was found inside the inflected target, perhaps a rule was not satisfied with a target source? Unsatisfied inflected target: ' . $inflectedTarget); - } - - return $inflectedTarget; - } - - /** - * Normalize spec string - * - * @param string $spec - * @return string - */ - protected function _normalizeSpec($spec) - { - return ltrim((string) $spec, ':&'); - } - - /** - * Resolve named filters and convert them to filter objects. - * - * @param string $rule - * @return FilterInterface - */ - protected function _getRule($rule) - { - if ($rule instanceof FilterInterface) { - return $rule; - } - - $rule = (string) $rule; - return $this->getPluginManager()->get($rule); - } -} diff --git a/library/Zend/Filter/Int.php b/library/Zend/Filter/Int.php deleted file mode 100755 index 0f2b80dba..000000000 --- a/library/Zend/Filter/Int.php +++ /dev/null @@ -1,33 +0,0 @@ - 'boolean', - self::TYPE_INTEGER => 'integer', - self::TYPE_EMPTY_ARRAY => 'array', - self::TYPE_STRING => 'string', - self::TYPE_ZERO_STRING => 'zero', - self::TYPE_FLOAT => 'float', - self::TYPE_ALL => 'all', - ); - - /** - * @var array - */ - protected $options = array( - 'type' => self::TYPE_ALL, - ); - - /** - * Constructor - * - * @param string|array|Traversable $typeOrOptions OPTIONAL - */ - public function __construct($typeOrOptions = null) - { - if ($typeOrOptions !== null) { - if ($typeOrOptions instanceof Traversable) { - $typeOrOptions = iterator_to_array($typeOrOptions); - } - - if (is_array($typeOrOptions)) { - if (isset($typeOrOptions['type'])) { - $this->setOptions($typeOrOptions); - } else { - $this->setType($typeOrOptions); - } - } else { - $this->setType($typeOrOptions); - } - } - } - - /** - * Set boolean types - * - * @param int|array $type - * @throws Exception\InvalidArgumentException - * @return self - */ - public function setType($type = null) - { - if (is_array($type)) { - $detected = 0; - foreach ($type as $value) { - if (is_int($value)) { - $detected += $value; - } elseif (in_array($value, $this->constants)) { - $detected += array_search($value, $this->constants); - } - } - - $type = $detected; - } elseif (is_string($type) && in_array($type, $this->constants)) { - $type = array_search($type, $this->constants); - } - - if (!is_int($type) || ($type < 0) || ($type > self::TYPE_ALL)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Unknown type value "%s" (%s)', - $type, - gettype($type) - )); - } - - $this->options['type'] = $type; - return $this; - } - - /** - * Returns defined boolean types - * - * @return int - */ - public function getType() - { - return $this->options['type']; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns null representation of $value, if value is empty and matches - * types that should be considered null. - * - * @param string $value - * @return string - */ - public function filter($value) - { - $type = $this->getType(); - - // FLOAT (0.0) - if ($type >= self::TYPE_FLOAT) { - $type -= self::TYPE_FLOAT; - if (is_float($value) && ($value == 0.0)) { - return null; - } - } - - // STRING ZERO ('0') - if ($type >= self::TYPE_ZERO_STRING) { - $type -= self::TYPE_ZERO_STRING; - if (is_string($value) && ($value == '0')) { - return null; - } - } - - // STRING ('') - if ($type >= self::TYPE_STRING) { - $type -= self::TYPE_STRING; - if (is_string($value) && ($value == '')) { - return null; - } - } - - // EMPTY_ARRAY (array()) - if ($type >= self::TYPE_EMPTY_ARRAY) { - $type -= self::TYPE_EMPTY_ARRAY; - if (is_array($value) && ($value == array())) { - return null; - } - } - - // INTEGER (0) - if ($type >= self::TYPE_INTEGER) { - $type -= self::TYPE_INTEGER; - if (is_int($value) && ($value == 0)) { - return null; - } - } - - // BOOLEAN (false) - if ($type >= self::TYPE_BOOLEAN) { - $type -= self::TYPE_BOOLEAN; - if (is_bool($value) && ($value == false)) { - return null; - } - } - - return $value; - } -} diff --git a/library/Zend/Filter/PregReplace.php b/library/Zend/Filter/PregReplace.php deleted file mode 100755 index 9a7e3f3ad..000000000 --- a/library/Zend/Filter/PregReplace.php +++ /dev/null @@ -1,166 +0,0 @@ - null, - 'replacement' => '', - ); - - /** - * Constructor - * Supported options are - * 'pattern' => matching pattern - * 'replacement' => replace with this - * - * @param array|Traversable|string|null $options - */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = iterator_to_array($options); - } - - if (!is_array($options) - || (!isset($options['pattern']) && !isset($options['replacement'])) - ) { - $args = func_get_args(); - if (isset($args[0])) { - $this->setPattern($args[0]); - } - if (isset($args[1])) { - $this->setReplacement($args[1]); - } - } else { - $this->setOptions($options); - } - } - - /** - * Set the regex pattern to search for - * @see preg_replace() - * - * @param string|array $pattern - same as the first argument of preg_replace - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setPattern($pattern) - { - if (!is_array($pattern) && !is_string($pattern)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects pattern to be array or string; received "%s"', - __METHOD__, - (is_object($pattern) ? get_class($pattern) : gettype($pattern)) - )); - } - - if (is_array($pattern)) { - foreach ($pattern as $p) { - $this->validatePattern($p); - } - } - - if (is_string($pattern)) { - $this->validatePattern($pattern); - } - - $this->options['pattern'] = $pattern; - return $this; - } - - /** - * Get currently set match pattern - * - * @return string|array - */ - public function getPattern() - { - return $this->options['pattern']; - } - - /** - * Set the replacement array/string - * @see preg_replace() - * - * @param array|string $replacement - same as the second argument of preg_replace - * @return self - * @throws Exception\InvalidArgumentException - */ - public function setReplacement($replacement) - { - if (!is_array($replacement) && !is_string($replacement)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects replacement to be array or string; received "%s"', - __METHOD__, - (is_object($replacement) ? get_class($replacement) : gettype($replacement)) - )); - } - $this->options['replacement'] = $replacement; - return $this; - } - - /** - * Get currently set replacement value - * - * @return string|array - */ - public function getReplacement() - { - return $this->options['replacement']; - } - - /** - * Perform regexp replacement as filter - * - * @param mixed $value - * @return mixed - * @throws Exception\RuntimeException - */ - public function filter($value) - { - if (!is_scalar($value) && !is_array($value)) { - return $value; - } - - if ($this->options['pattern'] === null) { - throw new Exception\RuntimeException(sprintf( - 'Filter %s does not have a valid pattern set', - get_class($this) - )); - } - - return preg_replace($this->options['pattern'], $this->options['replacement'], $value); - } - - /** - * Validate a pattern and ensure it does not contain the "e" modifier - * - * @param string $pattern - * @return bool - * @throws Exception\InvalidArgumentException - */ - protected function validatePattern($pattern) - { - if (!preg_match('/(?[imsxeADSUXJu]+)$/', $pattern, $matches)) { - return true; - } - - if (false !== strstr($matches['modifier'], 'e')) { - throw new Exception\InvalidArgumentException(sprintf( - 'Pattern for a PregReplace filter may not contain the "e" pattern modifier; received "%s"', - $pattern - )); - } - } -} diff --git a/library/Zend/Filter/README.md b/library/Zend/Filter/README.md deleted file mode 100755 index 2aeb60bf2..000000000 --- a/library/Zend/Filter/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Filter Component from ZF2 -========================= - -This is the Filter component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/Filter/RealPath.php b/library/Zend/Filter/RealPath.php deleted file mode 100755 index 00633d5c9..000000000 --- a/library/Zend/Filter/RealPath.php +++ /dev/null @@ -1,122 +0,0 @@ - true - ); - - /** - * Class constructor - * - * @param bool|Traversable $existsOrOptions Options to set - */ - public function __construct($existsOrOptions = true) - { - if ($existsOrOptions !== null) { - if (!static::isOptions($existsOrOptions)) { - $this->setExists($existsOrOptions); - } else { - $this->setOptions($existsOrOptions); - } - } - } - - /** - * Sets if the path has to exist - * TRUE when the path must exist - * FALSE when not existing paths can be given - * - * @param bool $flag Path must exist - * @return self - */ - public function setExists($flag = true) - { - $this->options['exists'] = (bool) $flag; - return $this; - } - - /** - * Returns true if the filtered path must exist - * - * @return bool - */ - public function getExists() - { - return $this->options['exists']; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns realpath($value) - * - * If the value provided is non-scalar, the value will remain unfiltered - * - * @param string $value - * @return string|mixed - */ - public function filter($value) - { - if (!is_string($value)) { - return $value; - } - $path = (string) $value; - - if ($this->options['exists']) { - return realpath($path); - } - - ErrorHandler::start(); - $realpath = realpath($path); - ErrorHandler::stop(); - if ($realpath) { - return $realpath; - } - - $drive = ''; - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - $path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path); - if (preg_match('/([a-zA-Z]\:)(.*)/', $path, $matches)) { - list(, $drive, $path) = $matches; - } else { - $cwd = getcwd(); - $drive = substr($cwd, 0, 2); - if (substr($path, 0, 1) != DIRECTORY_SEPARATOR) { - $path = substr($cwd, 3) . DIRECTORY_SEPARATOR . $path; - } - } - } elseif (substr($path, 0, 1) != DIRECTORY_SEPARATOR) { - $path = getcwd() . DIRECTORY_SEPARATOR . $path; - } - - $stack = array(); - $parts = explode(DIRECTORY_SEPARATOR, $path); - foreach ($parts as $dir) { - if (strlen($dir) && $dir !== '.') { - if ($dir == '..') { - array_pop($stack); - } else { - array_push($stack, $dir); - } - } - } - - return $drive . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $stack); - } -} diff --git a/library/Zend/Filter/StaticFilter.php b/library/Zend/Filter/StaticFilter.php deleted file mode 100755 index 2847137b6..000000000 --- a/library/Zend/Filter/StaticFilter.php +++ /dev/null @@ -1,70 +0,0 @@ -setShareByDefault(false); - } - static::$plugins = $manager; - } - - /** - * Get plugin manager for loading filter classes - * - * @return FilterPluginManager - */ - public static function getPluginManager() - { - if (null === static::$plugins) { - static::setPluginManager(new FilterPluginManager()); - } - return static::$plugins; - } - - /** - * Returns a value filtered through a specified filter class, without requiring separate - * instantiation of the filter object. - * - * The first argument of this method is a data input value, that you would have filtered. - * The second argument is a string, which corresponds to the basename of the filter class, - * relative to the Zend\Filter namespace. This method automatically loads the class, - * creates an instance, and applies the filter() method to the data input. You can also pass - * an array of constructor arguments, if they are needed for the filter class. - * - * @param mixed $value - * @param string $classBaseName - * @param array $args OPTIONAL - * @return mixed - * @throws Exception\ExceptionInterface - */ - public static function execute($value, $classBaseName, array $args = array()) - { - $plugins = static::getPluginManager(); - - $filter = $plugins->get($classBaseName, $args); - return $filter->filter($value); - } -} diff --git a/library/Zend/Filter/StringToLower.php b/library/Zend/Filter/StringToLower.php deleted file mode 100755 index 3d6f66a46..000000000 --- a/library/Zend/Filter/StringToLower.php +++ /dev/null @@ -1,62 +0,0 @@ - null, - ); - - /** - * Constructor - * - * @param string|array|Traversable $encodingOrOptions OPTIONAL - */ - public function __construct($encodingOrOptions = null) - { - if ($encodingOrOptions !== null) { - if (!static::isOptions($encodingOrOptions)) { - $this->setEncoding($encodingOrOptions); - } else { - $this->setOptions($encodingOrOptions); - } - } - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns the string $value, converting characters to lowercase as necessary - * - * If the value provided is non-scalar, the value will remain unfiltered - * - * @param string $value - * @return string|mixed - */ - public function filter($value) - { - if (!is_scalar($value)) { - return $value; - } - $value = (string) $value; - - if ($this->options['encoding'] !== null) { - return mb_strtolower($value, $this->options['encoding']); - } - - return strtolower($value); - } -} diff --git a/library/Zend/Filter/StringToUpper.php b/library/Zend/Filter/StringToUpper.php deleted file mode 100755 index 7f4c78e12..000000000 --- a/library/Zend/Filter/StringToUpper.php +++ /dev/null @@ -1,62 +0,0 @@ - null, - ); - - /** - * Constructor - * - * @param string|array|Traversable $encodingOrOptions OPTIONAL - */ - public function __construct($encodingOrOptions = null) - { - if ($encodingOrOptions !== null) { - if (!static::isOptions($encodingOrOptions)) { - $this->setEncoding($encodingOrOptions); - } else { - $this->setOptions($encodingOrOptions); - } - } - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns the string $value, converting characters to uppercase as necessary - * - * If the value provided is non-scalar, the value will remain unfiltered - * - * @param string $value - * @return string|mixed - */ - public function filter($value) - { - if (!is_scalar($value)) { - return $value; - } - $value = (string) $value; - - if ($this->options['encoding'] !== null) { - return mb_strtoupper($value, $this->options['encoding']); - } - - return strtoupper($value); - } -} diff --git a/library/Zend/Filter/StringTrim.php b/library/Zend/Filter/StringTrim.php deleted file mode 100755 index 2eae7fa36..000000000 --- a/library/Zend/Filter/StringTrim.php +++ /dev/null @@ -1,110 +0,0 @@ - null, - ); - - /** - * Sets filter options - * - * @param string|array|Traversable $charlistOrOptions - */ - public function __construct($charlistOrOptions = null) - { - if ($charlistOrOptions !== null) { - if (!is_array($charlistOrOptions) - && !$charlistOrOptions instanceof Traversable - ) { - $this->setCharList($charlistOrOptions); - } else { - $this->setOptions($charlistOrOptions); - } - } - } - - /** - * Sets the charList option - * - * @param string $charList - * @return self Provides a fluent interface - */ - public function setCharList($charList) - { - if (! strlen($charList)) { - $charList = null; - } - - $this->options['charlist'] = $charList; - - return $this; - } - - /** - * Returns the charList option - * - * @return string|null - */ - public function getCharList() - { - return $this->options['charlist']; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * Returns the string $value with characters stripped from the beginning and end - * - * @param string $value - * @return string - */ - public function filter($value) - { - if (!is_string($value)) { - return $value; - } - $value = (string) $value; - - if (null === $this->options['charlist']) { - return $this->unicodeTrim($value); - } - - return $this->unicodeTrim($value, $this->options['charlist']); - } - - /** - * Unicode aware trim method - * Fixes a PHP problem - * - * @param string $value - * @param string $charlist - * @return string - */ - protected function unicodeTrim($value, $charlist = '\\\\s') - { - $chars = preg_replace( - array('/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'), - array('\\\\\\0', '\\', '\/'), - $charlist - ); - - $pattern = '/^[' . $chars . ']+|[' . $chars . ']+$/usSD'; - - return preg_replace($pattern, '', $value); - } -} diff --git a/library/Zend/Filter/StripNewlines.php b/library/Zend/Filter/StripNewlines.php deleted file mode 100755 index 481facaa8..000000000 --- a/library/Zend/Filter/StripNewlines.php +++ /dev/null @@ -1,29 +0,0 @@ - Tags which are allowed - * 'allowAttribs' => Attributes which are allowed - * 'allowComments' => Are comments allowed ? - * - * @param string|array|Traversable $options - */ - public function __construct($options = null) - { - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - if ((!is_array($options)) || (is_array($options) && !array_key_exists('allowTags', $options) && - !array_key_exists('allowAttribs', $options) && !array_key_exists('allowComments', $options))) { - $options = func_get_args(); - $temp['allowTags'] = array_shift($options); - if (!empty($options)) { - $temp['allowAttribs'] = array_shift($options); - } - - if (!empty($options)) { - $temp['allowComments'] = array_shift($options); - } - - $options = $temp; - } - - if (array_key_exists('allowTags', $options)) { - $this->setTagsAllowed($options['allowTags']); - } - - if (array_key_exists('allowAttribs', $options)) { - $this->setAttributesAllowed($options['allowAttribs']); - } - } - - /** - * Returns the tagsAllowed option - * - * @return array - */ - public function getTagsAllowed() - { - return $this->tagsAllowed; - } - - /** - * Sets the tagsAllowed option - * - * @param array|string $tagsAllowed - * @return self Provides a fluent interface - */ - public function setTagsAllowed($tagsAllowed) - { - if (!is_array($tagsAllowed)) { - $tagsAllowed = array($tagsAllowed); - } - - foreach ($tagsAllowed as $index => $element) { - // If the tag was provided without attributes - if (is_int($index) && is_string($element)) { - // Canonicalize the tag name - $tagName = strtolower($element); - // Store the tag as allowed with no attributes - $this->tagsAllowed[$tagName] = array(); - } - // Otherwise, if a tag was provided with attributes - elseif (is_string($index) && (is_array($element) || is_string($element))) { - // Canonicalize the tag name - $tagName = strtolower($index); - // Canonicalize the attributes - if (is_string($element)) { - $element = array($element); - } - // Store the tag as allowed with the provided attributes - $this->tagsAllowed[$tagName] = array(); - foreach ($element as $attribute) { - if (is_string($attribute)) { - // Canonicalize the attribute name - $attributeName = strtolower($attribute); - $this->tagsAllowed[$tagName][$attributeName] = null; - } - } - } - } - - return $this; - } - - /** - * Returns the attributesAllowed option - * - * @return array - */ - public function getAttributesAllowed() - { - return $this->attributesAllowed; - } - - /** - * Sets the attributesAllowed option - * - * @param array|string $attributesAllowed - * @return self Provides a fluent interface - */ - public function setAttributesAllowed($attributesAllowed) - { - if (!is_array($attributesAllowed)) { - $attributesAllowed = array($attributesAllowed); - } - - // Store each attribute as allowed - foreach ($attributesAllowed as $attribute) { - if (is_string($attribute)) { - // Canonicalize the attribute name - $attributeName = strtolower($attribute); - $this->attributesAllowed[$attributeName] = null; - } - } - - return $this; - } - - /** - * Defined by Zend\Filter\FilterInterface - * - * If the value provided is non-scalar, the value will remain unfiltered - * - * @todo improve docblock descriptions - * @param string $value - * @return string|mixed - */ - public function filter($value) - { - if (!is_scalar($value)) { - return $value; - } - $value = (string) $value; - - // Strip HTML comments first - while (strpos($value, '' . $link . ''; - } - - return $link; - } - - /** - * Render link elements as string - * - * @param string|int $indent - * @return string - */ - public function toString($indent = null) - { - $indent = (null !== $indent) - ? $this->getWhitespace($indent) - : $this->getIndent(); - - $items = array(); - $this->getContainer()->ksort(); - foreach ($this as $item) { - $items[] = $this->itemToString($item); - } - - return $indent . implode($this->escape($this->getSeparator()) . $indent, $items); - } - - /** - * Create data item for stack - * - * @param array $attributes - * @return stdClass - */ - public function createData(array $attributes) - { - return (object) $attributes; - } - - /** - * Create item for stylesheet link item - * - * @param array $args - * @return stdClass|false Returns false if stylesheet is a duplicate - */ - public function createDataStylesheet(array $args) - { - $rel = 'stylesheet'; - $type = 'text/css'; - $media = 'screen'; - $conditionalStylesheet = false; - $href = array_shift($args); - - if ($this->isDuplicateStylesheet($href)) { - return false; - } - - if (0 < count($args)) { - $media = array_shift($args); - if (is_array($media)) { - $media = implode(',', $media); - } else { - $media = (string) $media; - } - } - if (0 < count($args)) { - $conditionalStylesheet = array_shift($args); - if (!empty($conditionalStylesheet) && is_string($conditionalStylesheet)) { - $conditionalStylesheet = (string) $conditionalStylesheet; - } else { - $conditionalStylesheet = null; - } - } - - if (0 < count($args) && is_array($args[0])) { - $extras = array_shift($args); - $extras = (array) $extras; - } - - $attributes = compact('rel', 'type', 'href', 'media', 'conditionalStylesheet', 'extras'); - - return $this->createData($attributes); - } - - /** - * Is the linked stylesheet a duplicate? - * - * @param string $uri - * @return bool - */ - protected function isDuplicateStylesheet($uri) - { - foreach ($this->getContainer() as $item) { - if (($item->rel == 'stylesheet') && ($item->href == $uri)) { - return true; - } - } - - return false; - } - - /** - * Create item for alternate link item - * - * @param array $args - * @throws Exception\InvalidArgumentException - * @return stdClass - */ - public function createDataAlternate(array $args) - { - if (3 > count($args)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Alternate tags require 3 arguments; %s provided', - count($args) - )); - } - - $rel = 'alternate'; - $href = array_shift($args); - $type = array_shift($args); - $title = array_shift($args); - - if (0 < count($args) && is_array($args[0])) { - $extras = array_shift($args); - $extras = (array) $extras; - - if (isset($extras['media']) && is_array($extras['media'])) { - $extras['media'] = implode(',', $extras['media']); - } - } - - $href = (string) $href; - $type = (string) $type; - $title = (string) $title; - - $attributes = compact('rel', 'href', 'type', 'title', 'extras'); - - return $this->createData($attributes); - } - - /** - * Create item for a prev relationship (mainly used for pagination) - * - * @param array $args - * @return stdClass - */ - public function createDataPrev(array $args) - { - $rel = 'prev'; - $href = (string) array_shift($args); - - $attributes = compact('rel', 'href'); - - return $this->createData($attributes); - } - - /** - * Create item for a prev relationship (mainly used for pagination) - * - * @param array $args - * @return stdClass - */ - public function createDataNext(array $args) - { - $rel = 'next'; - $href = (string) array_shift($args); - - $attributes = compact('rel', 'href'); - - return $this->createData($attributes); - } -} diff --git a/library/Zend/View/Helper/HeadMeta.php b/library/Zend/View/Helper/HeadMeta.php deleted file mode 100755 index 66a0dff59..000000000 --- a/library/Zend/View/Helper/HeadMeta.php +++ /dev/null @@ -1,453 +0,0 @@ -setSeparator(PHP_EOL); - } - - /** - * Retrieve object instance; optionally add meta tag - * - * @param string $content - * @param string $keyValue - * @param string $keyType - * @param array $modifiers - * @param string $placement - * @return HeadMeta - */ - public function __invoke($content = null, $keyValue = null, $keyType = 'name', $modifiers = array(), $placement = Placeholder\Container\AbstractContainer::APPEND) - { - if ((null !== $content) && (null !== $keyValue)) { - $item = $this->createData($keyType, $keyValue, $content, $modifiers); - $action = strtolower($placement); - switch ($action) { - case 'append': - case 'prepend': - case 'set': - $this->$action($item); - break; - default: - $this->append($item); - break; - } - } - - return $this; - } - - /** - * Overload method access - * - * @param string $method - * @param array $args - * @throws Exception\BadMethodCallException - * @return HeadMeta - */ - public function __call($method, $args) - { - if (preg_match('/^(?Pset|(pre|ap)pend|offsetSet)(?PName|HttpEquiv|Property|Itemprop)$/', $method, $matches)) { - $action = $matches['action']; - $type = $this->normalizeType($matches['type']); - $argc = count($args); - $index = null; - - if ('offsetSet' == $action) { - if (0 < $argc) { - $index = array_shift($args); - --$argc; - } - } - - if (2 > $argc) { - throw new Exception\BadMethodCallException( - 'Too few arguments provided; requires key value, and content' - ); - } - - if (3 > $argc) { - $args[] = array(); - } - - $item = $this->createData($type, $args[0], $args[1], $args[2]); - - if ('offsetSet' == $action) { - return $this->offsetSet($index, $item); - } - - $this->$action($item); - - return $this; - } - - return parent::__call($method, $args); - } - - /** - * Render placeholder as string - * - * @param string|int $indent - * @return string - */ - public function toString($indent = null) - { - $indent = (null !== $indent) - ? $this->getWhitespace($indent) - : $this->getIndent(); - - $items = array(); - $this->getContainer()->ksort(); - - try { - foreach ($this as $item) { - $items[] = $this->itemToString($item); - } - } catch (Exception\InvalidArgumentException $e) { - trigger_error($e->getMessage(), E_USER_WARNING); - return ''; - } - - return $indent . implode($this->escape($this->getSeparator()) . $indent, $items); - } - - /** - * Create data item for inserting into stack - * - * @param string $type - * @param string $typeValue - * @param string $content - * @param array $modifiers - * @return stdClass - */ - public function createData($type, $typeValue, $content, array $modifiers) - { - $data = new stdClass; - $data->type = $type; - $data->$type = $typeValue; - $data->content = $content; - $data->modifiers = $modifiers; - - return $data; - } - - /** - * Build meta HTML string - * - * @param stdClass $item - * @throws Exception\InvalidArgumentException - * @return string - */ - public function itemToString(stdClass $item) - { - if (!in_array($item->type, $this->typeKeys)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid type "%s" provided for meta', - $item->type - )); - } - $type = $item->type; - - $modifiersString = ''; - foreach ($item->modifiers as $key => $value) { - if ($this->view->plugin('doctype')->isHtml5() - && $key == 'scheme' - ) { - throw new Exception\InvalidArgumentException( - 'Invalid modifier "scheme" provided; not supported by HTML5' - ); - } - if (!in_array($key, $this->modifierKeys)) { - continue; - } - $modifiersString .= $key . '="' . $this->escape($value) . '" '; - } - - $modifiersString = rtrim($modifiersString); - - if ('' != $modifiersString) { - $modifiersString = ' ' . $modifiersString; - } - - if (method_exists($this->view, 'plugin')) { - if ($this->view->plugin('doctype')->isHtml5() - && $type == 'charset' - ) { - $tpl = ($this->view->plugin('doctype')->isXhtml()) - ? '' - : ''; - } elseif ($this->view->plugin('doctype')->isXhtml()) { - $tpl = ''; - } else { - $tpl = ''; - } - } else { - $tpl = ''; - } - - $meta = sprintf( - $tpl, - $type, - $this->escape($item->$type), - $this->escape($item->content), - $modifiersString - ); - - if (isset($item->modifiers['conditional']) && !empty($item->modifiers['conditional']) && is_string($item->modifiers['conditional'])) { - // inner wrap with comment end and start if !IE - if (str_replace(' ', '', $item->modifiers['conditional']) === '!IE') { - $meta = '' . $meta . ''; - } - - return $meta; - } - - /** - * Normalize type attribute of meta - * - * @param string $type type in CamelCase - * @throws Exception\DomainException - * @return string - */ - protected function normalizeType($type) - { - switch ($type) { - case 'Name': - return 'name'; - case 'HttpEquiv': - return 'http-equiv'; - case 'Property': - return 'property'; - case 'Itemprop': - return 'itemprop'; - default: - throw new Exception\DomainException(sprintf( - 'Invalid type "%s" passed to normalizeType', - $type - )); - } - } - - /** - * Determine if item is valid - * - * @param mixed $item - * @return bool - */ - protected function isValid($item) - { - if ((!$item instanceof stdClass) - || !isset($item->type) - || !isset($item->modifiers) - ) { - return false; - } - - if (!isset($item->content) - && (! $this->view->plugin('doctype')->isHtml5() - || (! $this->view->plugin('doctype')->isHtml5() && $item->type !== 'charset')) - ) { - return false; - } - - // is only supported with doctype html - if (! $this->view->plugin('doctype')->isHtml5() - && $item->type === 'itemprop' - ) { - return false; - } - - // is only supported with doctype RDFa - if (!$this->view->plugin('doctype')->isRdfa() - && $item->type === 'property' - ) { - return false; - } - - return true; - } - - /** - * Append - * - * @param string $value - * @return void - * @throws Exception\InvalidArgumentException - */ - public function append($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid value passed to append; please use appendMeta()' - ); - } - - return $this->getContainer()->append($value); - } - - /** - * OffsetSet - * - * @param string|int $index - * @param string $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function offsetSet($index, $value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid value passed to offsetSet; please use offsetSetName() or offsetSetHttpEquiv()' - ); - } - - return $this->getContainer()->offsetSet($index, $value); - } - - /** - * OffsetUnset - * - * @param string|int $index - * @throws Exception\InvalidArgumentException - * @return void - */ - public function offsetUnset($index) - { - if (!in_array($index, $this->getContainer()->getKeys())) { - throw new Exception\InvalidArgumentException('Invalid index passed to offsetUnset()'); - } - - return $this->getContainer()->offsetUnset($index); - } - - /** - * Prepend - * - * @param string $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function prepend($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid value passed to prepend; please use prependMeta()' - ); - } - - return $this->getContainer()->prepend($value); - } - - /** - * Set - * - * @param string $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function set($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException('Invalid value passed to set; please use setMeta()'); - } - - $container = $this->getContainer(); - foreach ($container->getArrayCopy() as $index => $item) { - if ($item->type == $value->type && $item->{$item->type} == $value->{$value->type}) { - $this->offsetUnset($index); - } - } - - return $this->append($value); - } - - /** - * Create an HTML5-style meta charset tag. Something like - * - * Not valid in a non-HTML5 doctype - * - * @param string $charset - * @return HeadMeta Provides a fluent interface - */ - public function setCharset($charset) - { - $item = new stdClass; - $item->type = 'charset'; - $item->charset = $charset; - $item->content = null; - $item->modifiers = array(); - $this->set($item); - - return $this; - } -} diff --git a/library/Zend/View/Helper/HeadScript.php b/library/Zend/View/Helper/HeadScript.php deleted file mode 100755 index eca0475d3..000000000 --- a/library/Zend/View/Helper/HeadScript.php +++ /dev/null @@ -1,507 +0,0 @@ -setSeparator(PHP_EOL); - } - - /** - * Return headScript object - * - * Returns headScript helper object; optionally, allows specifying a script - * or script file to include. - * - * @param string $mode Script or file - * @param string $spec Script/url - * @param string $placement Append, prepend, or set - * @param array $attrs Array of script attributes - * @param string $type Script type and/or array of script attributes - * @return HeadScript - */ - public function __invoke($mode = self::FILE, $spec = null, $placement = 'APPEND', array $attrs = array(), $type = 'text/javascript') - { - if ((null !== $spec) && is_string($spec)) { - $action = ucfirst(strtolower($mode)); - $placement = strtolower($placement); - switch ($placement) { - case 'set': - case 'prepend': - case 'append': - $action = $placement . $action; - break; - default: - $action = 'append' . $action; - break; - } - $this->$action($spec, $type, $attrs); - } - - return $this; - } - - /** - * Overload method access - * - * @param string $method Method to call - * @param array $args Arguments of method - * @throws Exception\BadMethodCallException if too few arguments or invalid method - * @return HeadScript - */ - public function __call($method, $args) - { - if (preg_match('/^(?Pset|(ap|pre)pend|offsetSet)(?PFile|Script)$/', $method, $matches)) { - if (1 > count($args)) { - throw new Exception\BadMethodCallException(sprintf( - 'Method "%s" requires at least one argument', - $method - )); - } - - $action = $matches['action']; - $mode = strtolower($matches['mode']); - $type = 'text/javascript'; - $attrs = array(); - - if ('offsetSet' == $action) { - $index = array_shift($args); - if (1 > count($args)) { - throw new Exception\BadMethodCallException(sprintf( - 'Method "%s" requires at least two arguments, an index and source', - $method - )); - } - } - - $content = $args[0]; - - if (isset($args[1])) { - $type = (string) $args[1]; - } - if (isset($args[2])) { - $attrs = (array) $args[2]; - } - - switch ($mode) { - case 'script': - $item = $this->createData($type, $attrs, $content); - if ('offsetSet' == $action) { - $this->offsetSet($index, $item); - } else { - $this->$action($item); - } - break; - case 'file': - default: - if (!$this->isDuplicate($content)) { - $attrs['src'] = $content; - $item = $this->createData($type, $attrs); - if ('offsetSet' == $action) { - $this->offsetSet($index, $item); - } else { - $this->$action($item); - } - } - break; - } - - return $this; - } - - return parent::__call($method, $args); - } - - /** - * Retrieve string representation - * - * @param string|int $indent Amount of whitespaces or string to use for indention - * @return string - */ - public function toString($indent = null) - { - $indent = (null !== $indent) - ? $this->getWhitespace($indent) - : $this->getIndent(); - - if ($this->view) { - $useCdata = $this->view->plugin('doctype')->isXhtml() ? true : false; - } else { - $useCdata = $this->useCdata ? true : false; - } - - $escapeStart = ($useCdata) ? '//' : '//-->'; - - $items = array(); - $this->getContainer()->ksort(); - foreach ($this as $item) { - if (!$this->isValid($item)) { - continue; - } - - $items[] = $this->itemToString($item, $indent, $escapeStart, $escapeEnd); - } - - return implode($this->getSeparator(), $items); - } - - /** - * Start capture action - * - * @param mixed $captureType Type of capture - * @param string $type Type of script - * @param array $attrs Attributes of capture - * @throws Exception\RuntimeException - * @return void - */ - public function captureStart($captureType = Placeholder\Container\AbstractContainer::APPEND, $type = 'text/javascript', $attrs = array()) - { - if ($this->captureLock) { - throw new Exception\RuntimeException('Cannot nest headScript captures'); - } - - $this->captureLock = true; - $this->captureType = $captureType; - $this->captureScriptType = $type; - $this->captureScriptAttrs = $attrs; - ob_start(); - } - - /** - * End capture action and store - * - * @return void - */ - public function captureEnd() - { - $content = ob_get_clean(); - $type = $this->captureScriptType; - $attrs = $this->captureScriptAttrs; - $this->captureScriptType = null; - $this->captureScriptAttrs = null; - $this->captureLock = false; - - switch ($this->captureType) { - case Placeholder\Container\AbstractContainer::SET: - case Placeholder\Container\AbstractContainer::PREPEND: - case Placeholder\Container\AbstractContainer::APPEND: - $action = strtolower($this->captureType) . 'Script'; - break; - default: - $action = 'appendScript'; - break; - } - - $this->$action($content, $type, $attrs); - } - - /** - * Create data item containing all necessary components of script - * - * @param string $type Type of data - * @param array $attributes Attributes of data - * @param string $content Content of data - * @return stdClass - */ - public function createData($type, array $attributes, $content = null) - { - $data = new stdClass(); - $data->type = $type; - $data->attributes = $attributes; - $data->source = $content; - - return $data; - } - - /** - * Is the file specified a duplicate? - * - * @param string $file Name of file to check - * @return bool - */ - protected function isDuplicate($file) - { - foreach ($this->getContainer() as $item) { - if (($item->source === null) && array_key_exists('src', $item->attributes) && ($file == $item->attributes['src'])) { - return true; - } - } - - return false; - } - - /** - * Is the script provided valid? - * - * @param mixed $value Is the given script valid? - * @return bool - */ - protected function isValid($value) - { - if ((!$value instanceof stdClass) || !isset($value->type) || (!isset($value->source) && !isset($value->attributes))) { - return false; - } - - return true; - } - - /** - * Create script HTML - * - * @param mixed $item Item to convert - * @param string $indent String to add before the item - * @param string $escapeStart Starting sequence - * @param string $escapeEnd Ending sequence - * @return string - */ - public function itemToString($item, $indent, $escapeStart, $escapeEnd) - { - $attrString = ''; - if (!empty($item->attributes)) { - foreach ($item->attributes as $key => $value) { - if ((!$this->arbitraryAttributesAllowed() && !in_array($key, $this->optionalAttributes)) - || in_array($key, array('conditional', 'noescape'))) { - continue; - } - if ('defer' == $key) { - $value = 'defer'; - } - $attrString .= sprintf(' %s="%s"', $key, ($this->autoEscape) ? $this->escape($value) : $value); - } - } - - $addScriptEscape = !(isset($item->attributes['noescape']) && filter_var($item->attributes['noescape'], FILTER_VALIDATE_BOOLEAN)); - - $type = ($this->autoEscape) ? $this->escape($item->type) : $item->type; - $html = ''; - - if (isset($item->attributes['conditional']) && !empty($item->attributes['conditional']) && is_string($item->attributes['conditional'])) { - // inner wrap with comment end and start if !IE - if (str_replace(' ', '', $item->attributes['conditional']) === '!IE') { - $html = '' . $html . ''; - } else { - $html = $indent . $html; - } - - return $html; - } - - /** - * Override append - * - * @param string $value Append script or file - * @throws Exception\InvalidArgumentException - * @return void - */ - public function append($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid argument passed to append(); please use one of the helper methods, appendScript() or appendFile()' - ); - } - - return $this->getContainer()->append($value); - } - - /** - * Override prepend - * - * @param string $value Prepend script or file - * @throws Exception\InvalidArgumentException - * @return void - */ - public function prepend($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid argument passed to prepend(); please use one of the helper methods, prependScript() or prependFile()' - ); - } - - return $this->getContainer()->prepend($value); - } - - /** - * Override set - * - * @param string $value Set script or file - * @throws Exception\InvalidArgumentException - * @return void - */ - public function set($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid argument passed to set(); please use one of the helper methods, setScript() or setFile()' - ); - } - - return $this->getContainer()->set($value); - } - - /** - * Override offsetSet - * - * @param string|int $index Set script of file offset - * @param mixed $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function offsetSet($index, $value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid argument passed to offsetSet(); please use one of the helper methods, offsetSetScript() or offsetSetFile()' - ); - } - - return $this->getContainer()->offsetSet($index, $value); - } - - /** - * Set flag indicating if arbitrary attributes are allowed - * - * @param bool $flag Set flag - * @return HeadScript - */ - public function setAllowArbitraryAttributes($flag) - { - $this->arbitraryAttributes = (bool) $flag; - return $this; - } - - /** - * Are arbitrary attributes allowed? - * - * @return bool - */ - public function arbitraryAttributesAllowed() - { - return $this->arbitraryAttributes; - } -} diff --git a/library/Zend/View/Helper/HeadStyle.php b/library/Zend/View/Helper/HeadStyle.php deleted file mode 100755 index c6cce3a70..000000000 --- a/library/Zend/View/Helper/HeadStyle.php +++ /dev/null @@ -1,413 +0,0 @@ -setSeparator(PHP_EOL); - } - - /** - * Return headStyle object - * - * Returns headStyle helper object; optionally, allows specifying - * - * @param string $content Stylesheet contents - * @param string $placement Append, prepend, or set - * @param string|array $attributes Optional attributes to utilize - * @return HeadStyle - */ - public function __invoke($content = null, $placement = 'APPEND', $attributes = array()) - { - if ((null !== $content) && is_string($content)) { - switch (strtoupper($placement)) { - case 'SET': - $action = 'setStyle'; - break; - case 'PREPEND': - $action = 'prependStyle'; - break; - case 'APPEND': - default: - $action = 'appendStyle'; - break; - } - $this->$action($content, $attributes); - } - - return $this; - } - - /** - * Overload method calls - * - * @param string $method - * @param array $args - * @throws Exception\BadMethodCallException When no $content provided or invalid method - * @return void - */ - public function __call($method, $args) - { - if (preg_match('/^(?Pset|(ap|pre)pend|offsetSet)(Style)$/', $method, $matches)) { - $index = null; - $argc = count($args); - $action = $matches['action']; - - if ('offsetSet' == $action) { - if (0 < $argc) { - $index = array_shift($args); - --$argc; - } - } - - if (1 > $argc) { - throw new Exception\BadMethodCallException(sprintf( - 'Method "%s" requires minimally content for the stylesheet', - $method - )); - } - - $content = $args[0]; - $attrs = array(); - if (isset($args[1])) { - $attrs = (array) $args[1]; - } - - $item = $this->createData($content, $attrs); - - if ('offsetSet' == $action) { - $this->offsetSet($index, $item); - } else { - $this->$action($item); - } - - return $this; - } - - return parent::__call($method, $args); - } - - /** - * Create string representation of placeholder - * - * @param string|int $indent - * @return string - */ - public function toString($indent = null) - { - $indent = (null !== $indent) - ? $this->getWhitespace($indent) - : $this->getIndent(); - - $items = array(); - $this->getContainer()->ksort(); - foreach ($this as $item) { - if (!$this->isValid($item)) { - continue; - } - $items[] = $this->itemToString($item, $indent); - } - - $return = $indent . implode($this->getSeparator() . $indent, $items); - $return = preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return); - - return $return; - } - - /** - * Start capture action - * - * @param string $type - * @param string $attrs - * @throws Exception\RuntimeException - * @return void - */ - public function captureStart($type = Placeholder\Container\AbstractContainer::APPEND, $attrs = null) - { - if ($this->captureLock) { - throw new Exception\RuntimeException('Cannot nest headStyle captures'); - } - - $this->captureLock = true; - $this->captureAttrs = $attrs; - $this->captureType = $type; - ob_start(); - } - - /** - * End capture action and store - * - * @return void - */ - public function captureEnd() - { - $content = ob_get_clean(); - $attrs = $this->captureAttrs; - $this->captureAttrs = null; - $this->captureLock = false; - - switch ($this->captureType) { - case Placeholder\Container\AbstractContainer::SET: - $this->setStyle($content, $attrs); - break; - case Placeholder\Container\AbstractContainer::PREPEND: - $this->prependStyle($content, $attrs); - break; - case Placeholder\Container\AbstractContainer::APPEND: - default: - $this->appendStyle($content, $attrs); - break; - } - } - - /** - * Create data item for use in stack - * - * @param string $content - * @param array $attributes - * @return stdClass - */ - public function createData($content, array $attributes) - { - if (!isset($attributes['media'])) { - $attributes['media'] = 'screen'; - } elseif (is_array($attributes['media'])) { - $attributes['media'] = implode(',', $attributes['media']); - } - - $data = new stdClass(); - $data->content = $content; - $data->attributes = $attributes; - - return $data; - } - - /** - * Determine if a value is a valid style tag - * - * @param mixed $value - * @return bool - */ - protected function isValid($value) - { - if ((!$value instanceof stdClass) || !isset($value->content) || !isset($value->attributes)) { - return false; - } - - return true; - } - - /** - * Convert content and attributes into valid style tag - * - * @param stdClass $item Item to render - * @param string $indent Indentation to use - * @return string - */ - public function itemToString(stdClass $item, $indent) - { - $attrString = ''; - if (!empty($item->attributes)) { - $enc = 'UTF-8'; - if ($this->view instanceof View\Renderer\RendererInterface - && method_exists($this->view, 'getEncoding') - ) { - $enc = $this->view->getEncoding(); - } - $escaper = $this->getEscaper($enc); - foreach ($item->attributes as $key => $value) { - if (!in_array($key, $this->optionalAttributes)) { - continue; - } - if ('media' == $key) { - if (false === strpos($value, ',')) { - if (!in_array($value, $this->mediaTypes)) { - continue; - } - } else { - $mediaTypes = explode(',', $value); - $value = ''; - foreach ($mediaTypes as $type) { - $type = trim($type); - if (!in_array($type, $this->mediaTypes)) { - continue; - } - $value .= $type .','; - } - $value = substr($value, 0, -1); - } - } - $attrString .= sprintf(' %s="%s"', $key, $escaper->escapeHtmlAttr($value)); - } - } - - $escapeStart = $indent . '' . PHP_EOL; - if (isset($item->attributes['conditional']) - && !empty($item->attributes['conditional']) - && is_string($item->attributes['conditional']) - ) { - $escapeStart = null; - $escapeEnd = null; - } - - $html = ''; - - if (null == $escapeStart && null == $escapeEnd) { - // inner wrap with comment end and start if !IE - if (str_replace(' ', '', $item->attributes['conditional']) === '!IE') { - $html = '' . $html . ''; - } - - return $html; - } - - /** - * Override append to enforce style creation - * - * @param mixed $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function append($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid value passed to append; please use appendStyle()' - ); - } - - return $this->getContainer()->append($value); - } - - /** - * Override offsetSet to enforce style creation - * - * @param string|int $index - * @param mixed $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function offsetSet($index, $value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid value passed to offsetSet; please use offsetSetStyle()' - ); - } - - return $this->getContainer()->offsetSet($index, $value); - } - - /** - * Override prepend to enforce style creation - * - * @param mixed $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function prepend($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException( - 'Invalid value passed to prepend; please use prependStyle()' - ); - } - - return $this->getContainer()->prepend($value); - } - - /** - * Override set to enforce style creation - * - * @param mixed $value - * @throws Exception\InvalidArgumentException - * @return void - */ - public function set($value) - { - if (!$this->isValid($value)) { - throw new Exception\InvalidArgumentException('Invalid value passed to set; please use setStyle()'); - } - - return $this->getContainer()->set($value); - } -} diff --git a/library/Zend/View/Helper/HeadTitle.php b/library/Zend/View/Helper/HeadTitle.php deleted file mode 100755 index 2ea8d78dd..000000000 --- a/library/Zend/View/Helper/HeadTitle.php +++ /dev/null @@ -1,263 +0,0 @@ -getDefaultAttachOrder()) - ? Placeholder\Container\AbstractContainer::APPEND - : $this->getDefaultAttachOrder(); - } - - $title = (string) $title; - if ($title !== '') { - if ($setType == Placeholder\Container\AbstractContainer::SET) { - $this->set($title); - } elseif ($setType == Placeholder\Container\AbstractContainer::PREPEND) { - $this->prepend($title); - } else { - $this->append($title); - } - } - - return $this; - } - - /** - * Render title (wrapped by title tag) - * - * @param string|null $indent - * @return string - */ - public function toString($indent = null) - { - $indent = (null !== $indent) - ? $this->getWhitespace($indent) - : $this->getIndent(); - - $output = $this->renderTitle(); - - return $indent . '' . $output . ''; - } - - /** - * Render title string - * - * @return string - */ - public function renderTitle() - { - $items = array(); - - if (null !== ($translator = $this->getTranslator())) { - foreach ($this as $item) { - $items[] = $translator->translate($item, $this->getTranslatorTextDomain()); - } - } else { - foreach ($this as $item) { - $items[] = $item; - } - } - - $separator = $this->getSeparator(); - $output = ''; - - $prefix = $this->getPrefix(); - if ($prefix) { - $output .= $prefix; - } - - $output .= implode($separator, $items); - - $postfix = $this->getPostfix(); - if ($postfix) { - $output .= $postfix; - } - - $output = ($this->autoEscape) ? $this->escape($output) : $output; - - return $output; - } - - /** - * Set a default order to add titles - * - * @param string $setType - * @throws Exception\DomainException - * @return HeadTitle - */ - public function setDefaultAttachOrder($setType) - { - if (!in_array($setType, array( - Placeholder\Container\AbstractContainer::APPEND, - Placeholder\Container\AbstractContainer::SET, - Placeholder\Container\AbstractContainer::PREPEND - ))) { - throw new Exception\DomainException( - "You must use a valid attach order: 'PREPEND', 'APPEND' or 'SET'" - ); - } - $this->defaultAttachOrder = $setType; - - return $this; - } - - /** - * Get the default attach order, if any. - * - * @return mixed - */ - public function getDefaultAttachOrder() - { - return $this->defaultAttachOrder; - } - - // Translator methods - Good candidate to refactor as a trait with PHP 5.4 - - /** - * Sets translator to use in helper - * - * @param Translator $translator [optional] translator. - * Default is null, which sets no translator. - * @param string $textDomain [optional] text domain - * Default is null, which skips setTranslatorTextDomain - * @return HeadTitle - */ - public function setTranslator(Translator $translator = null, $textDomain = null) - { - $this->translator = $translator; - if (null !== $textDomain) { - $this->setTranslatorTextDomain($textDomain); - } - return $this; - } - - /** - * Returns translator used in helper - * - * @return Translator|null - */ - public function getTranslator() - { - if (! $this->isTranslatorEnabled()) { - return null; - } - - return $this->translator; - } - - /** - * Checks if the helper has a translator - * - * @return bool - */ - public function hasTranslator() - { - return (bool) $this->getTranslator(); - } - - /** - * Sets whether translator is enabled and should be used - * - * @param bool $enabled [optional] whether translator should be used. - * Default is true. - * @return HeadTitle - */ - public function setTranslatorEnabled($enabled = true) - { - $this->translatorEnabled = (bool) $enabled; - return $this; - } - - /** - * Returns whether translator is enabled and should be used - * - * @return bool - */ - public function isTranslatorEnabled() - { - return $this->translatorEnabled; - } - - /** - * Set translation text domain - * - * @param string $textDomain - * @return HeadTitle - */ - public function setTranslatorTextDomain($textDomain = 'default') - { - $this->translatorTextDomain = $textDomain; - return $this; - } - - /** - * Return the translation text domain - * - * @return string - */ - public function getTranslatorTextDomain() - { - return $this->translatorTextDomain; - } -} diff --git a/library/Zend/View/Helper/HelperInterface.php b/library/Zend/View/Helper/HelperInterface.php deleted file mode 100755 index 2d58c01f9..000000000 --- a/library/Zend/View/Helper/HelperInterface.php +++ /dev/null @@ -1,30 +0,0 @@ - $data, 'quality' => 'high'), $params); - - $htmlObject = $this->getView()->plugin('htmlObject'); - return $htmlObject($data, self::TYPE, $attribs, $params, $content); - } -} diff --git a/library/Zend/View/Helper/HtmlList.php b/library/Zend/View/Helper/HtmlList.php deleted file mode 100755 index 29c79c73c..000000000 --- a/library/Zend/View/Helper/HtmlList.php +++ /dev/null @@ -1,58 +0,0 @@ -getView()->plugin('escapeHtml'); - $item = $escaper($item); - } - $list .= '
      • ' . $item . '
      • ' . self::EOL; - } else { - $itemLength = 5 + strlen(self::EOL); - if ($itemLength < strlen($list)) { - $list = substr($list, 0, strlen($list) - $itemLength) - . $this($item, $ordered, $attribs, $escape) . '' . self::EOL; - } else { - $list .= '
      • ' . $this($item, $ordered, $attribs, $escape) . '
      • ' . self::EOL; - } - } - } - - if ($attribs) { - $attribs = $this->htmlAttribs($attribs); - } else { - $attribs = ''; - } - - $tag = ($ordered) ? 'ol' : 'ul'; - - return '<' . $tag . $attribs . '>' . self::EOL . $list . '' . self::EOL; - } -} diff --git a/library/Zend/View/Helper/HtmlObject.php b/library/Zend/View/Helper/HtmlObject.php deleted file mode 100755 index 17c2822f3..000000000 --- a/library/Zend/View/Helper/HtmlObject.php +++ /dev/null @@ -1,63 +0,0 @@ - $data, 'type' => $type), $attribs); - - // Params - $paramHtml = array(); - $closingBracket = $this->getClosingBracket(); - - foreach ($params as $param => $options) { - if (is_string($options)) { - $options = array('value' => $options); - } - - $options = array_merge(array('name' => $param), $options); - - $paramHtml[] = 'htmlAttribs($options) . $closingBracket; - } - - // Content - if (is_array($content)) { - $content = implode(self::EOL, $content); - } - - // Object header - $xhtml = 'htmlAttribs($attribs) . '>' . self::EOL - . implode(self::EOL, $paramHtml) . self::EOL - . ($content ? $content . self::EOL : '') - . ''; - - return $xhtml; - } -} diff --git a/library/Zend/View/Helper/HtmlPage.php b/library/Zend/View/Helper/HtmlPage.php deleted file mode 100755 index ee170c1b0..000000000 --- a/library/Zend/View/Helper/HtmlPage.php +++ /dev/null @@ -1,51 +0,0 @@ - self::ATTRIB_CLASSID); - - /** - * Output a html object tag - * - * @param string $data The html url - * @param array $attribs Attribs for the object tag - * @param array $params Params for in the object tag - * @param string $content Alternative content - * @return string - */ - public function __invoke($data, array $attribs = array(), array $params = array(), $content = null) - { - // Attribs - $attribs = array_merge($this->attribs, $attribs); - - // Params - $params = array_merge(array('data' => $data), $params); - - $htmlObject = $this->getView()->plugin('htmlObject'); - return $htmlObject($data, self::TYPE, $attribs, $params, $content); - } -} diff --git a/library/Zend/View/Helper/HtmlQuicktime.php b/library/Zend/View/Helper/HtmlQuicktime.php deleted file mode 100755 index 629d6efa3..000000000 --- a/library/Zend/View/Helper/HtmlQuicktime.php +++ /dev/null @@ -1,56 +0,0 @@ - self::ATTRIB_CLASSID, 'codebase' => self::ATTRIB_CODEBASE); - - /** - * Output a quicktime movie object tag - * - * @param string $data The quicktime file - * @param array $attribs Attribs for the object tag - * @param array $params Params for in the object tag - * @param string $content Alternative content - * @return string - */ - public function __invoke($data, array $attribs = array(), array $params = array(), $content = null) - { - // Attrs - $attribs = array_merge($this->attribs, $attribs); - - // Params - $params = array_merge(array('src' => $data), $params); - - $htmlObject = $this->getView()->plugin('htmlObject'); - return $htmlObject($data, self::TYPE, $attribs, $params, $content); - } -} diff --git a/library/Zend/View/Helper/Identity.php b/library/Zend/View/Helper/Identity.php deleted file mode 100755 index 4fe145373..000000000 --- a/library/Zend/View/Helper/Identity.php +++ /dev/null @@ -1,69 +0,0 @@ -authenticationService instanceof AuthenticationService) { - throw new Exception\RuntimeException('No AuthenticationService instance provided'); - } - - if (!$this->authenticationService->hasIdentity()) { - return null; - } - - return $this->authenticationService->getIdentity(); - } - - /** - * Set AuthenticationService instance - * - * @param AuthenticationService $authenticationService - * @return Identity - */ - public function setAuthenticationService(AuthenticationService $authenticationService) - { - $this->authenticationService = $authenticationService; - return $this; - } - - /** - * Get AuthenticationService instance - * - * @return AuthenticationService - */ - public function getAuthenticationService() - { - return $this->authenticationService; - } -} diff --git a/library/Zend/View/Helper/InlineScript.php b/library/Zend/View/Helper/InlineScript.php deleted file mode 100755 index 57dace7d6..000000000 --- a/library/Zend/View/Helper/InlineScript.php +++ /dev/null @@ -1,42 +0,0 @@ -response instanceof Response) { - $headers = $this->response->getHeaders(); - $headers->addHeaderLine('Content-Type', 'application/json'); - } - - return $data; - } - - /** - * Set the response object - * - * @param Response $response - * @return Json - */ - public function setResponse(Response $response) - { - $this->response = $response; - return $this; - } -} diff --git a/library/Zend/View/Helper/Layout.php b/library/Zend/View/Helper/Layout.php deleted file mode 100755 index 65b630fb2..000000000 --- a/library/Zend/View/Helper/Layout.php +++ /dev/null @@ -1,98 +0,0 @@ -getRoot(); - } - - return $this->setTemplate($template); - } - - /** - * Get layout template - * - * @return string - */ - public function getLayout() - { - return $this->getRoot()->getTemplate(); - } - - /** - * Get the root view model - * - * @throws Exception\RuntimeException - * @return null|Model - */ - protected function getRoot() - { - $helper = $this->getViewModelHelper(); - - if (!$helper->hasRoot()) { - throw new Exception\RuntimeException(sprintf( - '%s: no view model currently registered as root in renderer', - __METHOD__ - )); - } - - return $helper->getRoot(); - } - - /** - * Set layout template - * - * @param string $template - * @return Layout - */ - public function setTemplate($template) - { - $this->getRoot()->setTemplate((string) $template); - return $this; - } - - /** - * Retrieve the view model helper - * - * @return ViewModel - */ - protected function getViewModelHelper() - { - if (null === $this->viewModelHelper) { - $this->viewModelHelper = $this->getView()->plugin('view_model'); - } - - return $this->viewModelHelper; - } -} diff --git a/library/Zend/View/Helper/Navigation.php b/library/Zend/View/Helper/Navigation.php deleted file mode 100755 index 015a5ec02..000000000 --- a/library/Zend/View/Helper/Navigation.php +++ /dev/null @@ -1,346 +0,0 @@ -setContainer($container); - } - - return $this; - } - - /** - * Magic overload: Proxy to other navigation helpers or the container - * - * Examples of usage from a view script or layout: - * - * // proxy to Menu helper and render container: - * echo $this->navigation()->menu(); - * - * // proxy to Breadcrumbs helper and set indentation: - * $this->navigation()->breadcrumbs()->setIndent(8); - * - * // proxy to container and find all pages with 'blog' route: - * $blogPages = $this->navigation()->findAllByRoute('blog'); - * - * - * @param string $method helper name or method name in container - * @param array $arguments [optional] arguments to pass - * @throws \Zend\View\Exception\ExceptionInterface if proxying to a helper, and the - * helper is not an instance of the - * interface specified in - * {@link findHelper()} - * @throws \Zend\Navigation\Exception\ExceptionInterface if method does not exist in container - * @return mixed returns what the proxied call returns - */ - public function __call($method, array $arguments = array()) - { - // check if call should proxy to another helper - $helper = $this->findHelper($method, false); - if ($helper) { - if ($helper instanceof ServiceLocatorAwareInterface && $this->getServiceLocator()) { - $helper->setServiceLocator($this->getServiceLocator()); - } - return call_user_func_array($helper, $arguments); - } - - // default behaviour: proxy call to container - return parent::__call($method, $arguments); - } - - /** - * Renders helper - * - * @param AbstractContainer $container - * @return string - * @throws Exception\RuntimeException - */ - public function render($container = null) - { - return $this->findHelper($this->getDefaultProxy())->render($container); - } - - /** - * Returns the helper matching $proxy - * - * The helper must implement the interface - * {@link Zend\View\Helper\Navigation\Helper}. - * - * @param string $proxy helper name - * @param bool $strict [optional] whether exceptions should be - * thrown if something goes - * wrong. Default is true. - * @throws Exception\RuntimeException if $strict is true and helper cannot be found - * @return \Zend\View\Helper\Navigation\HelperInterface helper instance - */ - public function findHelper($proxy, $strict = true) - { - $plugins = $this->getPluginManager(); - if (!$plugins->has($proxy)) { - if ($strict) { - throw new Exception\RuntimeException(sprintf( - 'Failed to find plugin for %s', - $proxy - )); - } - return false; - } - - $helper = $plugins->get($proxy); - $container = $this->getContainer(); - $hash = spl_object_hash($container) . spl_object_hash($helper); - - if (!isset($this->injected[$hash])) { - $helper->setContainer(); - $this->inject($helper); - $this->injected[$hash] = true; - } else { - if ($this->getInjectContainer()) { - $helper->setContainer($container); - } - } - - return $helper; - } - - /** - * Injects container, ACL, and translator to the given $helper if this - * helper is configured to do so - * - * @param NavigationHelper $helper helper instance - * @return void - */ - protected function inject(NavigationHelper $helper) - { - if ($this->getInjectContainer() && !$helper->hasContainer()) { - $helper->setContainer($this->getContainer()); - } - - if ($this->getInjectAcl()) { - if (!$helper->hasAcl()) { - $helper->setAcl($this->getAcl()); - } - if (!$helper->hasRole()) { - $helper->setRole($this->getRole()); - } - } - - if ($this->getInjectTranslator() && !$helper->hasTranslator()) { - $helper->setTranslator( - $this->getTranslator(), - $this->getTranslatorTextDomain() - ); - } - } - - /** - * Sets the default proxy to use in {@link render()} - * - * @param string $proxy default proxy - * @return Navigation - */ - public function setDefaultProxy($proxy) - { - $this->defaultProxy = (string) $proxy; - return $this; - } - - /** - * Returns the default proxy to use in {@link render()} - * - * @return string - */ - public function getDefaultProxy() - { - return $this->defaultProxy; - } - - /** - * Sets whether container should be injected when proxying - * - * @param bool $injectContainer - * @return Navigation - */ - public function setInjectContainer($injectContainer = true) - { - $this->injectContainer = (bool) $injectContainer; - return $this; - } - - /** - * Returns whether container should be injected when proxying - * - * @return bool - */ - public function getInjectContainer() - { - return $this->injectContainer; - } - - /** - * Sets whether ACL should be injected when proxying - * - * @param bool $injectAcl - * @return Navigation - */ - public function setInjectAcl($injectAcl = true) - { - $this->injectAcl = (bool) $injectAcl; - return $this; - } - - /** - * Returns whether ACL should be injected when proxying - * - * @return bool - */ - public function getInjectAcl() - { - return $this->injectAcl; - } - - /** - * Sets whether translator should be injected when proxying - * - * @param bool $injectTranslator - * @return Navigation - */ - public function setInjectTranslator($injectTranslator = true) - { - $this->injectTranslator = (bool) $injectTranslator; - return $this; - } - - /** - * Returns whether translator should be injected when proxying - * - * @return bool - */ - public function getInjectTranslator() - { - return $this->injectTranslator; - } - - /** - * Set manager for retrieving navigation helpers - * - * @param Navigation\PluginManager $plugins - * @return Navigation - */ - public function setPluginManager(Navigation\PluginManager $plugins) - { - $renderer = $this->getView(); - if ($renderer) { - $plugins->setRenderer($renderer); - } - $this->plugins = $plugins; - - return $this; - } - - /** - * Retrieve plugin loader for navigation helpers - * - * Lazy-loads an instance of Navigation\HelperLoader if none currently - * registered. - * - * @return Navigation\PluginManager - */ - public function getPluginManager() - { - if (null === $this->plugins) { - $this->setPluginManager(new Navigation\PluginManager()); - } - - return $this->plugins; - } - - /** - * Set the View object - * - * @param Renderer $view - * @return self - */ - public function setView(Renderer $view) - { - parent::setView($view); - if ($view && $this->plugins) { - $this->plugins->setRenderer($view); - } - return $this; - } -} diff --git a/library/Zend/View/Helper/Navigation/AbstractHelper.php b/library/Zend/View/Helper/Navigation/AbstractHelper.php deleted file mode 100755 index 1b997683f..000000000 --- a/library/Zend/View/Helper/Navigation/AbstractHelper.php +++ /dev/null @@ -1,945 +0,0 @@ -getContainer(), $method), - $arguments); - } - - /** - * Magic overload: Proxy to {@link render()}. - * - * This method will trigger an E_USER_ERROR if rendering the helper causes - * an exception to be thrown. - * - * Implements {@link HelperInterface::__toString()}. - * - * @return string - */ - public function __toString() - { - try { - return $this->render(); - } catch (\Exception $e) { - $msg = get_class($e) . ': ' . $e->getMessage(); - trigger_error($msg, E_USER_ERROR); - return ''; - } - } - - /** - * Finds the deepest active page in the given container - * - * @param Navigation\AbstractContainer $container container to search - * @param int|null $minDepth [optional] minimum depth - * required for page to be - * valid. Default is to use - * {@link getMinDepth()}. A - * null value means no minimum - * depth required. - * @param int|null $maxDepth [optional] maximum depth - * a page can have to be - * valid. Default is to use - * {@link getMaxDepth()}. A - * null value means no maximum - * depth required. - * @return array an associative array with - * the values 'depth' and - * 'page', or an empty array - * if not found - */ - public function findActive($container, $minDepth = null, $maxDepth = -1) - { - $this->parseContainer($container); - if (!is_int($minDepth)) { - $minDepth = $this->getMinDepth(); - } - if ((!is_int($maxDepth) || $maxDepth < 0) && null !== $maxDepth) { - $maxDepth = $this->getMaxDepth(); - } - - $found = null; - $foundDepth = -1; - $iterator = new RecursiveIteratorIterator( - $container, - RecursiveIteratorIterator::CHILD_FIRST - ); - - /** @var \Zend\Navigation\Page\AbstractPage $page */ - foreach ($iterator as $page) { - $currDepth = $iterator->getDepth(); - if ($currDepth < $minDepth || !$this->accept($page)) { - // page is not accepted - continue; - } - - if ($page->isActive(false) && $currDepth > $foundDepth) { - // found an active page at a deeper level than before - $found = $page; - $foundDepth = $currDepth; - } - } - - if (is_int($maxDepth) && $foundDepth > $maxDepth) { - while ($foundDepth > $maxDepth) { - if (--$foundDepth < $minDepth) { - $found = null; - break; - } - - $found = $found->getParent(); - if (!$found instanceof AbstractPage) { - $found = null; - break; - } - } - } - - if ($found) { - return array('page' => $found, 'depth' => $foundDepth); - } - - return array(); - } - - /** - * Verifies container and eventually fetches it from service locator if it is a string - * - * @param Navigation\AbstractContainer|string|null $container - * @throws Exception\InvalidArgumentException - */ - protected function parseContainer(&$container = null) - { - if (null === $container) { - return; - } - - if (is_string($container)) { - if (!$this->getServiceLocator()) { - throw new Exception\InvalidArgumentException(sprintf( - 'Attempted to set container with alias "%s" but no ServiceLocator was set', - $container - )); - } - - /** - * Load the navigation container from the root service locator - * - * The navigation container is probably located in Zend\ServiceManager\ServiceManager - * and not in the View\HelperPluginManager. If the set service locator is a - * HelperPluginManager, access the navigation container via the main service locator. - */ - $sl = $this->getServiceLocator(); - if ($sl instanceof View\HelperPluginManager) { - $sl = $sl->getServiceLocator(); - } - $container = $sl->get($container); - return; - } - - if (!$container instanceof Navigation\AbstractContainer) { - throw new Exception\InvalidArgumentException( - 'Container must be a string alias or an instance of ' . - 'Zend\Navigation\AbstractContainer' - ); - } - } - - // Iterator filter methods: - - /** - * Determines whether a page should be accepted when iterating - * - * Default listener may be 'overridden' by attaching listener to 'isAllowed' - * method. Listener must be 'short circuited' if overriding default ACL - * listener. - * - * Rules: - * - If a page is not visible it is not accepted, unless RenderInvisible has - * been set to true - * - If $useAcl is true (default is true): - * - Page is accepted if listener returns true, otherwise false - * - If page is accepted and $recursive is true, the page - * will not be accepted if it is the descendant of a non-accepted page - * - * @param AbstractPage $page page to check - * @param bool $recursive [optional] if true, page will not be - * accepted if it is the descendant of - * a page that is not accepted. Default - * is true - * - * @return bool Whether page should be accepted - */ - public function accept(AbstractPage $page, $recursive = true) - { - $accept = true; - - if (!$page->isVisible(false) && !$this->getRenderInvisible()) { - $accept = false; - } elseif ($this->getUseAcl()) { - $acl = $this->getAcl(); - $role = $this->getRole(); - $params = array('acl' => $acl, 'page' => $page, 'role' => $role); - $accept = $this->isAllowed($params); - } - - if ($accept && $recursive) { - $parent = $page->getParent(); - - if ($parent instanceof AbstractPage) { - $accept = $this->accept($parent, true); - } - } - - return $accept; - } - - /** - * Determines whether a page should be allowed given certain parameters - * - * @param array $params - * @return bool - */ - protected function isAllowed($params) - { - $results = $this->getEventManager()->trigger(__FUNCTION__, $this, $params); - return $results->last(); - } - - // Util methods: - - /** - * Retrieve whitespace representation of $indent - * - * @param int|string $indent - * @return string - */ - protected function getWhitespace($indent) - { - if (is_int($indent)) { - $indent = str_repeat(' ', $indent); - } - - return (string) $indent; - } - - /** - * Converts an associative array to a string of tag attributes. - * - * Overloads {@link View\Helper\AbstractHtmlElement::htmlAttribs()}. - * - * @param array $attribs an array where each key-value pair is converted - * to an attribute name and value - * @return string - */ - protected function htmlAttribs($attribs) - { - // filter out null values and empty string values - foreach ($attribs as $key => $value) { - if ($value === null || (is_string($value) && !strlen($value))) { - unset($attribs[$key]); - } - } - - return parent::htmlAttribs($attribs); - } - - /** - * Returns an HTML string containing an 'a' element for the given page - * - * @param AbstractPage $page page to generate HTML for - * @return string HTML string (Label) - */ - public function htmlify(AbstractPage $page) - { - $label = $this->translate($page->getLabel(), $page->getTextDomain()); - $title = $this->translate($page->getTitle(), $page->getTextDomain()); - - // get attribs for anchor element - $attribs = array( - 'id' => $page->getId(), - 'title' => $title, - 'class' => $page->getClass(), - 'href' => $page->getHref(), - 'target' => $page->getTarget() - ); - - /** @var \Zend\View\Helper\EscapeHtml $escaper */ - $escaper = $this->view->plugin('escapeHtml'); - $label = $escaper($label); - - return 'htmlAttribs($attribs) . '>' . $label . ''; - } - - /** - * Translate a message (for label, title, …) - * - * @param string $message ID of the message to translate - * @param string $textDomain Text domain (category name for the translations) - * @return string Translated message - */ - protected function translate($message, $textDomain = null) - { - if (is_string($message) && !empty($message)) { - if (null !== ($translator = $this->getTranslator())) { - if (null === $textDomain) { - $textDomain = $this->getTranslatorTextDomain(); - } - - return $translator->translate($message, $textDomain); - } - } - - return $message; - } - - /** - * Normalize an ID - * - * Overrides {@link View\Helper\AbstractHtmlElement::normalizeId()}. - * - * @param string $value - * @return string - */ - protected function normalizeId($value) - { - $prefix = get_class($this); - $prefix = strtolower(trim(substr($prefix, strrpos($prefix, '\\')), '\\')); - - return $prefix . '-' . $value; - } - - /** - * Sets ACL to use when iterating pages - * - * Implements {@link HelperInterface::setAcl()}. - * - * @param Acl\AclInterface $acl ACL object. - * @return AbstractHelper - */ - public function setAcl(Acl\AclInterface $acl = null) - { - $this->acl = $acl; - return $this; - } - - /** - * Returns ACL or null if it isn't set using {@link setAcl()} or - * {@link setDefaultAcl()} - * - * Implements {@link HelperInterface::getAcl()}. - * - * @return Acl\AclInterface|null ACL object or null - */ - public function getAcl() - { - if ($this->acl === null && static::$defaultAcl !== null) { - return static::$defaultAcl; - } - - return $this->acl; - } - - /** - * Checks if the helper has an ACL instance - * - * Implements {@link HelperInterface::hasAcl()}. - * - * @return bool - */ - public function hasAcl() - { - if ($this->acl instanceof Acl\Acl - || static::$defaultAcl instanceof Acl\Acl - ) { - return true; - } - - return false; - } - - /** - * Set the event manager. - * - * @param EventManagerInterface $events - * @return AbstractHelper - */ - public function setEventManager(EventManagerInterface $events) - { - $events->setIdentifiers(array( - __CLASS__, - get_called_class(), - )); - - $this->events = $events; - - $this->setDefaultListeners(); - - return $this; - } - - /** - * Get the event manager. - * - * @return EventManagerInterface - */ - public function getEventManager() - { - if (null === $this->events) { - $this->setEventManager(new EventManager()); - } - - return $this->events; - } - - /** - * Sets navigation container the helper operates on by default - * - * Implements {@link HelperInterface::setContainer()}. - * - * @param string|Navigation\AbstractContainer $container Default is null, meaning container will be reset. - * @return AbstractHelper - */ - public function setContainer($container = null) - { - $this->parseContainer($container); - $this->container = $container; - - return $this; - } - - /** - * Returns the navigation container helper operates on by default - * - * Implements {@link HelperInterface::getContainer()}. - * - * If no container is set, a new container will be instantiated and - * stored in the helper. - * - * @return Navigation\AbstractContainer navigation container - */ - public function getContainer() - { - if (null === $this->container) { - $this->container = new Navigation\Navigation(); - } - - return $this->container; - } - - /** - * Checks if the helper has a container - * - * Implements {@link HelperInterface::hasContainer()}. - * - * @return bool - */ - public function hasContainer() - { - return null !== $this->container; - } - - /** - * Set the indentation string for using in {@link render()}, optionally a - * number of spaces to indent with - * - * @param string|int $indent - * @return AbstractHelper - */ - public function setIndent($indent) - { - $this->indent = $this->getWhitespace($indent); - return $this; - } - - /** - * Returns indentation - * - * @return string - */ - public function getIndent() - { - return $this->indent; - } - - /** - * Sets the maximum depth a page can have to be included when rendering - * - * @param int $maxDepth Default is null, which sets no maximum depth. - * @return AbstractHelper - */ - public function setMaxDepth($maxDepth = null) - { - if (null === $maxDepth || is_int($maxDepth)) { - $this->maxDepth = $maxDepth; - } else { - $this->maxDepth = (int) $maxDepth; - } - - return $this; - } - - /** - * Returns maximum depth a page can have to be included when rendering - * - * @return int|null - */ - public function getMaxDepth() - { - return $this->maxDepth; - } - - /** - * Sets the minimum depth a page must have to be included when rendering - * - * @param int $minDepth Default is null, which sets no minimum depth. - * @return AbstractHelper - */ - public function setMinDepth($minDepth = null) - { - if (null === $minDepth || is_int($minDepth)) { - $this->minDepth = $minDepth; - } else { - $this->minDepth = (int) $minDepth; - } - - return $this; - } - - /** - * Returns minimum depth a page must have to be included when rendering - * - * @return int|null - */ - public function getMinDepth() - { - if (!is_int($this->minDepth) || $this->minDepth < 0) { - return 0; - } - - return $this->minDepth; - } - - /** - * Render invisible items? - * - * @param bool $renderInvisible - * @return AbstractHelper - */ - public function setRenderInvisible($renderInvisible = true) - { - $this->renderInvisible = (bool) $renderInvisible; - return $this; - } - - /** - * Return renderInvisible flag - * - * @return bool - */ - public function getRenderInvisible() - { - return $this->renderInvisible; - } - - /** - * Sets ACL role(s) to use when iterating pages - * - * Implements {@link HelperInterface::setRole()}. - * - * @param mixed $role [optional] role to set. Expects a string, an - * instance of type {@link Acl\Role\RoleInterface}, or null. Default - * is null, which will set no role. - * @return AbstractHelper - * @throws Exception\InvalidArgumentException - */ - public function setRole($role = null) - { - if (null === $role || is_string($role) || - $role instanceof Acl\Role\RoleInterface - ) { - $this->role = $role; - } else { - throw new Exception\InvalidArgumentException(sprintf( - '$role must be a string, null, or an instance of ' - . 'Zend\Permissions\Role\RoleInterface; %s given', - (is_object($role) ? get_class($role) : gettype($role)) - )); - } - - return $this; - } - - /** - * Returns ACL role to use when iterating pages, or null if it isn't set - * using {@link setRole()} or {@link setDefaultRole()} - * - * Implements {@link HelperInterface::getRole()}. - * - * @return string|Acl\Role\RoleInterface|null - */ - public function getRole() - { - if ($this->role === null && static::$defaultRole !== null) { - return static::$defaultRole; - } - - return $this->role; - } - - /** - * Checks if the helper has an ACL role - * - * Implements {@link HelperInterface::hasRole()}. - * - * @return bool - */ - public function hasRole() - { - if ($this->role instanceof Acl\Role\RoleInterface - || is_string($this->role) - || static::$defaultRole instanceof Acl\Role\RoleInterface - || is_string(static::$defaultRole) - ) { - return true; - } - - return false; - } - - /** - * Set the service locator. - * - * @param ServiceLocatorInterface $serviceLocator - * @return AbstractHelper - */ - public function setServiceLocator(ServiceLocatorInterface $serviceLocator) - { - $this->serviceLocator = $serviceLocator; - return $this; - } - - /** - * Get the service locator. - * - * @return ServiceLocatorInterface - */ - public function getServiceLocator() - { - return $this->serviceLocator; - } - - // Translator methods - Good candidate to refactor as a trait with PHP 5.4 - - /** - * Sets translator to use in helper - * - * @param Translator $translator [optional] translator. - * Default is null, which sets no translator. - * @param string $textDomain [optional] text domain - * Default is null, which skips setTranslatorTextDomain - * @return AbstractHelper - */ - public function setTranslator(Translator $translator = null, $textDomain = null) - { - $this->translator = $translator; - if (null !== $textDomain) { - $this->setTranslatorTextDomain($textDomain); - } - - return $this; - } - - /** - * Returns translator used in helper - * - * @return Translator|null - */ - public function getTranslator() - { - if (! $this->isTranslatorEnabled()) { - return null; - } - - return $this->translator; - } - - /** - * Checks if the helper has a translator - * - * @return bool - */ - public function hasTranslator() - { - return (bool) $this->getTranslator(); - } - - /** - * Sets whether translator is enabled and should be used - * - * @param bool $enabled - * @return AbstractHelper - */ - public function setTranslatorEnabled($enabled = true) - { - $this->translatorEnabled = (bool) $enabled; - return $this; - } - - /** - * Returns whether translator is enabled and should be used - * - * @return bool - */ - public function isTranslatorEnabled() - { - return $this->translatorEnabled; - } - - /** - * Set translation text domain - * - * @param string $textDomain - * @return AbstractHelper - */ - public function setTranslatorTextDomain($textDomain = 'default') - { - $this->translatorTextDomain = $textDomain; - return $this; - } - - /** - * Return the translation text domain - * - * @return string - */ - public function getTranslatorTextDomain() - { - return $this->translatorTextDomain; - } - - /** - * Sets whether ACL should be used - * - * Implements {@link HelperInterface::setUseAcl()}. - * - * @param bool $useAcl - * @return AbstractHelper - */ - public function setUseAcl($useAcl = true) - { - $this->useAcl = (bool) $useAcl; - return $this; - } - - /** - * Returns whether ACL should be used - * - * Implements {@link HelperInterface::getUseAcl()}. - * - * @return bool - */ - public function getUseAcl() - { - return $this->useAcl; - } - - // Static methods: - - /** - * Sets default ACL to use if another ACL is not explicitly set - * - * @param Acl\AclInterface $acl [optional] ACL object. Default is null, which - * sets no ACL object. - * @return void - */ - public static function setDefaultAcl(Acl\AclInterface $acl = null) - { - static::$defaultAcl = $acl; - } - - /** - * Sets default ACL role(s) to use when iterating pages if not explicitly - * set later with {@link setRole()} - * - * @param mixed $role [optional] role to set. Expects null, string, or an - * instance of {@link Acl\Role\RoleInterface}. Default is null, which - * sets no default role. - * @return void - * @throws Exception\InvalidArgumentException if role is invalid - */ - public static function setDefaultRole($role = null) - { - if (null === $role - || is_string($role) - || $role instanceof Acl\Role\RoleInterface - ) { - static::$defaultRole = $role; - } else { - throw new Exception\InvalidArgumentException(sprintf( - '$role must be null|string|Zend\Permissions\Role\RoleInterface; received "%s"', - (is_object($role) ? get_class($role) : gettype($role)) - )); - } - } - - /** - * Attaches default ACL listeners, if ACLs are in use - */ - protected function setDefaultListeners() - { - if (!$this->getUseAcl()) { - return; - } - - $this->getEventManager()->getSharedManager()->attach( - 'Zend\View\Helper\Navigation\AbstractHelper', - 'isAllowed', - array('Zend\View\Helper\Navigation\Listener\AclListener', 'accept') - ); - } -} diff --git a/library/Zend/View/Helper/Navigation/Breadcrumbs.php b/library/Zend/View/Helper/Navigation/Breadcrumbs.php deleted file mode 100755 index 5337ca8e0..000000000 --- a/library/Zend/View/Helper/Navigation/Breadcrumbs.php +++ /dev/null @@ -1,292 +0,0 @@ -setContainer($container); - } - - return $this; - } - - /** - * Renders helper - * - * Implements {@link HelperInterface::render()}. - * - * @param AbstractContainer $container [optional] container to render. Default is - * to render the container registered in the helper. - * @return string - */ - public function render($container = null) - { - $partial = $this->getPartial(); - if ($partial) { - return $this->renderPartial($container, $partial); - } - - return $this->renderStraight($container); - } - - /** - * Renders breadcrumbs by chaining 'a' elements with the separator - * registered in the helper - * - * @param AbstractContainer $container [optional] container to render. Default is - * to render the container registered in the helper. - * @return string - */ - public function renderStraight($container = null) - { - $this->parseContainer($container); - if (null === $container) { - $container = $this->getContainer(); - } - - // find deepest active - if (!$active = $this->findActive($container)) { - return ''; - } - - $active = $active['page']; - - // put the deepest active page last in breadcrumbs - if ($this->getLinkLast()) { - $html = $this->htmlify($active); - } else { - /** @var \Zend\View\Helper\EscapeHtml $escaper */ - $escaper = $this->view->plugin('escapeHtml'); - $html = $escaper( - $this->translate($active->getLabel(), $active->getTextDomain()) - ); - } - - // walk back to root - while ($parent = $active->getParent()) { - if ($parent instanceof AbstractPage) { - // prepend crumb to html - $html = $this->htmlify($parent) - . $this->getSeparator() - . $html; - } - - if ($parent === $container) { - // at the root of the given container - break; - } - - $active = $parent; - } - - return strlen($html) ? $this->getIndent() . $html : ''; - } - - /** - * Renders the given $container by invoking the partial view helper - * - * The container will simply be passed on as a model to the view script, - * so in the script it will be available in $this->container. - * - * @param AbstractContainer $container [optional] container to pass to view script. - * Default is to use the container registered - * in the helper. - * @param string|array $partial [optional] partial view script to use. - * Default is to use the partial registered - * in the helper. If an array is given, it - * is expected to contain two values; the - * partial view script to use, and the module - * where the script can be found. - * @throws Exception\RuntimeException if no partial provided - * @throws Exception\InvalidArgumentException if partial is invalid array - * @return string helper output - */ - public function renderPartial($container = null, $partial = null) - { - $this->parseContainer($container); - if (null === $container) { - $container = $this->getContainer(); - } - - if (null === $partial) { - $partial = $this->getPartial(); - } - - if (empty($partial)) { - throw new Exception\RuntimeException( - 'Unable to render menu: No partial view script provided' - ); - } - - // put breadcrumb pages in model - $model = array( - 'pages' => array(), - 'separator' => $this->getSeparator() - ); - $active = $this->findActive($container); - if ($active) { - $active = $active['page']; - $model['pages'][] = $active; - while ($parent = $active->getParent()) { - if ($parent instanceof AbstractPage) { - $model['pages'][] = $parent; - } else { - break; - } - - if ($parent === $container) { - // break if at the root of the given container - break; - } - - $active = $parent; - } - $model['pages'] = array_reverse($model['pages']); - } - - /** @var \Zend\View\Helper\Partial $partialHelper */ - $partialHelper = $this->view->plugin('partial'); - - if (is_array($partial)) { - if (count($partial) != 2) { - throw new Exception\InvalidArgumentException( - 'Unable to render menu: A view partial supplied as ' - . 'an array must contain two values: partial view ' - . 'script and module where script can be found' - ); - } - - return $partialHelper($partial[0], $model); - } - - return $partialHelper($partial, $model); - } - - /** - * Sets whether last page in breadcrumbs should be hyperlinked - * - * @param bool $linkLast whether last page should be hyperlinked - * @return Breadcrumbs - */ - public function setLinkLast($linkLast) - { - $this->linkLast = (bool) $linkLast; - return $this; - } - - /** - * Returns whether last page in breadcrumbs should be hyperlinked - * - * @return bool - */ - public function getLinkLast() - { - return $this->linkLast; - } - - /** - * Sets which partial view script to use for rendering menu - * - * @param string|array $partial partial view script or null. If an array is - * given, it is expected to contain two - * values; the partial view script to use, - * and the module where the script can be - * found. - * @return Breadcrumbs - */ - public function setPartial($partial) - { - if (null === $partial || is_string($partial) || is_array($partial)) { - $this->partial = $partial; - } - - return $this; - } - - /** - * Returns partial view script to use for rendering menu - * - * @return string|array|null - */ - public function getPartial() - { - return $this->partial; - } - - /** - * Sets breadcrumb separator - * - * @param string $separator separator string - * @return Breadcrumbs - */ - public function setSeparator($separator) - { - if (is_string($separator)) { - $this->separator = $separator; - } - - return $this; - } - - /** - * Returns breadcrumb separator - * - * @return string breadcrumb separator - */ - public function getSeparator() - { - return $this->separator; - } -} diff --git a/library/Zend/View/Helper/Navigation/HelperInterface.php b/library/Zend/View/Helper/Navigation/HelperInterface.php deleted file mode 100755 index 8b52c8c1d..000000000 --- a/library/Zend/View/Helper/Navigation/HelperInterface.php +++ /dev/null @@ -1,143 +0,0 @@ - elements - */ -class Links extends AbstractHelper -{ - /** - * Constants used for specifying which link types to find and render - * - * @var int - */ - const RENDER_ALTERNATE = 0x0001; - const RENDER_STYLESHEET = 0x0002; - const RENDER_START = 0x0004; - const RENDER_NEXT = 0x0008; - const RENDER_PREV = 0x0010; - const RENDER_CONTENTS = 0x0020; - const RENDER_INDEX = 0x0040; - const RENDER_GLOSSARY = 0x0080; - const RENDER_COPYRIGHT = 0x0100; - const RENDER_CHAPTER = 0x0200; - const RENDER_SECTION = 0x0400; - const RENDER_SUBSECTION = 0x0800; - const RENDER_APPENDIX = 0x1000; - const RENDER_HELP = 0x2000; - const RENDER_BOOKMARK = 0x4000; - const RENDER_CUSTOM = 0x8000; - const RENDER_ALL = 0xffff; - - /** - * Maps render constants to W3C link types - * - * @var array - */ - protected static $RELATIONS = array( - self::RENDER_ALTERNATE => 'alternate', - self::RENDER_STYLESHEET => 'stylesheet', - self::RENDER_START => 'start', - self::RENDER_NEXT => 'next', - self::RENDER_PREV => 'prev', - self::RENDER_CONTENTS => 'contents', - self::RENDER_INDEX => 'index', - self::RENDER_GLOSSARY => 'glossary', - self::RENDER_COPYRIGHT => 'copyright', - self::RENDER_CHAPTER => 'chapter', - self::RENDER_SECTION => 'section', - self::RENDER_SUBSECTION => 'subsection', - self::RENDER_APPENDIX => 'appendix', - self::RENDER_HELP => 'help', - self::RENDER_BOOKMARK => 'bookmark', - ); - - /** - * The helper's render flag - * - * @see render() - * @see setRenderFlag() - * @var int - */ - protected $renderFlag = self::RENDER_ALL; - - /** - * Root container - * - * Used for preventing methods to traverse above the container given to - * the {@link render()} method. - * - * @see _findRoot() - * @var AbstractContainer - */ - protected $root; - - /** - * Helper entry point - * - * @param string|AbstractContainer $container container to operate on - * @return Links - */ - public function __invoke($container = null) - { - if (null !== $container) { - $this->setContainer($container); - } - - return $this; - } - - /** - * Magic overload: Proxy calls to {@link findRelation()} or container - * - * Examples of finder calls: - * - * // METHOD // SAME AS - * $h->findRelNext($page); // $h->findRelation($page, 'rel', 'next') - * $h->findRevSection($page); // $h->findRelation($page, 'rev', 'section'); - * $h->findRelFoo($page); // $h->findRelation($page, 'rel', 'foo'); - * - * - * @param string $method - * @param array $arguments - * @return mixed - * @throws Exception\ExceptionInterface - */ - public function __call($method, array $arguments = array()) - { - ErrorHandler::start(E_WARNING); - $result = preg_match('/find(Rel|Rev)(.+)/', $method, $match); - ErrorHandler::stop(); - if ($result) { - return $this->findRelation($arguments[0], - strtolower($match[1]), - strtolower($match[2])); - } - - return parent::__call($method, $arguments); - } - - /** - * Renders helper - * - * Implements {@link HelperInterface::render()}. - * - * @param AbstractContainer|string|null $container [optional] container to render. - * Default is to render the - * container registered in the - * helper. - * @return string - */ - public function render($container = null) - { - $this->parseContainer($container); - if (null === $container) { - $container = $this->getContainer(); - } - - $active = $this->findActive($container); - if ($active) { - $active = $active['page']; - } else { - // no active page - return ''; - } - - $output = ''; - $indent = $this->getIndent(); - $this->root = $container; - - $result = $this->findAllRelations($active, $this->getRenderFlag()); - foreach ($result as $attrib => $types) { - foreach ($types as $relation => $pages) { - foreach ($pages as $page) { - $r = $this->renderLink($page, $attrib, $relation); - if ($r) { - $output .= $indent . $r . self::EOL; - } - } - } - } - - $this->root = null; - - // return output (trim last newline by spec) - return strlen($output) ? rtrim($output, self::EOL) : ''; - } - - /** - * Renders the given $page as a link element, with $attrib = $relation - * - * @param AbstractPage $page the page to render the link for - * @param string $attrib the attribute to use for $type, - * either 'rel' or 'rev' - * @param string $relation relation type, muse be one of; - * alternate, appendix, bookmark, - * chapter, contents, copyright, - * glossary, help, home, index, next, - * prev, section, start, stylesheet, - * subsection - * @return string - * @throws Exception\DomainException - */ - public function renderLink(AbstractPage $page, $attrib, $relation) - { - if (!in_array($attrib, array('rel', 'rev'))) { - throw new Exception\DomainException(sprintf( - 'Invalid relation attribute "%s", must be "rel" or "rev"', - $attrib - )); - } - - if (!$href = $page->getHref()) { - return ''; - } - - // TODO: add more attribs - // http://www.w3.org/TR/html401/struct/links.html#h-12.2 - $attribs = array( - $attrib => $relation, - 'href' => $href, - 'title' => $page->getLabel() - ); - - return 'htmlAttribs($attribs) . - $this->getClosingBracket(); - } - - // Finder methods: - - /** - * Finds all relations (forward and reverse) for the given $page - * - * The form of the returned array: - * - * // $page denotes an instance of Zend\Navigation\Page\AbstractPage - * $returned = array( - * 'rel' => array( - * 'alternate' => array($page, $page, $page), - * 'start' => array($page), - * 'next' => array($page), - * 'prev' => array($page), - * 'canonical' => array($page) - * ), - * 'rev' => array( - * 'section' => array($page) - * ) - * ); - * - * - * @param AbstractPage $page page to find links for - * @param null|int - * @return array - */ - public function findAllRelations(AbstractPage $page, $flag = null) - { - if (!is_int($flag)) { - $flag = self::RENDER_ALL; - } - - $result = array('rel' => array(), 'rev' => array()); - $native = array_values(static::$RELATIONS); - - foreach (array_keys($result) as $rel) { - $meth = 'getDefined' . ucfirst($rel); - $types = array_merge($native, array_diff($page->$meth(), $native)); - - foreach ($types as $type) { - if (!$relFlag = array_search($type, static::$RELATIONS)) { - $relFlag = self::RENDER_CUSTOM; - } - if (!($flag & $relFlag)) { - continue; - } - - $found = $this->findRelation($page, $rel, $type); - if ($found) { - if (!is_array($found)) { - $found = array($found); - } - $result[$rel][$type] = $found; - } - } - } - - return $result; - } - - /** - * Finds relations of the given $rel=$type from $page - * - * This method will first look for relations in the page instance, then - * by searching the root container if nothing was found in the page. - * - * @param AbstractPage $page page to find relations for - * @param string $rel relation, "rel" or "rev" - * @param string $type link type, e.g. 'start', 'next' - * @return AbstractPage|array|null - * @throws Exception\DomainException if $rel is not "rel" or "rev" - */ - public function findRelation(AbstractPage $page, $rel, $type) - { - if (!in_array($rel, array('rel', 'rev'))) { - throw new Exception\DomainException(sprintf( - 'Invalid argument: $rel must be "rel" or "rev"; "%s" given', - $rel - )); - } - - if (!$result = $this->findFromProperty($page, $rel, $type)) { - $result = $this->findFromSearch($page, $rel, $type); - } - - return $result; - } - - /** - * Finds relations of given $type for $page by checking if the - * relation is specified as a property of $page - * - * @param AbstractPage $page page to find relations for - * @param string $rel relation, 'rel' or 'rev' - * @param string $type link type, e.g. 'start', 'next' - * @return AbstractPage|array|null - */ - protected function findFromProperty(AbstractPage $page, $rel, $type) - { - $method = 'get' . ucfirst($rel); - $result = $page->$method($type); - if ($result) { - $result = $this->convertToPages($result); - if ($result) { - if (!is_array($result)) { - $result = array($result); - } - - foreach ($result as $key => $page) { - if (!$this->accept($page)) { - unset($result[$key]); - } - } - - return count($result) == 1 ? $result[0] : $result; - } - } - - return null; - } - - /** - * Finds relations of given $rel=$type for $page by using the helper to - * search for the relation in the root container - * - * @param AbstractPage $page page to find relations for - * @param string $rel relation, 'rel' or 'rev' - * @param string $type link type, e.g. 'start', 'next', etc - * @return array|null - */ - protected function findFromSearch(AbstractPage $page, $rel, $type) - { - $found = null; - - $method = 'search' . ucfirst($rel) . ucfirst($type); - if (method_exists($this, $method)) { - $found = $this->$method($page); - } - - return $found; - } - - // Search methods: - - /** - * Searches the root container for the forward 'start' relation of the given - * $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to the first document in a collection of documents. This link type - * tells search engines which document is considered by the author to be the - * starting point of the collection. - * - * @param AbstractPage $page - * @return AbstractPage|null - */ - public function searchRelStart(AbstractPage $page) - { - $found = $this->findRoot($page); - if (!$found instanceof AbstractPage) { - $found->rewind(); - $found = $found->current(); - } - - if ($found === $page || !$this->accept($found)) { - $found = null; - } - - return $found; - } - - /** - * Searches the root container for the forward 'next' relation of the given - * $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to the next document in a linear sequence of documents. User - * agents may choose to preload the "next" document, to reduce the perceived - * load time. - * - * @param AbstractPage $page - * @return AbstractPage|null - */ - public function searchRelNext(AbstractPage $page) - { - $found = null; - $break = false; - $iterator = new RecursiveIteratorIterator($this->findRoot($page), - RecursiveIteratorIterator::SELF_FIRST); - foreach ($iterator as $intermediate) { - if ($intermediate === $page) { - // current page; break at next accepted page - $break = true; - continue; - } - - if ($break && $this->accept($intermediate)) { - $found = $intermediate; - break; - } - } - - return $found; - } - - /** - * Searches the root container for the forward 'prev' relation of the given - * $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to the previous document in an ordered series of documents. Some - * user agents also support the synonym "Previous". - * - * @param AbstractPage $page - * @return AbstractPage|null - */ - public function searchRelPrev(AbstractPage $page) - { - $found = null; - $prev = null; - $iterator = new RecursiveIteratorIterator( - $this->findRoot($page), - RecursiveIteratorIterator::SELF_FIRST); - foreach ($iterator as $intermediate) { - if (!$this->accept($intermediate)) { - continue; - } - if ($intermediate === $page) { - $found = $prev; - break; - } - - $prev = $intermediate; - } - - return $found; - } - - /** - * Searches the root container for forward 'chapter' relations of the given - * $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to a document serving as a chapter in a collection of documents. - * - * @param AbstractPage $page - * @return AbstractPage|array|null - */ - public function searchRelChapter(AbstractPage $page) - { - $found = array(); - - // find first level of pages - $root = $this->findRoot($page); - - // find start page(s) - $start = $this->findRelation($page, 'rel', 'start'); - if (!is_array($start)) { - $start = array($start); - } - - foreach ($root as $chapter) { - // exclude self and start page from chapters - if ($chapter !== $page && - !in_array($chapter, $start) && - $this->accept($chapter)) { - $found[] = $chapter; - } - } - - switch (count($found)) { - case 0: - return null; - case 1: - return $found[0]; - default: - return $found; - } - } - - /** - * Searches the root container for forward 'section' relations of the given - * $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to a document serving as a section in a collection of documents. - * - * @param AbstractPage $page - * @return AbstractPage|array|null - */ - public function searchRelSection(AbstractPage $page) - { - $found = array(); - - // check if given page has pages and is a chapter page - if ($page->hasPages() && $this->findRoot($page)->hasPage($page)) { - foreach ($page as $section) { - if ($this->accept($section)) { - $found[] = $section; - } - } - } - - switch (count($found)) { - case 0: - return null; - case 1: - return $found[0]; - default: - return $found; - } - } - - /** - * Searches the root container for forward 'subsection' relations of the - * given $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to a document serving as a subsection in a collection of - * documents. - * - * @param AbstractPage $page - * @return AbstractPage|array|null - */ - public function searchRelSubsection(AbstractPage $page) - { - $found = array(); - - if ($page->hasPages()) { - // given page has child pages, loop chapters - foreach ($this->findRoot($page) as $chapter) { - // is page a section? - if ($chapter->hasPage($page)) { - foreach ($page as $subsection) { - if ($this->accept($subsection)) { - $found[] = $subsection; - } - } - } - } - } - - switch (count($found)) { - case 0: - return null; - case 1: - return $found[0]; - default: - return $found; - } - } - - /** - * Searches the root container for the reverse 'section' relation of the - * given $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to a document serving as a section in a collection of documents. - * - * @param AbstractPage $page - * @return AbstractPage|null - */ - public function searchRevSection(AbstractPage $page) - { - $found = null; - $parent = $page->getParent(); - if ($parent) { - if ($parent instanceof AbstractPage && - $this->findRoot($page)->hasPage($parent)) { - $found = $parent; - } - } - - return $found; - } - - /** - * Searches the root container for the reverse 'section' relation of the - * given $page - * - * From {@link http://www.w3.org/TR/html4/types.html#type-links}: - * Refers to a document serving as a subsection in a collection of - * documents. - * - * @param AbstractPage $page - * @return AbstractPage|null - */ - public function searchRevSubsection(AbstractPage $page) - { - $found = null; - $parent = $page->getParent(); - if ($parent) { - if ($parent instanceof AbstractPage) { - $root = $this->findRoot($page); - foreach ($root as $chapter) { - if ($chapter->hasPage($parent)) { - $found = $parent; - break; - } - } - } - } - - return $found; - } - - // Util methods: - - /** - * Returns the root container of the given page - * - * When rendering a container, the render method still store the given - * container as the root container, and unset it when done rendering. This - * makes sure finder methods will not traverse above the container given - * to the render method. - * - * @param AbstractPage $page - * @return AbstractContainer - */ - protected function findRoot(AbstractPage $page) - { - if ($this->root) { - return $this->root; - } - - $root = $page; - - while ($parent = $page->getParent()) { - $root = $parent; - if ($parent instanceof AbstractPage) { - $page = $parent; - } else { - break; - } - } - - return $root; - } - - /** - * Converts a $mixed value to an array of pages - * - * @param mixed $mixed mixed value to get page(s) from - * @param bool $recursive whether $value should be looped - * if it is an array or a config - * @return AbstractPage|array|null - */ - protected function convertToPages($mixed, $recursive = true) - { - if ($mixed instanceof AbstractPage) { - // value is a page instance; return directly - return $mixed; - } elseif ($mixed instanceof AbstractContainer) { - // value is a container; return pages in it - $pages = array(); - foreach ($mixed as $page) { - $pages[] = $page; - } - return $pages; - } elseif ($mixed instanceof Traversable) { - $mixed = ArrayUtils::iteratorToArray($mixed); - } elseif (is_string($mixed)) { - // value is a string; make a URI page - return AbstractPage::factory(array( - 'type' => 'uri', - 'uri' => $mixed - )); - } - - if (is_array($mixed) && !empty($mixed)) { - if ($recursive && is_numeric(key($mixed))) { - // first key is numeric; assume several pages - $pages = array(); - foreach ($mixed as $value) { - $value = $this->convertToPages($value, false); - if ($value) { - $pages[] = $value; - } - } - return $pages; - } else { - // pass array to factory directly - try { - $page = AbstractPage::factory($mixed); - return $page; - } catch (\Exception $e) { - } - } - } - - // nothing found - return null; - } - - /** - * Sets the helper's render flag - * - * The helper uses the bitwise '&' operator against the hex values of the - * render constants. This means that the flag can is "bitwised" value of - * the render constants. Examples: - * - * // render all links except glossary - * $flag = Links:RENDER_ALL ^ Links:RENDER_GLOSSARY; - * $helper->setRenderFlag($flag); - * - * // render only chapters and sections - * $flag = Links:RENDER_CHAPTER | Links:RENDER_SECTION; - * $helper->setRenderFlag($flag); - * - * // render only relations that are not native W3C relations - * $helper->setRenderFlag(Links:RENDER_CUSTOM); - * - * // render all relations (default) - * $helper->setRenderFlag(Links:RENDER_ALL); - * - * - * Note that custom relations can also be rendered directly using the - * {@link renderLink()} method. - * - * @param int $renderFlag - * @return Links - */ - public function setRenderFlag($renderFlag) - { - $this->renderFlag = (int) $renderFlag; - - return $this; - } - - /** - * Returns the helper's render flag - * - * @return int - */ - public function getRenderFlag() - { - return $this->renderFlag; - } -} diff --git a/library/Zend/View/Helper/Navigation/Listener/AclListener.php b/library/Zend/View/Helper/Navigation/Listener/AclListener.php deleted file mode 100755 index 5c8656084..000000000 --- a/library/Zend/View/Helper/Navigation/Listener/AclListener.php +++ /dev/null @@ -1,55 +0,0 @@ -getParams(); - $acl = $params['acl']; - $page = $params['page']; - $role = $params['role']; - - if (!$acl) { - return $accepted; - } - - $resource = $page->getResource(); - $privilege = $page->getPrivilege(); - - if ($resource || $privilege) { - $accepted = $acl->hasResource($resource) - && $acl->isAllowed($role, $resource, $privilege); - } - - return $accepted; - } -} diff --git a/library/Zend/View/Helper/Navigation/Menu.php b/library/Zend/View/Helper/Navigation/Menu.php deleted file mode 100755 index 29d719923..000000000 --- a/library/Zend/View/Helper/Navigation/Menu.php +++ /dev/null @@ -1,765 +0,0 @@ - element - * - * @var bool - */ - protected $addClassToListItem = false; - - /** - * Whether labels should be escaped - * - * @var bool - */ - protected $escapeLabels = true; - - /** - * Whether only active branch should be rendered - * - * @var bool - */ - protected $onlyActiveBranch = false; - - /** - * Partial view script to use for rendering menu - * - * @var string|array - */ - protected $partial = null; - - /** - * Whether parents should be rendered when only rendering active branch - * - * @var bool - */ - protected $renderParents = true; - - /** - * CSS class to use for the ul element - * - * @var string - */ - protected $ulClass = 'navigation'; - - /** - * CSS class to use for the active li element - * - * @var string - */ - protected $liActiveClass = 'active'; - - /** - * View helper entry point: - * Retrieves helper and optionally sets container to operate on - * - * @param AbstractContainer $container [optional] container to operate on - * @return self - */ - public function __invoke($container = null) - { - if (null !== $container) { - $this->setContainer($container); - } - - return $this; - } - - /** - * Renders menu - * - * Implements {@link HelperInterface::render()}. - * - * If a partial view is registered in the helper, the menu will be rendered - * using the given partial script. If no partial is registered, the menu - * will be rendered as an 'ul' element by the helper's internal method. - * - * @see renderPartial() - * @see renderMenu() - * - * @param AbstractContainer $container [optional] container to render. Default is - * to render the container registered in the helper. - * @return string - */ - public function render($container = null) - { - $partial = $this->getPartial(); - if ($partial) { - return $this->renderPartial($container, $partial); - } - - return $this->renderMenu($container); - } - - /** - * Renders the deepest active menu within [$minDepth, $maxDepth], (called - * from {@link renderMenu()}) - * - * @param AbstractContainer $container container to render - * @param string $ulClass CSS class for first UL - * @param string $indent initial indentation - * @param int|null $minDepth minimum depth - * @param int|null $maxDepth maximum depth - * @param bool $escapeLabels Whether or not to escape the labels - * @param bool $addClassToListItem Whether or not page class applied to
      • element - * @param string $liActiveClass CSS class for active LI - * @return string - */ - protected function renderDeepestMenu( - AbstractContainer $container, - $ulClass, - $indent, - $minDepth, - $maxDepth, - $escapeLabels, - $addClassToListItem, - $liActiveClass - ) { - if (!$active = $this->findActive($container, $minDepth - 1, $maxDepth)) { - return ''; - } - - // special case if active page is one below minDepth - if ($active['depth'] < $minDepth) { - if (!$active['page']->hasPages(!$this->renderInvisible)) { - return ''; - } - } elseif (!$active['page']->hasPages(!$this->renderInvisible)) { - // found pages has no children; render siblings - $active['page'] = $active['page']->getParent(); - } elseif (is_int($maxDepth) && $active['depth'] +1 > $maxDepth) { - // children are below max depth; render siblings - $active['page'] = $active['page']->getParent(); - } - - /* @var $escaper \Zend\View\Helper\EscapeHtmlAttr */ - $escaper = $this->view->plugin('escapeHtmlAttr'); - $ulClass = $ulClass ? ' class="' . $escaper($ulClass) . '"' : ''; - $html = $indent . '' . PHP_EOL; - - foreach ($active['page'] as $subPage) { - if (!$this->accept($subPage)) { - continue; - } - - // render li tag and page - $liClasses = array(); - // Is page active? - if ($subPage->isActive(true)) { - $liClasses[] = $liActiveClass; - } - // Add CSS class from page to
      • - if ($addClassToListItem && $subPage->getClass()) { - $liClasses[] = $subPage->getClass(); - } - $liClass = empty($liClasses) ? '' : ' class="' . $escaper(implode(' ', $liClasses)) . '"'; - - $html .= $indent . ' ' . PHP_EOL; - $html .= $indent . ' ' . $this->htmlify($subPage, $escapeLabels, $addClassToListItem) . PHP_EOL; - $html .= $indent . '
      • ' . PHP_EOL; - } - - $html .= $indent . '
      '; - - return $html; - } - - /** - * Renders helper - * - * Renders a HTML 'ul' for the given $container. If $container is not given, - * the container registered in the helper will be used. - * - * Available $options: - * - * - * @param AbstractContainer $container [optional] container to create menu from. - * Default is to use the container retrieved - * from {@link getContainer()}. - * @param array $options [optional] options for controlling rendering - * @return string - */ - public function renderMenu($container = null, array $options = array()) - { - $this->parseContainer($container); - if (null === $container) { - $container = $this->getContainer(); - } - - - $options = $this->normalizeOptions($options); - - if ($options['onlyActiveBranch'] && !$options['renderParents']) { - $html = $this->renderDeepestMenu($container, - $options['ulClass'], - $options['indent'], - $options['minDepth'], - $options['maxDepth'], - $options['escapeLabels'], - $options['addClassToListItem'], - $options['liActiveClass'] - ); - } else { - $html = $this->renderNormalMenu($container, - $options['ulClass'], - $options['indent'], - $options['minDepth'], - $options['maxDepth'], - $options['onlyActiveBranch'], - $options['escapeLabels'], - $options['addClassToListItem'], - $options['liActiveClass'] - ); - } - - return $html; - } - - /** - * Renders a normal menu (called from {@link renderMenu()}) - * - * @param AbstractContainer $container container to render - * @param string $ulClass CSS class for first UL - * @param string $indent initial indentation - * @param int|null $minDepth minimum depth - * @param int|null $maxDepth maximum depth - * @param bool $onlyActive render only active branch? - * @param bool $escapeLabels Whether or not to escape the labels - * @param bool $addClassToListItem Whether or not page class applied to
    • element - * @param string $liActiveClass CSS class for active LI - * @return string - */ - protected function renderNormalMenu( - AbstractContainer $container, - $ulClass, - $indent, - $minDepth, - $maxDepth, - $onlyActive, - $escapeLabels, - $addClassToListItem, - $liActiveClass - ) { - $html = ''; - - // find deepest active - $found = $this->findActive($container, $minDepth, $maxDepth); - /* @var $escaper \Zend\View\Helper\EscapeHtmlAttr */ - $escaper = $this->view->plugin('escapeHtmlAttr'); - - if ($found) { - $foundPage = $found['page']; - $foundDepth = $found['depth']; - } else { - $foundPage = null; - } - - // create iterator - $iterator = new RecursiveIteratorIterator($container, - RecursiveIteratorIterator::SELF_FIRST); - if (is_int($maxDepth)) { - $iterator->setMaxDepth($maxDepth); - } - - // iterate container - $prevDepth = -1; - foreach ($iterator as $page) { - $depth = $iterator->getDepth(); - $isActive = $page->isActive(true); - if ($depth < $minDepth || !$this->accept($page)) { - // page is below minDepth or not accepted by acl/visibility - continue; - } elseif ($onlyActive && !$isActive) { - // page is not active itself, but might be in the active branch - $accept = false; - if ($foundPage) { - if ($foundPage->hasPage($page)) { - // accept if page is a direct child of the active page - $accept = true; - } elseif ($foundPage->getParent()->hasPage($page)) { - // page is a sibling of the active page... - if (!$foundPage->hasPages(!$this->renderInvisible) || - is_int($maxDepth) && $foundDepth + 1 > $maxDepth) { - // accept if active page has no children, or the - // children are too deep to be rendered - $accept = true; - } - } - } - - if (!$accept) { - continue; - } - } - - // make sure indentation is correct - $depth -= $minDepth; - $myIndent = $indent . str_repeat(' ', $depth); - - if ($depth > $prevDepth) { - // start new ul tag - if ($ulClass && $depth == 0) { - $ulClass = ' class="' . $escaper($ulClass) . '"'; - } else { - $ulClass = ''; - } - $html .= $myIndent . '' . PHP_EOL; - } elseif ($prevDepth > $depth) { - // close li/ul tags until we're at current depth - for ($i = $prevDepth; $i > $depth; $i--) { - $ind = $indent . str_repeat(' ', $i); - $html .= $ind . '
    • ' . PHP_EOL; - $html .= $ind . '
    ' . PHP_EOL; - } - // close previous li tag - $html .= $myIndent . ' ' . PHP_EOL; - } else { - // close previous li tag - $html .= $myIndent . ' ' . PHP_EOL; - } - - // render li tag and page - $liClasses = array(); - // Is page active? - if ($isActive) { - $liClasses[] = $liActiveClass; - } - // Add CSS class from page to
  • - if ($addClassToListItem && $page->getClass()) { - $liClasses[] = $page->getClass(); - } - $liClass = empty($liClasses) ? '' : ' class="' . $escaper(implode(' ', $liClasses)) . '"'; - - $html .= $myIndent . ' ' . PHP_EOL - . $myIndent . ' ' . $this->htmlify($page, $escapeLabels, $addClassToListItem) . PHP_EOL; - - // store as previous depth for next iteration - $prevDepth = $depth; - } - - if ($html) { - // done iterating container; close open ul/li tags - for ($i = $prevDepth+1; $i > 0; $i--) { - $myIndent = $indent . str_repeat(' ', $i-1); - $html .= $myIndent . '
  • ' . PHP_EOL - . $myIndent . '' . PHP_EOL; - } - $html = rtrim($html, PHP_EOL); - } - - return $html; - } - - /** - * Renders the given $container by invoking the partial view helper - * - * The container will simply be passed on as a model to the view script - * as-is, and will be available in the partial script as 'container', e.g. - * echo 'Number of pages: ', count($this->container);. - * - * @param AbstractContainer $container [optional] container to pass to view - * script. Default is to use the container - * registered in the helper. - * @param string|array $partial [optional] partial view script to use. - * Default is to use the partial - * registered in the helper. If an array - * is given, it is expected to contain two - * values; the partial view script to use, - * and the module where the script can be - * found. - * @return string - * @throws Exception\RuntimeException if no partial provided - * @throws Exception\InvalidArgumentException if partial is invalid array - */ - public function renderPartial($container = null, $partial = null) - { - $this->parseContainer($container); - if (null === $container) { - $container = $this->getContainer(); - } - - if (null === $partial) { - $partial = $this->getPartial(); - } - - if (empty($partial)) { - throw new Exception\RuntimeException( - 'Unable to render menu: No partial view script provided' - ); - } - - $model = array( - 'container' => $container - ); - - /** @var \Zend\View\Helper\Partial $partialHelper */ - $partialHelper = $this->view->plugin('partial'); - - if (is_array($partial)) { - if (count($partial) != 2) { - throw new Exception\InvalidArgumentException( - 'Unable to render menu: A view partial supplied as ' - . 'an array must contain two values: partial view ' - . 'script and module where script can be found' - ); - } - - return $partialHelper($partial[0], $model); - } - - return $partialHelper($partial, $model); - } - - /** - * Renders the inner-most sub menu for the active page in the $container - * - * This is a convenience method which is equivalent to the following call: - * - * renderMenu($container, array( - * 'indent' => $indent, - * 'ulClass' => $ulClass, - * 'minDepth' => null, - * 'maxDepth' => null, - * 'onlyActiveBranch' => true, - * 'renderParents' => false, - * 'liActiveClass' => $liActiveClass - * )); - * - * - * @param AbstractContainer $container [optional] container to - * render. Default is to render - * the container registered in - * the helper. - * @param string $ulClass [optional] CSS class to - * use for UL element. Default - * is to use the value from - * {@link getUlClass()}. - * @param string|int $indent [optional] indentation as - * a string or number of - * spaces. Default is to use - * the value retrieved from - * {@link getIndent()}. - * @param string $liActiveClass [optional] CSS class to - * use for UL element. Default - * is to use the value from - * {@link getUlClass()}. - * @return string - */ - public function renderSubMenu( - AbstractContainer $container = null, - $ulClass = null, - $indent = null, - $liActiveClass = null - ) { - return $this->renderMenu($container, array( - 'indent' => $indent, - 'ulClass' => $ulClass, - 'minDepth' => null, - 'maxDepth' => null, - 'onlyActiveBranch' => true, - 'renderParents' => false, - 'escapeLabels' => true, - 'addClassToListItem' => false, - 'liActiveClass' => $liActiveClass - )); - } - - /** - * Returns an HTML string containing an 'a' element for the given page if - * the page's href is not empty, and a 'span' element if it is empty - * - * Overrides {@link AbstractHelper::htmlify()}. - * - * @param AbstractPage $page page to generate HTML for - * @param bool $escapeLabel Whether or not to escape the label - * @param bool $addClassToListItem Whether or not to add the page class to the list item - * @return string - */ - public function htmlify(AbstractPage $page, $escapeLabel = true, $addClassToListItem = false) - { - // get attribs for element - $attribs = array( - 'id' => $page->getId(), - 'title' => $this->translate($page->getTitle(), $page->getTextDomain()), - ); - - if ($addClassToListItem === false) { - $attribs['class'] = $page->getClass(); - } - - // does page have a href? - $href = $page->getHref(); - if ($href) { - $element = 'a'; - $attribs['href'] = $href; - $attribs['target'] = $page->getTarget(); - } else { - $element = 'span'; - } - - $html = '<' . $element . $this->htmlAttribs($attribs) . '>'; - $label = $this->translate($page->getLabel(), $page->getTextDomain()); - if ($escapeLabel === true) { - /** @var \Zend\View\Helper\EscapeHtml $escaper */ - $escaper = $this->view->plugin('escapeHtml'); - $html .= $escaper($label); - } else { - $html .= $label; - } - $html .= ''; - - return $html; - } - - /** - * Normalizes given render options - * - * @param array $options [optional] options to normalize - * @return array - */ - protected function normalizeOptions(array $options = array()) - { - if (isset($options['indent'])) { - $options['indent'] = $this->getWhitespace($options['indent']); - } else { - $options['indent'] = $this->getIndent(); - } - - if (isset($options['ulClass']) && $options['ulClass'] !== null) { - $options['ulClass'] = (string) $options['ulClass']; - } else { - $options['ulClass'] = $this->getUlClass(); - } - - if (array_key_exists('minDepth', $options)) { - if (null !== $options['minDepth']) { - $options['minDepth'] = (int) $options['minDepth']; - } - } else { - $options['minDepth'] = $this->getMinDepth(); - } - - if ($options['minDepth'] < 0 || $options['minDepth'] === null) { - $options['minDepth'] = 0; - } - - if (array_key_exists('maxDepth', $options)) { - if (null !== $options['maxDepth']) { - $options['maxDepth'] = (int) $options['maxDepth']; - } - } else { - $options['maxDepth'] = $this->getMaxDepth(); - } - - if (!isset($options['onlyActiveBranch'])) { - $options['onlyActiveBranch'] = $this->getOnlyActiveBranch(); - } - - if (!isset($options['escapeLabels'])) { - $options['escapeLabels'] = $this->escapeLabels; - } - - if (!isset($options['renderParents'])) { - $options['renderParents'] = $this->getRenderParents(); - } - - if (!isset($options['addClassToListItem'])) { - $options['addClassToListItem'] = $this->getAddClassToListItem(); - } - - if (isset($options['liActiveClass']) && $options['liActiveClass'] !== null) { - $options['liActiveClass'] = (string) $options['liActiveClass']; - } else { - $options['liActiveClass'] = $this->getLiActiveClass(); - } - - return $options; - } - - /** - * Sets a flag indicating whether labels should be escaped - * - * @param bool $flag [optional] escape labels - * @return self - */ - public function escapeLabels($flag = true) - { - $this->escapeLabels = (bool) $flag; - return $this; - } - - /** - * Enables/disables page class applied to
  • element - * - * @param bool $flag [optional] page class applied to
  • element - * Default is true. - * @return self fluent interface, returns self - */ - public function setAddClassToListItem($flag = true) - { - $this->addClassToListItem = (bool) $flag; - return $this; - } - - /** - * Returns flag indicating whether page class should be applied to
  • element - * - * By default, this value is false. - * - * @return bool whether parents should be rendered - */ - public function getAddClassToListItem() - { - return $this->addClassToListItem; - } - - /** - * Sets a flag indicating whether only active branch should be rendered - * - * @param bool $flag [optional] render only active branch. - * @return self - */ - public function setOnlyActiveBranch($flag = true) - { - $this->onlyActiveBranch = (bool) $flag; - return $this; - } - - /** - * Returns a flag indicating whether only active branch should be rendered - * - * By default, this value is false, meaning the entire menu will be - * be rendered. - * - * @return bool - */ - public function getOnlyActiveBranch() - { - return $this->onlyActiveBranch; - } - - /** - * Sets which partial view script to use for rendering menu - * - * @param string|array $partial partial view script or null. If an array is - * given, it is expected to contain two - * values; the partial view script to use, - * and the module where the script can be - * found. - * @return self - */ - public function setPartial($partial) - { - if (null === $partial || is_string($partial) || is_array($partial)) { - $this->partial = $partial; - } - - return $this; - } - - /** - * Returns partial view script to use for rendering menu - * - * @return string|array|null - */ - public function getPartial() - { - return $this->partial; - } - - /** - * Enables/disables rendering of parents when only rendering active branch - * - * See {@link setOnlyActiveBranch()} for more information. - * - * @param bool $flag [optional] render parents when rendering active branch. - * @return self - */ - public function setRenderParents($flag = true) - { - $this->renderParents = (bool) $flag; - return $this; - } - - /** - * Returns flag indicating whether parents should be rendered when rendering - * only the active branch - * - * By default, this value is true. - * - * @return bool - */ - public function getRenderParents() - { - return $this->renderParents; - } - - /** - * Sets CSS class to use for the first 'ul' element when rendering - * - * @param string $ulClass CSS class to set - * @return self - */ - public function setUlClass($ulClass) - { - if (is_string($ulClass)) { - $this->ulClass = $ulClass; - } - - return $this; - } - - /** - * Returns CSS class to use for the first 'ul' element when rendering - * - * @return string - */ - public function getUlClass() - { - return $this->ulClass; - } - - /** - * Sets CSS class to use for the active 'li' element when rendering - * - * @param string $liActiveClass CSS class to set - * @return self - */ - public function setLiActiveClass($liActiveClass) - { - if (is_string($liActiveClass)) { - $this->liActiveClass = $liActiveClass; - } - - return $this; - } - - /** - * Returns CSS class to use for the active 'li' element when rendering - * - * @return string - */ - public function getLiActiveClass() - { - return $this->liActiveClass; - } -} diff --git a/library/Zend/View/Helper/Navigation/PluginManager.php b/library/Zend/View/Helper/Navigation/PluginManager.php deleted file mode 100755 index 8faf86eb3..000000000 --- a/library/Zend/View/Helper/Navigation/PluginManager.php +++ /dev/null @@ -1,58 +0,0 @@ - 'Zend\View\Helper\Navigation\Breadcrumbs', - 'links' => 'Zend\View\Helper\Navigation\Links', - 'menu' => 'Zend\View\Helper\Navigation\Menu', - 'sitemap' => 'Zend\View\Helper\Navigation\Sitemap', - ); - - /** - * Validate the plugin - * - * Checks that the helper loaded is an instance of AbstractHelper. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidArgumentException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof AbstractHelper) { - // we're okay - return; - } - - throw new Exception\InvalidArgumentException(sprintf( - 'Plugin of type %s is invalid; must implement %s\AbstractHelper', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/View/Helper/Navigation/Sitemap.php b/library/Zend/View/Helper/Navigation/Sitemap.php deleted file mode 100755 index 2ba2b4a4b..000000000 --- a/library/Zend/View/Helper/Navigation/Sitemap.php +++ /dev/null @@ -1,441 +0,0 @@ - tag - * - * @var string - */ - const SITEMAP_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; - - /** - * Schema URL - * - * @var string - */ - const SITEMAP_XSD = 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'; - - /** - * Whether XML output should be formatted - * - * @var bool - */ - protected $formatOutput = false; - - /** - * Server url - * - * @var string - */ - protected $serverUrl; - - /** - * List of urls in the sitemap - * - * @var array - */ - protected $urls = array(); - - /** - * Whether sitemap should be validated using Zend\Validate\Sitemap\* - * - * @var bool - */ - protected $useSitemapValidators = true; - - /** - * Whether sitemap should be schema validated when generated - * - * @var bool - */ - protected $useSchemaValidation = false; - - /** - * Whether the XML declaration should be included in XML output - * - * @var bool - */ - protected $useXmlDeclaration = true; - - /** - * Helper entry point - * - * @param string|AbstractContainer $container container to operate on - * @return Sitemap - */ - public function __invoke($container = null) - { - if (null !== $container) { - $this->setContainer($container); - } - - return $this; - } - - /** - * Renders helper - * - * Implements {@link HelperInterface::render()}. - * - * @param AbstractContainer $container [optional] container to render. Default is - * to render the container registered in the helper. - * @return string - */ - public function render($container = null) - { - $dom = $this->getDomSitemap($container); - $xml = $this->getUseXmlDeclaration() ? - $dom->saveXML() : - $dom->saveXML($dom->documentElement); - - return rtrim($xml, PHP_EOL); - } - - /** - * Returns a DOMDocument containing the Sitemap XML for the given container - * - * @param AbstractContainer $container [optional] container to get - * breadcrumbs from, defaults - * to what is registered in the - * helper - * @return DOMDocument DOM representation of the - * container - * @throws Exception\RuntimeException if schema validation is on - * and the sitemap is invalid - * according to the sitemap - * schema, or if sitemap - * validators are used and the - * loc element fails validation - */ - public function getDomSitemap(AbstractContainer $container = null) - { - // Reset the urls - $this->urls = array(); - - if (null === $container) { - $container = $this->getContainer(); - } - - // check if we should validate using our own validators - if ($this->getUseSitemapValidators()) { - // create validators - $locValidator = new \Zend\Validator\Sitemap\Loc(); - $lastmodValidator = new \Zend\Validator\Sitemap\Lastmod(); - $changefreqValidator = new \Zend\Validator\Sitemap\Changefreq(); - $priorityValidator = new \Zend\Validator\Sitemap\Priority(); - } - - // create document - $dom = new DOMDocument('1.0', 'UTF-8'); - $dom->formatOutput = $this->getFormatOutput(); - - // ...and urlset (root) element - $urlSet = $dom->createElementNS(self::SITEMAP_NS, 'urlset'); - $dom->appendChild($urlSet); - - // create iterator - $iterator = new RecursiveIteratorIterator($container, - RecursiveIteratorIterator::SELF_FIRST); - - $maxDepth = $this->getMaxDepth(); - if (is_int($maxDepth)) { - $iterator->setMaxDepth($maxDepth); - } - $minDepth = $this->getMinDepth(); - if (!is_int($minDepth) || $minDepth < 0) { - $minDepth = 0; - } - - // iterate container - foreach ($iterator as $page) { - if ($iterator->getDepth() < $minDepth || !$this->accept($page)) { - // page should not be included - continue; - } - - // get absolute url from page - if (!$url = $this->url($page)) { - // skip page if it has no url (rare case) - // or already is in the sitemap - continue; - } - - // create url node for this page - $urlNode = $dom->createElementNS(self::SITEMAP_NS, 'url'); - $urlSet->appendChild($urlNode); - - if ($this->getUseSitemapValidators() - && !$locValidator->isValid($url) - ) { - throw new Exception\RuntimeException(sprintf( - 'Encountered an invalid URL for Sitemap XML: "%s"', - $url - )); - } - - // put url in 'loc' element - $urlNode->appendChild($dom->createElementNS(self::SITEMAP_NS, - 'loc', $url)); - - // add 'lastmod' element if a valid lastmod is set in page - if (isset($page->lastmod)) { - $lastmod = strtotime((string) $page->lastmod); - - // prevent 1970-01-01... - if ($lastmod !== false) { - $lastmod = date('c', $lastmod); - } - - if (!$this->getUseSitemapValidators() || - $lastmodValidator->isValid($lastmod)) { - $urlNode->appendChild( - $dom->createElementNS(self::SITEMAP_NS, 'lastmod', - $lastmod) - ); - } - } - - // add 'changefreq' element if a valid changefreq is set in page - if (isset($page->changefreq)) { - $changefreq = $page->changefreq; - if (!$this->getUseSitemapValidators() || - $changefreqValidator->isValid($changefreq)) { - $urlNode->appendChild( - $dom->createElementNS(self::SITEMAP_NS, 'changefreq', - $changefreq) - ); - } - } - - // add 'priority' element if a valid priority is set in page - if (isset($page->priority)) { - $priority = $page->priority; - if (!$this->getUseSitemapValidators() || - $priorityValidator->isValid($priority)) { - $urlNode->appendChild( - $dom->createElementNS(self::SITEMAP_NS, 'priority', $priority) - ); - } - } - } - - // validate using schema if specified - if ($this->getUseSchemaValidation()) { - ErrorHandler::start(); - $test = $dom->schemaValidate(self::SITEMAP_XSD); - $error = ErrorHandler::stop(); - if (!$test) { - throw new Exception\RuntimeException(sprintf( - 'Sitemap is invalid according to XML Schema at "%s"', - self::SITEMAP_XSD - ), 0, $error); - } - } - - return $dom; - } - - /** - * Returns an escaped absolute URL for the given page - * - * @param AbstractPage $page - * @return string - */ - public function url(AbstractPage $page) - { - $href = $page->getHref(); - - if (!isset($href{0})) { - // no href - return ''; - } elseif ($href{0} == '/') { - // href is relative to root; use serverUrl helper - $url = $this->getServerUrl() . $href; - } elseif (preg_match('/^[a-z]+:/im', (string) $href)) { - // scheme is given in href; assume absolute URL already - $url = (string) $href; - } else { - // href is relative to current document; use url helpers - $basePathHelper = $this->getView()->plugin('basepath'); - $curDoc = $basePathHelper(); - $curDoc = ('/' == $curDoc) ? '' : trim($curDoc, '/'); - $url = rtrim($this->getServerUrl(), '/') . '/' - . $curDoc - . (empty($curDoc) ? '' : '/') . $href; - } - - if (! in_array($url, $this->urls)) { - $this->urls[] = $url; - return $this->xmlEscape($url); - } - - return null; - } - - /** - * Escapes string for XML usage - * - * @param string $string - * @return string - */ - protected function xmlEscape($string) - { - $escaper = $this->view->plugin('escapeHtml'); - return $escaper($string); - } - - /** - * Sets whether XML output should be formatted - * - * @param bool $formatOutput - * @return Sitemap - */ - public function setFormatOutput($formatOutput = true) - { - $this->formatOutput = (bool) $formatOutput; - return $this; - } - - /** - * Returns whether XML output should be formatted - * - * @return bool - */ - public function getFormatOutput() - { - return $this->formatOutput; - } - - /** - * Sets server url (scheme and host-related stuff without request URI) - * - * E.g. http://www.example.com - * - * @param string $serverUrl - * @return Sitemap - * @throws Exception\InvalidArgumentException - */ - public function setServerUrl($serverUrl) - { - $uri = Uri\UriFactory::factory($serverUrl); - $uri->setFragment(''); - $uri->setPath(''); - $uri->setQuery(''); - - if ($uri->isValid()) { - $this->serverUrl = $uri->toString(); - } else { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid server URL: "%s"', - $serverUrl - )); - } - - return $this; - } - - /** - * Returns server URL - * - * @return string - */ - public function getServerUrl() - { - if (!isset($this->serverUrl)) { - $serverUrlHelper = $this->getView()->plugin('serverUrl'); - $this->serverUrl = $serverUrlHelper(); - } - - return $this->serverUrl; - } - - /** - * Sets whether sitemap should be validated using Zend\Validate\Sitemap_* - * - * @param bool $useSitemapValidators - * @return Sitemap - */ - public function setUseSitemapValidators($useSitemapValidators) - { - $this->useSitemapValidators = (bool) $useSitemapValidators; - return $this; - } - - /** - * Returns whether sitemap should be validated using Zend\Validate\Sitemap_* - * - * @return bool - */ - public function getUseSitemapValidators() - { - return $this->useSitemapValidators; - } - - /** - * Sets whether sitemap should be schema validated when generated - * - * @param bool $schemaValidation - * @return Sitemap - */ - public function setUseSchemaValidation($schemaValidation) - { - $this->useSchemaValidation = (bool) $schemaValidation; - return $this; - } - - /** - * Returns true if sitemap should be schema validated when generated - * - * @return bool - */ - public function getUseSchemaValidation() - { - return $this->useSchemaValidation; - } - - /** - * Sets whether the XML declaration should be used in output - * - * @param bool $useXmlDecl - * @return Sitemap - */ - public function setUseXmlDeclaration($useXmlDecl) - { - $this->useXmlDeclaration = (bool) $useXmlDecl; - return $this; - } - - /** - * Returns whether the XML declaration should be used in output - * - * @return bool - */ - public function getUseXmlDeclaration() - { - return $this->useXmlDeclaration; - } -} diff --git a/library/Zend/View/Helper/PaginationControl.php b/library/Zend/View/Helper/PaginationControl.php deleted file mode 100755 index 9963fdd35..000000000 --- a/library/Zend/View/Helper/PaginationControl.php +++ /dev/null @@ -1,131 +0,0 @@ -paginator is set and, - * if so, uses that. Also, if no scrolling style or partial are specified, - * the defaults will be used (if set). - * - * @param Paginator\Paginator $paginator (Optional) - * @param string $scrollingStyle (Optional) Scrolling style - * @param string $partial (Optional) View partial - * @param array|string $params (Optional) params to pass to the partial - * @throws Exception\RuntimeException if no paginator or no view partial provided - * @throws Exception\InvalidArgumentException if partial is invalid array - * @return string - */ - public function __invoke(Paginator\Paginator $paginator = null, $scrollingStyle = null, $partial = null, $params = null) - { - if ($paginator === null) { - if (isset($this->view->paginator) and $this->view->paginator !== null and $this->view->paginator instanceof Paginator\Paginator) { - $paginator = $this->view->paginator; - } else { - throw new Exception\RuntimeException('No paginator instance provided or incorrect type'); - } - } - - if ($partial === null) { - if (static::$defaultViewPartial === null) { - throw new Exception\RuntimeException('No view partial provided and no default set'); - } - - $partial = static::$defaultViewPartial; - } - - if ($scrollingStyle === null) { - $scrollingStyle = static::$defaultScrollingStyle; - } - - $pages = get_object_vars($paginator->getPages($scrollingStyle)); - - if ($params !== null) { - $pages = array_merge($pages, (array) $params); - } - - if (is_array($partial)) { - if (count($partial) != 2) { - throw new Exception\InvalidArgumentException( - 'A view partial supplied as an array must contain two values: the filename and its module' - ); - } - - if ($partial[1] !== null) { - $partialHelper = $this->view->plugin('partial'); - return $partialHelper($partial[0], $pages); - } - - $partial = $partial[0]; - } - - $partialHelper = $this->view->plugin('partial'); - return $partialHelper($partial, $pages); - } - - /** - * Sets the default Scrolling Style - * - * @param string $style string 'all' | 'elastic' | 'sliding' | 'jumping' - */ - public static function setDefaultScrollingStyle($style) - { - static::$defaultScrollingStyle = $style; - } - - /** - * Gets the default scrolling style - * - * @return string - */ - public static function getDefaultScrollingStyle() - { - return static::$defaultScrollingStyle; - } - - /** - * Sets the default view partial. - * - * @param string|array $partial View partial - */ - public static function setDefaultViewPartial($partial) - { - static::$defaultViewPartial = $partial; - } - - /** - * Gets the default view partial - * - * @return string|array - */ - public static function getDefaultViewPartial() - { - return static::$defaultViewPartial; - } -} diff --git a/library/Zend/View/Helper/Partial.php b/library/Zend/View/Helper/Partial.php deleted file mode 100755 index 444f161b9..000000000 --- a/library/Zend/View/Helper/Partial.php +++ /dev/null @@ -1,94 +0,0 @@ -getView()->render($name); - } - - if (is_scalar($values)) { - $values = array(); - } elseif ($values instanceof ModelInterface) { - $values = $values->getVariables(); - } elseif (is_object($values)) { - if (null !== ($objectKey = $this->getObjectKey())) { - $values = array($objectKey => $values); - } elseif (method_exists($values, 'toArray')) { - $values = $values->toArray(); - } else { - $values = get_object_vars($values); - } - } - - return $this->getView()->render($name, $values); - } - - /** - * Set object key - * - * @param string $key - * @return Partial - */ - public function setObjectKey($key) - { - if (null === $key) { - $this->objectKey = null; - return $this; - } - - $this->objectKey = (string) $key; - - return $this; - } - - /** - * Retrieve object key - * - * The objectKey is the variable to which an object in the iterator will be - * assigned. - * - * @return null|string - */ - public function getObjectKey() - { - return $this->objectKey; - } -} diff --git a/library/Zend/View/Helper/PartialLoop.php b/library/Zend/View/Helper/PartialLoop.php deleted file mode 100755 index f66297e67..000000000 --- a/library/Zend/View/Helper/PartialLoop.php +++ /dev/null @@ -1,77 +0,0 @@ -toArray(); - } else { - throw new Exception\InvalidArgumentException('PartialLoop helper requires iterable data'); - } - } - - // reset the counter if it's called again - $this->partialCounter = 0; - $content = ''; - - foreach ($values as $item) { - $this->partialCounter++; - $content .= parent::__invoke($name, $item); - } - - return $content; - } - - /** - * Get the partial counter - * - * @return int - */ - public function getPartialCounter() - { - return $this->partialCounter; - } -} diff --git a/library/Zend/View/Helper/Placeholder.php b/library/Zend/View/Helper/Placeholder.php deleted file mode 100755 index 297c17a55..000000000 --- a/library/Zend/View/Helper/Placeholder.php +++ /dev/null @@ -1,98 +0,0 @@ -getContainer($name); - } - - /** - * createContainer - * - * @param string $key - * @param array $value - * @return Container\AbstractContainer - */ - public function createContainer($key, array $value = array()) - { - $key = (string) $key; - - $this->items[$key] = new $this->containerClass($value); - return $this->items[$key]; - } - - /** - * Retrieve a placeholder container - * - * @param string $key - * @return Container\AbstractContainer - */ - public function getContainer($key) - { - $key = (string) $key; - if (isset($this->items[$key])) { - return $this->items[$key]; - } - - $container = $this->createContainer($key); - - return $container; - } - - /** - * Does a particular container exist? - * - * @param string $key - * @return bool - */ - public function containerExists($key) - { - $key = (string) $key; - $return = array_key_exists($key, $this->items); - return $return; - } -} diff --git a/library/Zend/View/Helper/Placeholder/Container.php b/library/Zend/View/Helper/Placeholder/Container.php deleted file mode 100755 index 35220176c..000000000 --- a/library/Zend/View/Helper/Placeholder/Container.php +++ /dev/null @@ -1,17 +0,0 @@ -toString(); - } - - /** - * Render the placeholder - * - * @param null|int|string $indent - * @return string - */ - public function toString($indent = null) - { - $indent = ($indent !== null) - ? $this->getWhitespace($indent) - : $this->getIndent(); - - $items = $this->getArrayCopy(); - $return = $indent - . $this->getPrefix() - . implode($this->getSeparator(), $items) - . $this->getPostfix(); - $return = preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return); - - return $return; - } - - /** - * Start capturing content to push into placeholder - * - * @param string $type How to capture content into placeholder; append, prepend, or set - * @param mixed $key Key to which to capture content - * @throws Exception\RuntimeException if nested captures detected - * @return void - */ - public function captureStart($type = AbstractContainer::APPEND, $key = null) - { - if ($this->captureLock) { - throw new Exception\RuntimeException( - 'Cannot nest placeholder captures for the same placeholder' - ); - } - - $this->captureLock = true; - $this->captureType = $type; - if ((null !== $key) && is_scalar($key)) { - $this->captureKey = (string) $key; - } - ob_start(); - } - - /** - * End content capture - * - * @return void - */ - public function captureEnd() - { - $data = ob_get_clean(); - $key = null; - $this->captureLock = false; - if (null !== $this->captureKey) { - $key = $this->captureKey; - } - switch ($this->captureType) { - case self::SET: - if (null !== $key) { - $this[$key] = $data; - } else { - $this->exchangeArray(array($data)); - } - break; - case self::PREPEND: - if (null !== $key) { - $array = array($key => $data); - $values = $this->getArrayCopy(); - $final = $array + $values; - $this->exchangeArray($final); - } else { - $this->prepend($data); - } - break; - case self::APPEND: - default: - if (null !== $key) { - if (empty($this[$key])) { - $this[$key] = $data; - } else { - $this[$key] .= $data; - } - } else { - $this[$this->nextIndex()] = $data; - } - break; - } - } - - /** - * Get keys - * - * @return array - */ - public function getKeys() - { - $array = $this->getArrayCopy(); - - return array_keys($array); - } - - /** - * Retrieve container value - * - * If single element registered, returns that element; otherwise, - * serializes to array. - * - * @return mixed - */ - public function getValue() - { - if (1 == count($this)) { - $keys = $this->getKeys(); - $key = array_shift($keys); - return $this[$key]; - } - - return $this->getArrayCopy(); - } - - /** - * Retrieve whitespace representation of $indent - * - * @param int|string $indent - * @return string - */ - public function getWhitespace($indent) - { - if (is_int($indent)) { - $indent = str_repeat(' ', $indent); - } - - return (string) $indent; - } - - /** - * Set a single value - * - * @param mixed $value - * @return void - */ - public function set($value) - { - $this->exchangeArray(array($value)); - - return $this; - } - - /** - * Prepend a value to the top of the container - * - * @param mixed $value - * @return self - */ - public function prepend($value) - { - $values = $this->getArrayCopy(); - array_unshift($values, $value); - $this->exchangeArray($values); - - return $this; - } - - /** - * Append a value to the end of the container - * - * @param mixed $value - * @return self - */ - public function append($value) - { - parent::append($value); - return $this; - } - - /** - * Next Index as defined by the PHP manual - * - * @return int - */ - public function nextIndex() - { - $keys = $this->getKeys(); - if (0 == count($keys)) { - return 0; - } - - return $nextIndex = max($keys) + 1; - } - - /** - * Set the indentation string for __toString() serialization, - * optionally, if a number is passed, it will be the number of spaces - * - * @param string|int $indent - * @return self - */ - public function setIndent($indent) - { - $this->indent = $this->getWhitespace($indent); - return $this; - } - - /** - * Retrieve indentation - * - * @return string - */ - public function getIndent() - { - return $this->indent; - } - - /** - * Set postfix for __toString() serialization - * - * @param string $postfix - * @return self - */ - public function setPostfix($postfix) - { - $this->postfix = (string) $postfix; - return $this; - } - - /** - * Retrieve postfix - * - * @return string - */ - public function getPostfix() - { - return $this->postfix; - } - - /** - * Set prefix for __toString() serialization - * - * @param string $prefix - * @return self - */ - public function setPrefix($prefix) - { - $this->prefix = (string) $prefix; - return $this; - } - - /** - * Retrieve prefix - * - * @return string - */ - public function getPrefix() - { - return $this->prefix; - } - - /** - * Set separator for __toString() serialization - * - * Used to implode elements in container - * - * @param string $separator - * @return self - */ - public function setSeparator($separator) - { - $this->separator = (string) $separator; - return $this; - } - - /** - * Retrieve separator - * - * @return string - */ - public function getSeparator() - { - return $this->separator; - } -} diff --git a/library/Zend/View/Helper/Placeholder/Container/AbstractStandalone.php b/library/Zend/View/Helper/Placeholder/Container/AbstractStandalone.php deleted file mode 100755 index 619ba7073..000000000 --- a/library/Zend/View/Helper/Placeholder/Container/AbstractStandalone.php +++ /dev/null @@ -1,376 +0,0 @@ -setContainer($this->getContainer()); - } - - /** - * Overload - * - * Proxy to container methods - * - * @param string $method - * @param array $args - * @throws Exception\BadMethodCallException - * @return mixed - */ - public function __call($method, $args) - { - $container = $this->getContainer(); - if (method_exists($container, $method)) { - $return = call_user_func_array(array($container, $method), $args); - if ($return === $container) { - // If the container is returned, we really want the current object - return $this; - } - return $return; - } - - throw new Exception\BadMethodCallException('Method "' . $method . '" does not exist'); - } - - /** - * Overloading: set property value - * - * @param string $key - * @param mixed $value - * @return void - */ - public function __set($key, $value) - { - $container = $this->getContainer(); - $container[$key] = $value; - } - - /** - * Overloading: retrieve property - * - * @param string $key - * @return mixed - */ - public function __get($key) - { - $container = $this->getContainer(); - if (isset($container[$key])) { - return $container[$key]; - } - - return null; - } - - /** - * Overloading: check if property is set - * - * @param string $key - * @return bool - */ - public function __isset($key) - { - $container = $this->getContainer(); - return isset($container[$key]); - } - - /** - * Overloading: unset property - * - * @param string $key - * @return void - */ - public function __unset($key) - { - $container = $this->getContainer(); - if (isset($container[$key])) { - unset($container[$key]); - } - } - - /** - * Cast to string representation - * - * @return string - */ - public function __toString() - { - return $this->toString(); - } - - /** - * String representation - * - * @return string - */ - public function toString() - { - return $this->getContainer()->toString(); - } - - /** - * Escape a string - * - * @param string $string - * @return string - */ - protected function escape($string) - { - if ($this->getView() instanceof RendererInterface - && method_exists($this->getView(), 'getEncoding') - ) { - $escaper = $this->getView()->plugin('escapeHtml'); - return $escaper((string) $string); - } - - return $this->getEscaper()->escapeHtml((string) $string); - } - - /** - * Set whether or not auto escaping should be used - * - * @param bool $autoEscape whether or not to auto escape output - * @return AbstractStandalone - */ - public function setAutoEscape($autoEscape = true) - { - $this->autoEscape = ($autoEscape) ? true : false; - return $this; - } - - /** - * Return whether autoEscaping is enabled or disabled - * - * return bool - */ - public function getAutoEscape() - { - return $this->autoEscape; - } - - /** - * Set container on which to operate - * - * @param AbstractContainer $container - * @return AbstractStandalone - */ - public function setContainer(AbstractContainer $container) - { - $this->container = $container; - return $this; - } - - /** - * Retrieve placeholder container - * - * @return AbstractContainer - */ - public function getContainer() - { - if (!$this->container instanceof AbstractContainer) { - $this->container = new $this->containerClass(); - } - return $this->container; - } - - /** - * Delete a container - * - * @return bool - */ - public function deleteContainer() - { - if (null != $this->container) { - $this->container = null; - return true; - } - - return false; - } - - /** - * Set the container class to use - * - * @param string $name - * @throws Exception\InvalidArgumentException - * @throws Exception\DomainException - * @return \Zend\View\Helper\Placeholder\Container\AbstractStandalone - */ - public function setContainerClass($name) - { - if (!class_exists($name)) { - throw new Exception\DomainException( - sprintf( - '%s expects a valid container class name; received "%s", which did not resolve', - __METHOD__, - $name - ) - ); - } - - if (!in_array('Zend\View\Helper\Placeholder\Container\AbstractContainer', class_parents($name))) { - throw new Exception\InvalidArgumentException('Invalid Container class specified'); - } - - $this->containerClass = $name; - return $this; - } - - /** - * Retrieve the container class - * - * @return string - */ - public function getContainerClass() - { - return $this->containerClass; - } - - /** - * Set Escaper instance - * - * @param Escaper $escaper - * @return AbstractStandalone - */ - public function setEscaper(Escaper $escaper) - { - $encoding = $escaper->getEncoding(); - $this->escapers[$encoding] = $escaper; - - return $this; - } - - /** - * Get Escaper instance - * - * Lazy-loads one if none available - * - * @param string|null $enc Encoding to use - * @return mixed - */ - public function getEscaper($enc = 'UTF-8') - { - $enc = strtolower($enc); - if (!isset($this->escapers[$enc])) { - $this->setEscaper(new Escaper($enc)); - } - - return $this->escapers[$enc]; - } - - /** - * Countable - * - * @return int - */ - public function count() - { - $container = $this->getContainer(); - return count($container); - } - - /** - * ArrayAccess: offsetExists - * - * @param string|int $offset - * @return bool - */ - public function offsetExists($offset) - { - return $this->getContainer()->offsetExists($offset); - } - - /** - * ArrayAccess: offsetGet - * - * @param string|int $offset - * @return mixed - */ - public function offsetGet($offset) - { - return $this->getContainer()->offsetGet($offset); - } - - /** - * ArrayAccess: offsetSet - * - * @param string|int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset, $value) - { - return $this->getContainer()->offsetSet($offset, $value); - } - - /** - * ArrayAccess: offsetUnset - * - * @param string|int $offset - * @return void - */ - public function offsetUnset($offset) - { - return $this->getContainer()->offsetUnset($offset); - } - - /** - * IteratorAggregate: get Iterator - * - * @return \Iterator - */ - public function getIterator() - { - return $this->getContainer()->getIterator(); - } -} diff --git a/library/Zend/View/Helper/Placeholder/Registry.php b/library/Zend/View/Helper/Placeholder/Registry.php deleted file mode 100755 index f86b4e1ad..000000000 --- a/library/Zend/View/Helper/Placeholder/Registry.php +++ /dev/null @@ -1,185 +0,0 @@ -items[$key] = $container; - - return $this; - } - - /** - * Retrieve a placeholder container - * - * @param string $key - * @return Container\AbstractContainer - */ - public function getContainer($key) - { - $key = (string) $key; - if (isset($this->items[$key])) { - return $this->items[$key]; - } - - $container = $this->createContainer($key); - - return $container; - } - - /** - * Does a particular container exist? - * - * @param string $key - * @return bool - */ - public function containerExists($key) - { - $key = (string) $key; - - return array_key_exists($key, $this->items); - } - - /** - * createContainer - * - * @param string $key - * @param array $value - * @return Container\AbstractContainer - */ - public function createContainer($key, array $value = array()) - { - $key = (string) $key; - - $this->items[$key] = new $this->containerClass($value); - - return $this->items[$key]; - } - - /** - * Delete a container - * - * @param string $key - * @return bool - */ - public function deleteContainer($key) - { - $key = (string) $key; - if (isset($this->items[$key])) { - unset($this->items[$key]); - return true; - } - - return false; - } - - /** - * Set the container class to use - * - * @param string $name - * @throws Exception\InvalidArgumentException - * @throws Exception\DomainException - * @return Registry - */ - public function setContainerClass($name) - { - if (!class_exists($name)) { - throw new Exception\DomainException( - sprintf( - '%s expects a valid registry class name; received "%s", which did not resolve', - __METHOD__, - $name - ) - ); - } - - if (!in_array('Zend\View\Helper\Placeholder\Container\AbstractContainer', class_parents($name))) { - throw new Exception\InvalidArgumentException('Invalid Container class specified'); - } - - $this->containerClass = $name; - - return $this; - } - - /** - * Retrieve the container class - * - * @return string - */ - public function getContainerClass() - { - return $this->containerClass; - } -} diff --git a/library/Zend/View/Helper/RenderChildModel.php b/library/Zend/View/Helper/RenderChildModel.php deleted file mode 100755 index d59edfe05..000000000 --- a/library/Zend/View/Helper/RenderChildModel.php +++ /dev/null @@ -1,133 +0,0 @@ -render($child); - } - - /** - * Render a model - * - * If a matching child model is found, it is rendered. If not, an empty - * string is returned. - * - * @param string $child - * @return string - */ - public function render($child) - { - $model = $this->findChild($child); - if (!$model) { - return ''; - } - - $current = $this->current; - $view = $this->getView(); - $return = $view->render($model); - $helper = $this->getViewModelHelper(); - $helper->setCurrent($current); - - return $return; - } - - /** - * Find the named child model - * - * Iterates through the current view model, looking for a child model that - * has a captureTo value matching the requested $child. If found, that child - * model is returned; otherwise, a boolean false is returned. - * - * @param string $child - * @return false|Model - */ - protected function findChild($child) - { - $this->current = $model = $this->getCurrent(); - foreach ($model->getChildren() as $childModel) { - if ($childModel->captureTo() == $child) { - return $childModel; - } - } - - return false; - } - - /** - * Get the current view model - * - * @throws Exception\RuntimeException - * @return null|Model - */ - protected function getCurrent() - { - $helper = $this->getViewModelHelper(); - if (!$helper->hasCurrent()) { - throw new Exception\RuntimeException(sprintf( - '%s: no view model currently registered in renderer; cannot query for children', - __METHOD__ - )); - } - - return $helper->getCurrent(); - } - - /** - * Retrieve the view model helper - * - * @return ViewModel - */ - protected function getViewModelHelper() - { - if ($this->viewModelHelper) { - return $this->viewModelHelper; - } - - if (method_exists($this->getView(), 'plugin')) { - $this->viewModelHelper = $this->view->plugin('view_model'); - } - - return $this->viewModelHelper; - } -} diff --git a/library/Zend/View/Helper/RenderToPlaceholder.php b/library/Zend/View/Helper/RenderToPlaceholder.php deleted file mode 100755 index 3707995b3..000000000 --- a/library/Zend/View/Helper/RenderToPlaceholder.php +++ /dev/null @@ -1,35 +0,0 @@ -view->plugin('placeholder'); - $placeholderHelper($placeholder)->captureStart(); - echo $this->view->render($script); - $placeholderHelper($placeholder)->captureEnd(); - } -} diff --git a/library/Zend/View/Helper/ServerUrl.php b/library/Zend/View/Helper/ServerUrl.php deleted file mode 100755 index ae846a9ba..000000000 --- a/library/Zend/View/Helper/ServerUrl.php +++ /dev/null @@ -1,330 +0,0 @@ -getScheme() . '://' . $this->getHost() . $path; - } - - /** - * Detect the host based on headers - * - * @return void - */ - protected function detectHost() - { - if ($this->setHostFromProxy()) { - return; - } - - if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { - // Detect if the port is set in SERVER_PORT and included in HTTP_HOST - if (isset($_SERVER['SERVER_PORT'])) { - $portStr = ':' . $_SERVER['SERVER_PORT']; - if (substr($_SERVER['HTTP_HOST'], 0-strlen($portStr), strlen($portStr)) == $portStr) { - $this->setHost(substr($_SERVER['HTTP_HOST'], 0, 0-strlen($portStr))); - return; - } - } - - $this->setHost($_SERVER['HTTP_HOST']); - - return; - } - - if (!isset($_SERVER['SERVER_NAME']) || !isset($_SERVER['SERVER_PORT'])) { - return; - } - - $name = $_SERVER['SERVER_NAME']; - $this->setHost($name); - } - - /** - * Detect the port - * - * @return null - */ - protected function detectPort() - { - if ($this->setPortFromProxy()) { - return; - } - - if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT']) { - $this->setPort($_SERVER['SERVER_PORT']); - return; - } - } - - /** - * Detect the scheme - * - * @return null - */ - protected function detectScheme() - { - if ($this->setSchemeFromProxy()) { - return; - } - - switch (true) { - case (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] === true)): - case (isset($_SERVER['HTTP_SCHEME']) && ($_SERVER['HTTP_SCHEME'] == 'https')): - case (443 === $this->getPort()): - $scheme = 'https'; - break; - default: - $scheme = 'http'; - break; - } - - $this->setScheme($scheme); - } - - /** - * Detect if a proxy is in use, and, if so, set the host based on it - * - * @return bool - */ - protected function setHostFromProxy() - { - if (!$this->useProxy) { - return false; - } - - if (!isset($_SERVER['HTTP_X_FORWARDED_HOST']) || empty($_SERVER['HTTP_X_FORWARDED_HOST'])) { - return false; - } - - $host = $_SERVER['HTTP_X_FORWARDED_HOST']; - if (strpos($host, ',') !== false) { - $hosts = explode(',', $host); - $host = trim(array_pop($hosts)); - } - if (empty($host)) { - return false; - } - $this->setHost($host); - - return true; - } - - /** - * Set port based on detected proxy headers - * - * @return bool - */ - protected function setPortFromProxy() - { - if (!$this->useProxy) { - return false; - } - - if (!isset($_SERVER['HTTP_X_FORWARDED_PORT']) || empty($_SERVER['HTTP_X_FORWARDED_PORT'])) { - return false; - } - - $port = $_SERVER['HTTP_X_FORWARDED_PORT']; - $this->setPort($port); - - return true; - } - - /** - * Set the current scheme based on detected proxy headers - * - * @return bool - */ - protected function setSchemeFromProxy() - { - if (!$this->useProxy) { - return false; - } - - if (isset($_SERVER['SSL_HTTPS'])) { - $sslHttps = strtolower($_SERVER['SSL_HTTPS']); - if (in_array($sslHttps, array('on', 1))) { - $this->setScheme('https'); - return true; - } - } - - if (!isset($_SERVER['HTTP_X_FORWARDED_PROTO']) || empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) { - return false; - } - - $scheme = trim(strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'])); - if (empty($scheme)) { - return false; - } - - $this->setScheme($scheme); - - return true; - } - - /** - * Sets host - * - * @param string $host - * @return ServerUrl - */ - public function setHost($host) - { - $port = $this->getPort(); - $scheme = $this->getScheme(); - - if (($scheme == 'http' && (null === $port || $port == 80)) - || ($scheme == 'https' && (null === $port || $port == 443)) - ) { - $this->host = $host; - return $this; - } - - $this->host = $host . ':' . $port; - - return $this; - } - - /** - * Returns host - * - * @return string - */ - public function getHost() - { - if (null === $this->host) { - $this->detectHost(); - } - - return $this->host; - } - - /** - * Set server port - * - * @param int $port - * @return ServerUrl - */ - public function setPort($port) - { - $this->port = (int) $port; - - return $this; - } - - /** - * Retrieve the server port - * - * @return int|null - */ - public function getPort() - { - if (null === $this->port) { - $this->detectPort(); - } - - return $this->port; - } - - /** - * Sets scheme (typically http or https) - * - * @param string $scheme - * @return ServerUrl - */ - public function setScheme($scheme) - { - $this->scheme = $scheme; - - return $this; - } - - /** - * Returns scheme (typically http or https) - * - * @return string - */ - public function getScheme() - { - if (null === $this->scheme) { - $this->detectScheme(); - } - - return $this->scheme; - } - - /** - * Set flag indicating whether or not to query proxy servers - * - * @param bool $useProxy - * @return ServerUrl - */ - public function setUseProxy($useProxy = false) - { - $this->useProxy = (bool) $useProxy; - - return $this; - } -} diff --git a/library/Zend/View/Helper/Service/FlashMessengerFactory.php b/library/Zend/View/Helper/Service/FlashMessengerFactory.php deleted file mode 100755 index fbaf53e8b..000000000 --- a/library/Zend/View/Helper/Service/FlashMessengerFactory.php +++ /dev/null @@ -1,47 +0,0 @@ -getServiceLocator(); - $helper = new FlashMessenger(); - $controllerPluginManager = $serviceLocator->get('ControllerPluginManager'); - $flashMessenger = $controllerPluginManager->get('flashmessenger'); - $helper->setPluginFlashMessenger($flashMessenger); - $config = $serviceLocator->get('Config'); - if (isset($config['view_helper_config']['flashmessenger'])) { - $configHelper = $config['view_helper_config']['flashmessenger']; - if (isset($configHelper['message_open_format'])) { - $helper->setMessageOpenFormat($configHelper['message_open_format']); - } - if (isset($configHelper['message_separator_string'])) { - $helper->setMessageSeparatorString($configHelper['message_separator_string']); - } - if (isset($configHelper['message_close_string'])) { - $helper->setMessageCloseString($configHelper['message_close_string']); - } - } - - return $helper; - } -} diff --git a/library/Zend/View/Helper/Service/IdentityFactory.php b/library/Zend/View/Helper/Service/IdentityFactory.php deleted file mode 100755 index a065a1d9d..000000000 --- a/library/Zend/View/Helper/Service/IdentityFactory.php +++ /dev/null @@ -1,32 +0,0 @@ -getServiceLocator(); - $helper = new Identity(); - if ($services->has('Zend\Authentication\AuthenticationService')) { - $helper->setAuthenticationService($services->get('Zend\Authentication\AuthenticationService')); - } - return $helper; - } -} diff --git a/library/Zend/View/Helper/Url.php b/library/Zend/View/Helper/Url.php deleted file mode 100755 index 9b2af7e97..000000000 --- a/library/Zend/View/Helper/Url.php +++ /dev/null @@ -1,126 +0,0 @@ -router) { - throw new Exception\RuntimeException('No RouteStackInterface instance provided'); - } - - if (3 == func_num_args() && is_bool($options)) { - $reuseMatchedParams = $options; - $options = array(); - } - - if ($name === null) { - if ($this->routeMatch === null) { - throw new Exception\RuntimeException('No RouteMatch instance provided'); - } - - $name = $this->routeMatch->getMatchedRouteName(); - - if ($name === null) { - throw new Exception\RuntimeException('RouteMatch does not contain a matched route name'); - } - } - - if (!is_array($params)) { - if (!$params instanceof Traversable) { - throw new Exception\InvalidArgumentException( - 'Params is expected to be an array or a Traversable object' - ); - } - $params = iterator_to_array($params); - } - - if ($reuseMatchedParams && $this->routeMatch !== null) { - $routeMatchParams = $this->routeMatch->getParams(); - - if (isset($routeMatchParams[ModuleRouteListener::ORIGINAL_CONTROLLER])) { - $routeMatchParams['controller'] = $routeMatchParams[ModuleRouteListener::ORIGINAL_CONTROLLER]; - unset($routeMatchParams[ModuleRouteListener::ORIGINAL_CONTROLLER]); - } - - if (isset($routeMatchParams[ModuleRouteListener::MODULE_NAMESPACE])) { - unset($routeMatchParams[ModuleRouteListener::MODULE_NAMESPACE]); - } - - $params = array_merge($routeMatchParams, $params); - } - - $options['name'] = $name; - - return $this->router->assemble($params, $options); - } - - /** - * Set the router to use for assembling. - * - * @param RouteStackInterface $router - * @return Url - */ - public function setRouter(RouteStackInterface $router) - { - $this->router = $router; - return $this; - } - - /** - * Set route match returned by the router. - * - * @param RouteMatch $routeMatch - * @return Url - */ - public function setRouteMatch(RouteMatch $routeMatch) - { - $this->routeMatch = $routeMatch; - return $this; - } -} diff --git a/library/Zend/View/Helper/ViewModel.php b/library/Zend/View/Helper/ViewModel.php deleted file mode 100755 index 49b130649..000000000 --- a/library/Zend/View/Helper/ViewModel.php +++ /dev/null @@ -1,92 +0,0 @@ -current = $model; - return $this; - } - - /** - * Get the current view model - * - * @return null|Model - */ - public function getCurrent() - { - return $this->current; - } - - /** - * Is a current view model composed? - * - * @return bool - */ - public function hasCurrent() - { - return ($this->current instanceof Model); - } - - /** - * Set the root view model - * - * @param Model $model - * @return ViewModel - */ - public function setRoot(Model $model) - { - $this->root = $model; - return $this; - } - - /** - * Get the root view model - * - * @return null|Model - */ - public function getRoot() - { - return $this->root; - } - - /** - * Is a root view model composed? - * - * @return bool - */ - public function hasRoot() - { - return ($this->root instanceof Model); - } -} diff --git a/library/Zend/View/HelperPluginManager.php b/library/Zend/View/HelperPluginManager.php deleted file mode 100755 index d2ddc6904..000000000 --- a/library/Zend/View/HelperPluginManager.php +++ /dev/null @@ -1,194 +0,0 @@ - 'Zend\View\Helper\Service\FlashMessengerFactory', - 'identity' => 'Zend\View\Helper\Service\IdentityFactory', - ); - - /** - * Default set of helpers - * - * @var array - */ - protected $invokableClasses = array( - // basepath, doctype, and url are set up as factories in the ViewHelperManagerFactory. - // basepath and url are not very useful without their factories, however the doctype - // helper works fine as an invokable. The factory for doctype simply checks for the - // config value from the merged config. - 'basepath' => 'Zend\View\Helper\BasePath', - 'cycle' => 'Zend\View\Helper\Cycle', - 'declarevars' => 'Zend\View\Helper\DeclareVars', - 'doctype' => 'Zend\View\Helper\Doctype', // overridden by a factory in ViewHelperManagerFactory - 'escapehtml' => 'Zend\View\Helper\EscapeHtml', - 'escapehtmlattr' => 'Zend\View\Helper\EscapeHtmlAttr', - 'escapejs' => 'Zend\View\Helper\EscapeJs', - 'escapecss' => 'Zend\View\Helper\EscapeCss', - 'escapeurl' => 'Zend\View\Helper\EscapeUrl', - 'gravatar' => 'Zend\View\Helper\Gravatar', - 'headlink' => 'Zend\View\Helper\HeadLink', - 'headmeta' => 'Zend\View\Helper\HeadMeta', - 'headscript' => 'Zend\View\Helper\HeadScript', - 'headstyle' => 'Zend\View\Helper\HeadStyle', - 'headtitle' => 'Zend\View\Helper\HeadTitle', - 'htmlflash' => 'Zend\View\Helper\HtmlFlash', - 'htmllist' => 'Zend\View\Helper\HtmlList', - 'htmlobject' => 'Zend\View\Helper\HtmlObject', - 'htmlpage' => 'Zend\View\Helper\HtmlPage', - 'htmlquicktime' => 'Zend\View\Helper\HtmlQuicktime', - 'inlinescript' => 'Zend\View\Helper\InlineScript', - 'json' => 'Zend\View\Helper\Json', - 'layout' => 'Zend\View\Helper\Layout', - 'paginationcontrol' => 'Zend\View\Helper\PaginationControl', - 'partialloop' => 'Zend\View\Helper\PartialLoop', - 'partial' => 'Zend\View\Helper\Partial', - 'placeholder' => 'Zend\View\Helper\Placeholder', - 'renderchildmodel' => 'Zend\View\Helper\RenderChildModel', - 'rendertoplaceholder' => 'Zend\View\Helper\RenderToPlaceholder', - 'serverurl' => 'Zend\View\Helper\ServerUrl', - 'url' => 'Zend\View\Helper\Url', - 'viewmodel' => 'Zend\View\Helper\ViewModel', - ); - - /** - * @var Renderer\RendererInterface - */ - protected $renderer; - - /** - * Constructor - * - * After invoking parent constructor, add an initializer to inject the - * attached renderer and translator, if any, to the currently requested helper. - * - * @param null|ConfigInterface $configuration - */ - public function __construct(ConfigInterface $configuration = null) - { - parent::__construct($configuration); - - $this->addInitializer(array($this, 'injectRenderer')) - ->addInitializer(array($this, 'injectTranslator')); - } - - /** - * Set renderer - * - * @param Renderer\RendererInterface $renderer - * @return HelperPluginManager - */ - public function setRenderer(Renderer\RendererInterface $renderer) - { - $this->renderer = $renderer; - - return $this; - } - - /** - * Retrieve renderer instance - * - * @return null|Renderer\RendererInterface - */ - public function getRenderer() - { - return $this->renderer; - } - - /** - * Inject a helper instance with the registered renderer - * - * @param Helper\HelperInterface $helper - * @return void - */ - public function injectRenderer($helper) - { - $renderer = $this->getRenderer(); - if (null === $renderer) { - return; - } - $helper->setView($renderer); - } - - /** - * Inject a helper instance with the registered translator - * - * @param Helper\HelperInterface $helper - * @return void - */ - public function injectTranslator($helper) - { - if (!$helper instanceof TranslatorAwareInterface) { - return; - } - - $locator = $this->getServiceLocator(); - - if (!$locator) { - return; - } - - if ($locator->has('MvcTranslator')) { - $helper->setTranslator($locator->get('MvcTranslator')); - return; - } - - if ($locator->has('Zend\I18n\Translator\TranslatorInterface')) { - $helper->setTranslator($locator->get('Zend\I18n\Translator\TranslatorInterface')); - return; - } - - if ($locator->has('Translator')) { - $helper->setTranslator($locator->get('Translator')); - return; - } - } - - /** - * Validate the plugin - * - * Checks that the helper loaded is an instance of Helper\HelperInterface. - * - * @param mixed $plugin - * @return void - * @throws Exception\InvalidHelperException if invalid - */ - public function validatePlugin($plugin) - { - if ($plugin instanceof Helper\HelperInterface) { - // we're okay - return; - } - - throw new Exception\InvalidHelperException(sprintf( - 'Plugin of type %s is invalid; must implement %s\Helper\HelperInterface', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), - __NAMESPACE__ - )); - } -} diff --git a/library/Zend/View/Model/ClearableModelInterface.php b/library/Zend/View/Model/ClearableModelInterface.php deleted file mode 100755 index 2edfe719e..000000000 --- a/library/Zend/View/Model/ClearableModelInterface.php +++ /dev/null @@ -1,23 +0,0 @@ -options['errorLevel'] = $errorLevel; - } - - /** - * @return int - */ - public function getErrorLevel() - { - if (array_key_exists('errorLevel', $this->options)) { - return $this->options['errorLevel']; - } - } - - /** - * Set result text. - * - * @param string $text - * @return \Zend\View\Model\ConsoleModel - */ - public function setResult($text) - { - $this->setVariable(self::RESULT, $text); - return $this; - } - - /** - * Get result text. - * - * @return mixed - */ - public function getResult() - { - return $this->getVariable(self::RESULT); - } -} diff --git a/library/Zend/View/Model/FeedModel.php b/library/Zend/View/Model/FeedModel.php deleted file mode 100755 index fc8351cd0..000000000 --- a/library/Zend/View/Model/FeedModel.php +++ /dev/null @@ -1,89 +0,0 @@ -feed instanceof Feed) { - return $this->feed; - } - - if (!$this->type) { - $options = $this->getOptions(); - if (isset($options['feed_type'])) { - $this->type = $options['feed_type']; - } - } - - $variables = $this->getVariables(); - $feed = FeedFactory::factory($variables); - $this->setFeed($feed); - - return $this->feed; - } - - /** - * Set the feed object - * - * @param Feed $feed - * @return FeedModel - */ - public function setFeed(Feed $feed) - { - $this->feed = $feed; - return $this; - } - - /** - * Get the feed type - * - * @return false|string - */ - public function getFeedType() - { - if ($this->type) { - return $this->type; - } - - $options = $this->getOptions(); - if (isset($options['feed_type'])) { - $this->type = $options['feed_type']; - } - return $this->type; - } -} diff --git a/library/Zend/View/Model/JsonModel.php b/library/Zend/View/Model/JsonModel.php deleted file mode 100755 index 191d3f5ec..000000000 --- a/library/Zend/View/Model/JsonModel.php +++ /dev/null @@ -1,69 +0,0 @@ -jsonpCallback = $callback; - return $this; - } - - /** - * Serialize to JSON - * - * @return string - */ - public function serialize() - { - $variables = $this->getVariables(); - if ($variables instanceof Traversable) { - $variables = ArrayUtils::iteratorToArray($variables); - } - - if (null !== $this->jsonpCallback) { - return $this->jsonpCallback.'('.Json::encode($variables).');'; - } - return Json::encode($variables); - } -} diff --git a/library/Zend/View/Model/ModelInterface.php b/library/Zend/View/Model/ModelInterface.php deleted file mode 100755 index 810540d70..000000000 --- a/library/Zend/View/Model/ModelInterface.php +++ /dev/null @@ -1,167 +0,0 @@ -setVariables($variables, true); - - if (null !== $options) { - $this->setOptions($options); - } - } - - /** - * Property overloading: set variable value - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) - { - $this->setVariable($name, $value); - } - - /** - * Property overloading: get variable value - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - if (!$this->__isset($name)) { - return null; - } - - $variables = $this->getVariables(); - return $variables[$name]; - } - - /** - * Property overloading: do we have the requested variable value? - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - $variables = $this->getVariables(); - return isset($variables[$name]); - } - - /** - * Property overloading: unset the requested variable - * - * @param string $name - * @return void - */ - public function __unset($name) - { - if (!$this->__isset($name)) { - return null; - } - - unset($this->variables[$name]); - } - - /** - * Set a single option - * - * @param string $name - * @param mixed $value - * @return ViewModel - */ - public function setOption($name, $value) - { - $this->options[(string) $name] = $value; - return $this; - } - - /** - * Get a single option - * - * @param string $name The option to get. - * @param mixed|null $default (optional) A default value if the option is not yet set. - * @return mixed - */ - public function getOption($name, $default = null) - { - $name = (string) $name; - return array_key_exists($name, $this->options) ? $this->options[$name] : $default; - } - - /** - * Set renderer options/hints en masse - * - * @param array|Traversable $options - * @throws \Zend\View\Exception\InvalidArgumentException - * @return ViewModel - */ - public function setOptions($options) - { - // Assumption is that lowest common denominator for renderer configuration - // is an array - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } - - if (!is_array($options)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an array, or Traversable argument; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - $this->options = $options; - return $this; - } - - /** - * Get renderer options/hints - * - * @return array - */ - public function getOptions() - { - return $this->options; - } - - /** - * Clear any existing renderer options/hints - * - * @return ViewModel - */ - public function clearOptions() - { - $this->options = array(); - return $this; - } - - /** - * Get a single view variable - * - * @param string $name - * @param mixed|null $default (optional) default value if the variable is not present. - * @return mixed - */ - public function getVariable($name, $default = null) - { - $name = (string) $name; - if (array_key_exists($name, $this->variables)) { - return $this->variables[$name]; - } - - return $default; - } - - /** - * Set view variable - * - * @param string $name - * @param mixed $value - * @return ViewModel - */ - public function setVariable($name, $value) - { - $this->variables[(string) $name] = $value; - return $this; - } - - /** - * Set view variables en masse - * - * Can be an array or a Traversable + ArrayAccess object. - * - * @param array|ArrayAccess|Traversable $variables - * @param bool $overwrite Whether or not to overwrite the internal container with $variables - * @throws Exception\InvalidArgumentException - * @return ViewModel - */ - public function setVariables($variables, $overwrite = false) - { - if (!is_array($variables) && !$variables instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an array, or Traversable argument; received "%s"', - __METHOD__, - (is_object($variables) ? get_class($variables) : gettype($variables)) - )); - } - - if ($overwrite) { - if (is_object($variables) && !$variables instanceof ArrayAccess) { - $variables = ArrayUtils::iteratorToArray($variables); - } - - $this->variables = $variables; - return $this; - } - - foreach ($variables as $key => $value) { - $this->setVariable($key, $value); - } - - return $this; - } - - /** - * Get view variables - * - * @return array|ArrayAccess|Traversable - */ - public function getVariables() - { - return $this->variables; - } - - /** - * Clear all variables - * - * Resets the internal variable container to an empty container. - * - * @return ViewModel - */ - public function clearVariables() - { - $this->variables = new ViewVariables(); - return $this; - } - - /** - * Set the template to be used by this model - * - * @param string $template - * @return ViewModel - */ - public function setTemplate($template) - { - $this->template = (string) $template; - return $this; - } - - /** - * Get the template to be used by this model - * - * @return string - */ - public function getTemplate() - { - return $this->template; - } - - /** - * Add a child model - * - * @param ModelInterface $child - * @param null|string $captureTo Optional; if specified, the "capture to" value to set on the child - * @param null|bool $append Optional; if specified, append to child with the same capture - * @return ViewModel - */ - public function addChild(ModelInterface $child, $captureTo = null, $append = null) - { - $this->children[] = $child; - if (null !== $captureTo) { - $child->setCaptureTo($captureTo); - } - if (null !== $append) { - $child->setAppend($append); - } - - return $this; - } - - /** - * Return all children. - * - * Return specifies an array, but may be any iterable object. - * - * @return array - */ - public function getChildren() - { - return $this->children; - } - - /** - * Does the model have any children? - * - * @return bool - */ - public function hasChildren() - { - return (0 < count($this->children)); - } - - /** - * Clears out all child models - * - * @return ViewModel - */ - public function clearChildren() - { - $this->children = array(); - return $this; - } - - /** - * Returns an array of Viewmodels with captureTo value $capture - * - * @param string $capture - * @param bool $recursive search recursive through children, default true - * @return array - */ - public function getChildrenByCaptureTo($capture, $recursive = true) - { - $children = array(); - - foreach ($this->children as $child) { - if ($recursive === true) { - $children += $child->getChildrenByCaptureTo($capture); - } - - if ($child->captureTo() === $capture) { - $children[] = $child; - } - } - - return $children; - } - - /** - * Set the name of the variable to capture this model to, if it is a child model - * - * @param string $capture - * @return ViewModel - */ - public function setCaptureTo($capture) - { - $this->captureTo = (string) $capture; - return $this; - } - - /** - * Get the name of the variable to which to capture this model - * - * @return string - */ - public function captureTo() - { - return $this->captureTo; - } - - /** - * Set flag indicating whether or not this is considered a terminal or standalone model - * - * @param bool $terminate - * @return ViewModel - */ - public function setTerminal($terminate) - { - $this->terminate = (bool) $terminate; - return $this; - } - - /** - * Is this considered a terminal or standalone model? - * - * @return bool - */ - public function terminate() - { - return $this->terminate; - } - - /** - * Set flag indicating whether or not append to child with the same capture - * - * @param bool $append - * @return ViewModel - */ - public function setAppend($append) - { - $this->append = (bool) $append; - return $this; - } - - /** - * Is this append to child with the same capture? - * - * @return bool - */ - public function isAppend() - { - return $this->append; - } - - /** - * Return count of children - * - * @return int - */ - public function count() - { - return count($this->children); - } - - /** - * Get iterator of children - * - * @return ArrayIterator - */ - public function getIterator() - { - return new ArrayIterator($this->children); - } -} diff --git a/library/Zend/View/README.md b/library/Zend/View/README.md deleted file mode 100755 index ec19b2c01..000000000 --- a/library/Zend/View/README.md +++ /dev/null @@ -1,15 +0,0 @@ -View Component from ZF2 -======================= - -This is the View component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/View/Renderer/ConsoleRenderer.php b/library/Zend/View/Renderer/ConsoleRenderer.php deleted file mode 100755 index 5f0cf10b2..000000000 --- a/library/Zend/View/Renderer/ConsoleRenderer.php +++ /dev/null @@ -1,149 +0,0 @@ -init(); - } - - public function setResolver(ResolverInterface $resolver) - { - return $this; - } - - /** - * Return the template engine object - * - * Returns the object instance, as it is its own template engine - * - * @return PhpRenderer - */ - public function getEngine() - { - return $this; - } - - /** - * Allow custom object initialization when extending ConsoleRenderer - * - * Triggered by {@link __construct() the constructor} as its final action. - * - * @return void - */ - public function init() - { - } - - /** - * Set filter chain - * - * @param FilterChain $filters - * @return ConsoleRenderer - */ - public function setFilterChain(FilterChain $filters) - { - $this->__filterChain = $filters; - return $this; - } - - /** - * Retrieve filter chain for post-filtering script content - * - * @return FilterChain - */ - public function getFilterChain() - { - if (null === $this->__filterChain) { - $this->setFilterChain(new FilterChain()); - } - return $this->__filterChain; - } - - /** - * Recursively processes all ViewModels and returns output. - * - * @param string|ModelInterface $model A ViewModel instance. - * @param null|array|\Traversable $values Values to use when rendering. If none - * provided, uses those in the composed - * variables container. - * @return string Console output. - */ - public function render($model, $values = null) - { - if (!$model instanceof ModelInterface) { - return ''; - } - - $result = ''; - $options = $model->getOptions(); - foreach ($options as $setting => $value) { - $method = 'set' . $setting; - if (method_exists($this, $method)) { - $this->$method($value); - } - unset($method, $setting, $value); - } - unset($options); - - $values = $model->getVariables(); - - if (isset($values['result'])) { - // filter and append the result - $result .= $this->getFilterChain()->filter($values['result']); - } - - if ($model->hasChildren()) { - // recursively render all children - foreach ($model->getChildren() as $child) { - $result .= $this->render($child, $values); - } - } - - return $result; - } - - /** - * @see Zend\View\Renderer\TreeRendererInterface - * @return bool - */ - public function canRenderTrees() - { - return true; - } -} diff --git a/library/Zend/View/Renderer/FeedRenderer.php b/library/Zend/View/Renderer/FeedRenderer.php deleted file mode 100755 index b91964683..000000000 --- a/library/Zend/View/Renderer/FeedRenderer.php +++ /dev/null @@ -1,138 +0,0 @@ -resolver = $resolver; - } - - /** - * Renders values as JSON - * - * @todo Determine what use case exists for accepting only $nameOrModel - * @param string|Model $nameOrModel The script/resource process, or a view model - * @param null|array|\ArrayAccess $values Values to use during rendering - * @throws Exception\InvalidArgumentException - * @return string The script output. - */ - public function render($nameOrModel, $values = null) - { - if ($nameOrModel instanceof Model) { - // Use case 1: View Model provided - // Non-FeedModel: cast to FeedModel - if (!$nameOrModel instanceof FeedModel) { - $vars = $nameOrModel->getVariables(); - $options = $nameOrModel->getOptions(); - $type = $this->getFeedType(); - if (isset($options['feed_type'])) { - $type = $options['feed_type']; - } else { - $this->setFeedType($type); - } - $nameOrModel = new FeedModel($vars, array('feed_type' => $type)); - } - } elseif (is_string($nameOrModel)) { - // Use case 2: string $nameOrModel + array|Traversable|Feed $values - $nameOrModel = new FeedModel($values, (array) $nameOrModel); - } else { - // Use case 3: failure - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a ViewModel or a string feed type as the first argument; received "%s"', - __METHOD__, - (is_object($nameOrModel) ? get_class($nameOrModel) : gettype($nameOrModel)) - )); - } - - // Get feed and type - $feed = $nameOrModel->getFeed(); - $type = $nameOrModel->getFeedType(); - if (!$type) { - $type = $this->getFeedType(); - } else { - $this->setFeedType($type); - } - - // Render feed - return $feed->export($type); - } - - /** - * Set feed type ('rss' or 'atom') - * - * @param string $feedType - * @throws Exception\InvalidArgumentException - * @return FeedRenderer - */ - public function setFeedType($feedType) - { - $feedType = strtolower($feedType); - if (!in_array($feedType, array('rss', 'atom'))) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a string of either "rss" or "atom"', - __METHOD__ - )); - } - - $this->feedType = $feedType; - return $this; - } - - /** - * Get feed type - * - * @return string - */ - public function getFeedType() - { - return $this->feedType; - } -} diff --git a/library/Zend/View/Renderer/JsonRenderer.php b/library/Zend/View/Renderer/JsonRenderer.php deleted file mode 100755 index 9666261db..000000000 --- a/library/Zend/View/Renderer/JsonRenderer.php +++ /dev/null @@ -1,243 +0,0 @@ -resolver = $resolver; - } - - /** - * Set flag indicating whether or not to merge unnamed children - * - * @param bool $mergeUnnamedChildren - * @return JsonRenderer - */ - public function setMergeUnnamedChildren($mergeUnnamedChildren) - { - $this->mergeUnnamedChildren = (bool) $mergeUnnamedChildren; - return $this; - } - - /** - * Set the JSONP callback function name - * - * @param string $callback - * @return JsonRenderer - */ - public function setJsonpCallback($callback) - { - $callback = (string) $callback; - if (!empty($callback)) { - $this->jsonpCallback = $callback; - } - return $this; - } - - /** - * Returns whether or not the jsonpCallback has been set - * - * @return bool - */ - public function hasJsonpCallback() - { - return (null !== $this->jsonpCallback); - } - - /** - * Should we merge unnamed children? - * - * @return bool - */ - public function mergeUnnamedChildren() - { - return $this->mergeUnnamedChildren; - } - - /** - * Renders values as JSON - * - * @todo Determine what use case exists for accepting both $nameOrModel and $values - * @param string|Model $nameOrModel The script/resource process, or a view model - * @param null|array|\ArrayAccess $values Values to use during rendering - * @throws Exception\DomainException - * @return string The script output. - */ - public function render($nameOrModel, $values = null) - { - // use case 1: View Models - // Serialize variables in view model - if ($nameOrModel instanceof Model) { - if ($nameOrModel instanceof JsonModel) { - $children = $this->recurseModel($nameOrModel, false); - $this->injectChildren($nameOrModel, $children); - $values = $nameOrModel->serialize(); - } else { - $values = $this->recurseModel($nameOrModel); - $values = Json::encode($values); - } - - if ($this->hasJsonpCallback()) { - $values = $this->jsonpCallback . '(' . $values . ');'; - } - return $values; - } - - // use case 2: $nameOrModel is populated, $values is not - // Serialize $nameOrModel - if (null === $values) { - if (!is_object($nameOrModel) || $nameOrModel instanceof JsonSerializable) { - $return = Json::encode($nameOrModel); - } elseif ($nameOrModel instanceof Traversable) { - $nameOrModel = ArrayUtils::iteratorToArray($nameOrModel); - $return = Json::encode($nameOrModel); - } else { - $return = Json::encode(get_object_vars($nameOrModel)); - } - - if ($this->hasJsonpCallback()) { - $return = $this->jsonpCallback . '(' . $return . ');'; - } - return $return; - } - - // use case 3: Both $nameOrModel and $values are populated - throw new Exception\DomainException(sprintf( - '%s: Do not know how to handle operation when both $nameOrModel and $values are populated', - __METHOD__ - )); - } - - /** - * Can this renderer render trees of view models? - * - * Yes. - * - * @return true - */ - public function canRenderTrees() - { - return true; - } - - /** - * Retrieve values from a model and recurse its children to build a data structure - * - * @param Model $model - * @param bool $mergeWithVariables Whether or not to merge children with - * the variables of the $model - * @return array - */ - protected function recurseModel(Model $model, $mergeWithVariables = true) - { - $values = array(); - if ($mergeWithVariables) { - $values = $model->getVariables(); - } - - if ($values instanceof Traversable) { - $values = ArrayUtils::iteratorToArray($values); - } - - if (!$model->hasChildren()) { - return $values; - } - - $mergeChildren = $this->mergeUnnamedChildren(); - foreach ($model as $child) { - $captureTo = $child->captureTo(); - if (!$captureTo && !$mergeChildren) { - // We don't want to do anything with this child - continue; - } - - $childValues = $this->recurseModel($child); - if ($captureTo) { - // Capturing to a specific key - // TODO please complete if append is true. must change old - // value to array and append to array? - $values[$captureTo] = $childValues; - } elseif ($mergeChildren) { - // Merging values with parent - $values = array_replace_recursive($values, $childValues); - } - } - return $values; - } - - /** - * Inject discovered child model values into parent model - * - * @todo detect collisions and decide whether to append and/or aggregate? - * @param Model $model - * @param array $children - */ - protected function injectChildren(Model $model, array $children) - { - foreach ($children as $child => $value) { - // TODO detect collisions and decide whether to append and/or aggregate? - $model->setVariable($child, $value); - } - } -} diff --git a/library/Zend/View/Renderer/PhpRenderer.php b/library/Zend/View/Renderer/PhpRenderer.php deleted file mode 100755 index 87baf3d98..000000000 --- a/library/Zend/View/Renderer/PhpRenderer.php +++ /dev/null @@ -1,574 +0,0 @@ -init(); - } - - /** - * Return the template engine object - * - * Returns the object instance, as it is its own template engine - * - * @return PhpRenderer - */ - public function getEngine() - { - return $this; - } - - /** - * Allow custom object initialization when extending PhpRenderer - * - * Triggered by {@link __construct() the constructor} as its final action. - * - * @return void - */ - public function init() - { - } - - /** - * Set script resolver - * - * @param Resolver $resolver - * @return PhpRenderer - * @throws Exception\InvalidArgumentException - */ - public function setResolver(Resolver $resolver) - { - $this->__templateResolver = $resolver; - return $this; - } - - /** - * Retrieve template name or template resolver - * - * @param null|string $name - * @return string|Resolver - */ - public function resolver($name = null) - { - if (null === $this->__templateResolver) { - $this->setResolver(new TemplatePathStack()); - } - - if (null !== $name) { - return $this->__templateResolver->resolve($name, $this); - } - - return $this->__templateResolver; - } - - /** - * Set variable storage - * - * Expects either an array, or an object implementing ArrayAccess. - * - * @param array|ArrayAccess $variables - * @return PhpRenderer - * @throws Exception\InvalidArgumentException - */ - public function setVars($variables) - { - if (!is_array($variables) && !$variables instanceof ArrayAccess) { - throw new Exception\InvalidArgumentException(sprintf( - 'Expected array or ArrayAccess object; received "%s"', - (is_object($variables) ? get_class($variables) : gettype($variables)) - )); - } - - // Enforce a Variables container - if (!$variables instanceof Variables) { - $variablesAsArray = array(); - foreach ($variables as $key => $value) { - $variablesAsArray[$key] = $value; - } - $variables = new Variables($variablesAsArray); - } - - $this->__vars = $variables; - return $this; - } - - /** - * Get a single variable, or all variables - * - * @param mixed $key - * @return mixed - */ - public function vars($key = null) - { - if (null === $this->__vars) { - $this->setVars(new Variables()); - } - - if (null === $key) { - return $this->__vars; - } - return $this->__vars[$key]; - } - - /** - * Get a single variable - * - * @param mixed $key - * @return mixed - */ - public function get($key) - { - if (null === $this->__vars) { - $this->setVars(new Variables()); - } - - return $this->__vars[$key]; - } - - /** - * Overloading: proxy to Variables container - * - * @param string $name - * @return mixed - */ - public function __get($name) - { - $vars = $this->vars(); - return $vars[$name]; - } - - /** - * Overloading: proxy to Variables container - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) - { - $vars = $this->vars(); - $vars[$name] = $value; - } - - /** - * Overloading: proxy to Variables container - * - * @param string $name - * @return bool - */ - public function __isset($name) - { - $vars = $this->vars(); - return isset($vars[$name]); - } - - /** - * Overloading: proxy to Variables container - * - * @param string $name - * @return void - */ - public function __unset($name) - { - $vars = $this->vars(); - if (!isset($vars[$name])) { - return; - } - unset($vars[$name]); - } - - /** - * Set helper plugin manager instance - * - * @param string|HelperPluginManager $helpers - * @return PhpRenderer - * @throws Exception\InvalidArgumentException - */ - public function setHelperPluginManager($helpers) - { - if (is_string($helpers)) { - if (!class_exists($helpers)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid helper helpers class provided (%s)', - $helpers - )); - } - $helpers = new $helpers(); - } - if (!$helpers instanceof HelperPluginManager) { - throw new Exception\InvalidArgumentException(sprintf( - 'Helper helpers must extend Zend\View\HelperPluginManager; got type "%s" instead', - (is_object($helpers) ? get_class($helpers) : gettype($helpers)) - )); - } - $helpers->setRenderer($this); - $this->__helpers = $helpers; - - return $this; - } - - /** - * Get helper plugin manager instance - * - * @return HelperPluginManager - */ - public function getHelperPluginManager() - { - if (null === $this->__helpers) { - $this->setHelperPluginManager(new HelperPluginManager()); - } - return $this->__helpers; - } - - /** - * Get plugin instance - * - * @param string $name Name of plugin to return - * @param null|array $options Options to pass to plugin constructor (if not already instantiated) - * @return AbstractHelper - */ - public function plugin($name, array $options = null) - { - return $this->getHelperPluginManager()->get($name, $options); - } - - /** - * Overloading: proxy to helpers - * - * Proxies to the attached plugin manager to retrieve, return, and potentially - * execute helpers. - * - * * If the helper does not define __invoke, it will be returned - * * If the helper does define __invoke, it will be called as a functor - * - * @param string $method - * @param array $argv - * @return mixed - */ - public function __call($method, $argv) - { - if (!isset($this->__pluginCache[$method])) { - $this->__pluginCache[$method] = $this->plugin($method); - } - if (is_callable($this->__pluginCache[$method])) { - return call_user_func_array($this->__pluginCache[$method], $argv); - } - return $this->__pluginCache[$method]; - } - - /** - * Set filter chain - * - * @param FilterChain $filters - * @return PhpRenderer - */ - public function setFilterChain(FilterChain $filters) - { - $this->__filterChain = $filters; - return $this; - } - - /** - * Retrieve filter chain for post-filtering script content - * - * @return FilterChain - */ - public function getFilterChain() - { - if (null === $this->__filterChain) { - $this->setFilterChain(new FilterChain()); - } - return $this->__filterChain; - } - - /** - * Processes a view script and returns the output. - * - * @param string|Model $nameOrModel Either the template to use, or a - * ViewModel. The ViewModel must have the - * template as an option in order to be - * valid. - * @param null|array|Traversable $values Values to use when rendering. If none - * provided, uses those in the composed - * variables container. - * @return string The script output. - * @throws Exception\DomainException if a ViewModel is passed, but does not - * contain a template option. - * @throws Exception\InvalidArgumentException if the values passed are not - * an array or ArrayAccess object - * @throws Exception\RuntimeException if the template cannot be rendered - */ - public function render($nameOrModel, $values = null) - { - if ($nameOrModel instanceof Model) { - $model = $nameOrModel; - $nameOrModel = $model->getTemplate(); - if (empty($nameOrModel)) { - throw new Exception\DomainException(sprintf( - '%s: received View Model argument, but template is empty', - __METHOD__ - )); - } - $options = $model->getOptions(); - foreach ($options as $setting => $value) { - $method = 'set' . $setting; - if (method_exists($this, $method)) { - $this->$method($value); - } - unset($method, $setting, $value); - } - unset($options); - - // Give view model awareness via ViewModel helper - $helper = $this->plugin('view_model'); - $helper->setCurrent($model); - - $values = $model->getVariables(); - unset($model); - } - - // find the script file name using the parent private method - $this->addTemplate($nameOrModel); - unset($nameOrModel); // remove $name from local scope - - $this->__varsCache[] = $this->vars(); - - if (null !== $values) { - $this->setVars($values); - } - unset($values); - - // extract all assigned vars (pre-escaped), but not 'this'. - // assigns to a double-underscored variable, to prevent naming collisions - $__vars = $this->vars()->getArrayCopy(); - if (array_key_exists('this', $__vars)) { - unset($__vars['this']); - } - extract($__vars); - unset($__vars); // remove $__vars from local scope - - while ($this->__template = array_pop($this->__templates)) { - $this->__file = $this->resolver($this->__template); - if (!$this->__file) { - throw new Exception\RuntimeException(sprintf( - '%s: Unable to render template "%s"; resolver could not resolve to a file', - __METHOD__, - $this->__template - )); - } - try { - ob_start(); - $includeReturn = include $this->__file; - $this->__content = ob_get_clean(); - } catch (\Exception $ex) { - ob_end_clean(); - throw $ex; - } - if ($includeReturn === false && empty($this->__content)) { - throw new Exception\UnexpectedValueException(sprintf( - '%s: Unable to render template "%s"; file include failed', - __METHOD__, - $this->__file - )); - } - } - - $this->setVars(array_pop($this->__varsCache)); - - return $this->getFilterChain()->filter($this->__content); // filter output - } - - /** - * Set flag indicating whether or not we should render trees of view models - * - * If set to true, the View instance will not attempt to render children - * separately, but instead pass the root view model directly to the PhpRenderer. - * It is then up to the developer to render the children from within the - * view script. - * - * @param bool $renderTrees - * @return PhpRenderer - */ - public function setCanRenderTrees($renderTrees) - { - $this->__renderTrees = (bool) $renderTrees; - return $this; - } - - /** - * Can we render trees, or are we configured to do so? - * - * @return bool - */ - public function canRenderTrees() - { - return $this->__renderTrees; - } - - /** - * Add a template to the stack - * - * @param string $template - * @return PhpRenderer - */ - public function addTemplate($template) - { - $this->__templates[] = $template; - return $this; - } - - /** - * Make sure View variables are cloned when the view is cloned. - * - * @return PhpRenderer - */ - public function __clone() - { - $this->__vars = clone $this->vars(); - } -} diff --git a/library/Zend/View/Renderer/RendererInterface.php b/library/Zend/View/Renderer/RendererInterface.php deleted file mode 100755 index d3dfa77f7..000000000 --- a/library/Zend/View/Renderer/RendererInterface.php +++ /dev/null @@ -1,47 +0,0 @@ -queue = new PriorityQueue(); - } - - /** - * Return count of attached resolvers - * - * @return int - */ - public function count() - { - return $this->queue->count(); - } - - /** - * IteratorAggregate: return internal iterator - * - * @return PriorityQueue - */ - public function getIterator() - { - return $this->queue; - } - - /** - * Attach a resolver - * - * @param Resolver $resolver - * @param int $priority - * @return AggregateResolver - */ - public function attach(Resolver $resolver, $priority = 1) - { - $this->queue->insert($resolver, $priority); - return $this; - } - - /** - * Resolve a template/pattern name to a resource the renderer can consume - * - * @param string $name - * @param null|Renderer $renderer - * @return false|string - */ - public function resolve($name, Renderer $renderer = null) - { - $this->lastLookupFailure = false; - $this->lastSuccessfulResolver = null; - - if (0 === count($this->queue)) { - $this->lastLookupFailure = static::FAILURE_NO_RESOLVERS; - return false; - } - - foreach ($this->queue as $resolver) { - $resource = $resolver->resolve($name, $renderer); - if (!$resource) { - // No resource found; try next resolver - continue; - } - - // Resource found; return it - $this->lastSuccessfulResolver = $resolver; - return $resource; - } - - $this->lastLookupFailure = static::FAILURE_NOT_FOUND; - return false; - } - - /** - * Return the last successful resolver, if any - * - * @return Resolver - */ - public function getLastSuccessfulResolver() - { - return $this->lastSuccessfulResolver; - } - - /** - * Get last lookup failure - * - * @return false|string - */ - public function getLastLookupFailure() - { - return $this->lastLookupFailure; - } -} diff --git a/library/Zend/View/Resolver/ResolverInterface.php b/library/Zend/View/Resolver/ResolverInterface.php deleted file mode 100755 index 8ffe130c6..000000000 --- a/library/Zend/View/Resolver/ResolverInterface.php +++ /dev/null @@ -1,24 +0,0 @@ -setMap($map); - } - - /** - * IteratorAggregate: return internal iterator - * - * @return Traversable - */ - public function getIterator() - { - return new ArrayIterator($this->map); - } - - /** - * Set (overwrite) template map - * - * Maps should be arrays or Traversable objects with name => path pairs - * - * @param array|Traversable $map - * @throws Exception\InvalidArgumentException - * @return TemplateMapResolver - */ - public function setMap($map) - { - if (!is_array($map) && !$map instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an array or Traversable, received "%s"', - __METHOD__, - (is_object($map) ? get_class($map) : gettype($map)) - )); - } - - if ($map instanceof Traversable) { - $map = ArrayUtils::iteratorToArray($map); - } - - $this->map = $map; - return $this; - } - - /** - * Add an entry to the map - * - * @param string|array|Traversable $nameOrMap - * @param null|string $path - * @throws Exception\InvalidArgumentException - * @return TemplateMapResolver - */ - public function add($nameOrMap, $path = null) - { - if (is_array($nameOrMap) || $nameOrMap instanceof Traversable) { - $this->merge($nameOrMap); - return $this; - } - - if (!is_string($nameOrMap)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects a string, array, or Traversable for the first argument; received "%s"', - __METHOD__, - (is_object($nameOrMap) ? get_class($nameOrMap) : gettype($nameOrMap)) - )); - } - - if (empty($path)) { - if (isset($this->map[$nameOrMap])) { - unset($this->map[$nameOrMap]); - } - return $this; - } - - $this->map[$nameOrMap] = $path; - return $this; - } - - /** - * Merge internal map with provided map - * - * @param array|Traversable $map - * @throws Exception\InvalidArgumentException - * @return TemplateMapResolver - */ - public function merge($map) - { - if (!is_array($map) && !$map instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s: expects an array or Traversable, received "%s"', - __METHOD__, - (is_object($map) ? get_class($map) : gettype($map)) - )); - } - - if ($map instanceof Traversable) { - $map = ArrayUtils::iteratorToArray($map); - } - - $this->map = array_replace_recursive($this->map, $map); - return $this; - } - - /** - * Does the resolver contain an entry for the given name? - * - * @param string $name - * @return bool - */ - public function has($name) - { - return array_key_exists($name, $this->map); - } - - /** - * Retrieve a template path by name - * - * @param string $name - * @return false|string - * @throws Exception\DomainException if no entry exists - */ - public function get($name) - { - if (!$this->has($name)) { - return false; - } - return $this->map[$name]; - } - - /** - * Retrieve the template map - * - * @return array - */ - public function getMap() - { - return $this->map; - } - - /** - * Resolve a template/pattern name to a resource the renderer can consume - * - * @param string $name - * @param null|Renderer $renderer - * @return string - */ - public function resolve($name, Renderer $renderer = null) - { - return $this->get($name); - } -} diff --git a/library/Zend/View/Resolver/TemplatePathStack.php b/library/Zend/View/Resolver/TemplatePathStack.php deleted file mode 100755 index 359be18f3..000000000 --- a/library/Zend/View/Resolver/TemplatePathStack.php +++ /dev/null @@ -1,338 +0,0 @@ -useViewStream = (bool) ini_get('short_open_tag'); - if ($this->useViewStream) { - if (!in_array('zend.view', stream_get_wrappers())) { - stream_wrapper_register('zend.view', 'Zend\View\Stream'); - } - } - - $this->paths = new SplStack; - if (null !== $options) { - $this->setOptions($options); - } - } - - /** - * Configure object - * - * @param array|Traversable $options - * @return void - * @throws Exception\InvalidArgumentException - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - 'Expected array or Traversable object; received "%s"', - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $key => $value) { - switch (strtolower($key)) { - case 'lfi_protection': - $this->setLfiProtection($value); - break; - case 'script_paths': - $this->addPaths($value); - break; - case 'use_stream_wrapper': - $this->setUseStreamWrapper($value); - break; - case 'default_suffix': - $this->setDefaultSuffix($value); - break; - default: - break; - } - } - } - - /** - * Set default file suffix - * - * @param string $defaultSuffix - * @return TemplatePathStack - */ - public function setDefaultSuffix($defaultSuffix) - { - $this->defaultSuffix = (string) $defaultSuffix; - $this->defaultSuffix = ltrim($this->defaultSuffix, '.'); - return $this; - } - - /** - * Get default file suffix - * - * @return string - */ - public function getDefaultSuffix() - { - return $this->defaultSuffix; - } - - /** - * Add many paths to the stack at once - * - * @param array $paths - * @return TemplatePathStack - */ - public function addPaths(array $paths) - { - foreach ($paths as $path) { - $this->addPath($path); - } - return $this; - } - - /** - * Rest the path stack to the paths provided - * - * @param SplStack|array $paths - * @return TemplatePathStack - * @throws Exception\InvalidArgumentException - */ - public function setPaths($paths) - { - if ($paths instanceof SplStack) { - $this->paths = $paths; - } elseif (is_array($paths)) { - $this->clearPaths(); - $this->addPaths($paths); - } else { - throw new Exception\InvalidArgumentException( - "Invalid argument provided for \$paths, expecting either an array or SplStack object" - ); - } - - return $this; - } - - /** - * Normalize a path for insertion in the stack - * - * @param string $path - * @return string - */ - public static function normalizePath($path) - { - $path = rtrim($path, '/'); - $path = rtrim($path, '\\'); - $path .= DIRECTORY_SEPARATOR; - return $path; - } - - /** - * Add a single path to the stack - * - * @param string $path - * @return TemplatePathStack - * @throws Exception\InvalidArgumentException - */ - public function addPath($path) - { - if (!is_string($path)) { - throw new Exception\InvalidArgumentException(sprintf( - 'Invalid path provided; must be a string, received %s', - gettype($path) - )); - } - $this->paths[] = static::normalizePath($path); - return $this; - } - - /** - * Clear all paths - * - * @return void - */ - public function clearPaths() - { - $this->paths = new SplStack; - } - - /** - * Returns stack of paths - * - * @return SplStack - */ - public function getPaths() - { - return $this->paths; - } - - /** - * Set LFI protection flag - * - * @param bool $flag - * @return TemplatePathStack - */ - public function setLfiProtection($flag) - { - $this->lfiProtectionOn = (bool) $flag; - return $this; - } - - /** - * Return status of LFI protection flag - * - * @return bool - */ - public function isLfiProtectionOn() - { - return $this->lfiProtectionOn; - } - - /** - * Set flag indicating if stream wrapper should be used if short_open_tag is off - * - * @param bool $flag - * @return TemplatePathStack - */ - public function setUseStreamWrapper($flag) - { - $this->useStreamWrapper = (bool) $flag; - return $this; - } - - /** - * Should the stream wrapper be used if short_open_tag is off? - * - * Returns true if the use_stream_wrapper flag is set, and if short_open_tag - * is disabled. - * - * @return bool - */ - public function useStreamWrapper() - { - return ($this->useViewStream && $this->useStreamWrapper); - } - - /** - * Retrieve the filesystem path to a view script - * - * @param string $name - * @param null|Renderer $renderer - * @return string - * @throws Exception\DomainException - */ - public function resolve($name, Renderer $renderer = null) - { - $this->lastLookupFailure = false; - - if ($this->isLfiProtectionOn() && preg_match('#\.\.[\\\/]#', $name)) { - throw new Exception\DomainException( - 'Requested scripts may not include parent directory traversal ("../", "..\\" notation)' - ); - } - - if (!count($this->paths)) { - $this->lastLookupFailure = static::FAILURE_NO_PATHS; - return false; - } - - // Ensure we have the expected file extension - $defaultSuffix = $this->getDefaultSuffix(); - if (pathinfo($name, PATHINFO_EXTENSION) == '') { - $name .= '.' . $defaultSuffix; - } - - foreach ($this->paths as $path) { - $file = new SplFileInfo($path . $name); - if ($file->isReadable()) { - // Found! Return it. - if (($filePath = $file->getRealPath()) === false && substr($path, 0, 7) === 'phar://') { - // Do not try to expand phar paths (realpath + phars == fail) - $filePath = $path . $name; - if (!file_exists($filePath)) { - break; - } - } - if ($this->useStreamWrapper()) { - // If using a stream wrapper, prepend the spec to the path - $filePath = 'zend.view://' . $filePath; - } - return $filePath; - } - } - - $this->lastLookupFailure = static::FAILURE_NOT_FOUND; - return false; - } - - /** - * Get the last lookup failure message, if any - * - * @return false|string - */ - public function getLastLookupFailure() - { - return $this->lastLookupFailure; - } -} diff --git a/library/Zend/View/Strategy/FeedStrategy.php b/library/Zend/View/Strategy/FeedStrategy.php deleted file mode 100755 index 40140da5a..000000000 --- a/library/Zend/View/Strategy/FeedStrategy.php +++ /dev/null @@ -1,111 +0,0 @@ -renderer = $renderer; - } - - /** - * {@inheritDoc} - */ - public function attach(EventManagerInterface $events, $priority = 1) - { - $this->listeners[] = $events->attach(ViewEvent::EVENT_RENDERER, array($this, 'selectRenderer'), $priority); - $this->listeners[] = $events->attach(ViewEvent::EVENT_RESPONSE, array($this, 'injectResponse'), $priority); - } - - /** - * Detect if we should use the FeedRenderer based on model type and/or - * Accept header - * - * @param ViewEvent $e - * @return null|FeedRenderer - */ - public function selectRenderer(ViewEvent $e) - { - $model = $e->getModel(); - - if (!$model instanceof Model\FeedModel) { - // no FeedModel present; do nothing - return; - } - - // FeedModel found - return $this->renderer; - } - - /** - * Inject the response with the feed payload and appropriate Content-Type header - * - * @param ViewEvent $e - * @return void - */ - public function injectResponse(ViewEvent $e) - { - $renderer = $e->getRenderer(); - if ($renderer !== $this->renderer) { - // Discovered renderer is not ours; do nothing - return; - } - - $result = $e->getResult(); - if (!is_string($result) && !$result instanceof Feed) { - // We don't have a string, and thus, no feed - return; - } - - // If the result is a feed, export it - if ($result instanceof Feed) { - $result = $result->export($renderer->getFeedType()); - } - - // Get the content-type header based on feed type - $feedType = $renderer->getFeedType(); - $feedType = ('rss' == $feedType) - ? 'application/rss+xml' - : 'application/atom+xml'; - - $model = $e->getModel(); - $charset = ''; - - if ($model instanceof Model\FeedModel) { - $feed = $model->getFeed(); - - $charset = '; charset=' . $feed->getEncoding() . ';'; - } - - // Populate response - $response = $e->getResponse(); - $response->setContent($result); - $headers = $response->getHeaders(); - $headers->addHeaderLine('content-type', $feedType . $charset); - } -} diff --git a/library/Zend/View/Strategy/JsonStrategy.php b/library/Zend/View/Strategy/JsonStrategy.php deleted file mode 100755 index 7cf4b91f0..000000000 --- a/library/Zend/View/Strategy/JsonStrategy.php +++ /dev/null @@ -1,141 +0,0 @@ -renderer = $renderer; - } - - /** - * {@inheritDoc} - */ - public function attach(EventManagerInterface $events, $priority = 1) - { - $this->listeners[] = $events->attach(ViewEvent::EVENT_RENDERER, array($this, 'selectRenderer'), $priority); - $this->listeners[] = $events->attach(ViewEvent::EVENT_RESPONSE, array($this, 'injectResponse'), $priority); - } - - /** - * Set the content-type character set - * - * @param string $charset - * @return JsonStrategy - */ - public function setCharset($charset) - { - $this->charset = (string) $charset; - return $this; - } - - /** - * Retrieve the current character set - * - * @return string - */ - public function getCharset() - { - return $this->charset; - } - - /** - * Detect if we should use the JsonRenderer based on model type and/or - * Accept header - * - * @param ViewEvent $e - * @return null|JsonRenderer - */ - public function selectRenderer(ViewEvent $e) - { - $model = $e->getModel(); - - if (!$model instanceof Model\JsonModel) { - // no JsonModel; do nothing - return; - } - - // JsonModel found - return $this->renderer; - } - - /** - * Inject the response with the JSON payload and appropriate Content-Type header - * - * @param ViewEvent $e - * @return void - */ - public function injectResponse(ViewEvent $e) - { - $renderer = $e->getRenderer(); - if ($renderer !== $this->renderer) { - // Discovered renderer is not ours; do nothing - return; - } - - $result = $e->getResult(); - if (!is_string($result)) { - // We don't have a string, and thus, no JSON - return; - } - - // Populate response - $response = $e->getResponse(); - $response->setContent($result); - $headers = $response->getHeaders(); - - if ($this->renderer->hasJsonpCallback()) { - $contentType = 'application/javascript'; - } else { - $contentType = 'application/json'; - } - - $contentType .= '; charset=' . $this->charset; - $headers->addHeaderLine('content-type', $contentType); - - if (in_array(strtoupper($this->charset), $this->multibyteCharsets)) { - $headers->addHeaderLine('content-transfer-encoding', 'BINARY'); - } - } -} diff --git a/library/Zend/View/Strategy/PhpRendererStrategy.php b/library/Zend/View/Strategy/PhpRendererStrategy.php deleted file mode 100755 index e8e04ceb3..000000000 --- a/library/Zend/View/Strategy/PhpRendererStrategy.php +++ /dev/null @@ -1,127 +0,0 @@ -renderer = $renderer; - } - - /** - * Retrieve the composed renderer - * - * @return PhpRenderer - */ - public function getRenderer() - { - return $this->renderer; - } - - /** - * Set list of possible content placeholders - * - * @param array $contentPlaceholders - * @return PhpRendererStrategy - */ - public function setContentPlaceholders(array $contentPlaceholders) - { - $this->contentPlaceholders = $contentPlaceholders; - return $this; - } - - /** - * Get list of possible content placeholders - * - * @return array - */ - public function getContentPlaceholders() - { - return $this->contentPlaceholders; - } - - /** - * {@inheritDoc} - */ - public function attach(EventManagerInterface $events, $priority = 1) - { - $this->listeners[] = $events->attach(ViewEvent::EVENT_RENDERER, array($this, 'selectRenderer'), $priority); - $this->listeners[] = $events->attach(ViewEvent::EVENT_RESPONSE, array($this, 'injectResponse'), $priority); - } - - /** - * Select the PhpRenderer; typically, this will be registered last or at - * low priority. - * - * @param ViewEvent $e - * @return PhpRenderer - */ - public function selectRenderer(ViewEvent $e) - { - return $this->renderer; - } - - /** - * Populate the response object from the View - * - * Populates the content of the response object from the view rendering - * results. - * - * @param ViewEvent $e - * @return void - */ - public function injectResponse(ViewEvent $e) - { - $renderer = $e->getRenderer(); - if ($renderer !== $this->renderer) { - return; - } - - $result = $e->getResult(); - $response = $e->getResponse(); - - // Set content - // If content is empty, check common placeholders to determine if they are - // populated, and set the content from them. - if (empty($result)) { - $placeholders = $renderer->plugin('placeholder'); - foreach ($this->contentPlaceholders as $placeholder) { - if ($placeholders->containerExists($placeholder)) { - $result = (string) $placeholders->getContainer($placeholder); - break; - } - } - } - $response->setContent($result); - } -} diff --git a/library/Zend/View/Stream.php b/library/Zend/View/Stream.php deleted file mode 100755 index 42bb7a962..000000000 --- a/library/Zend/View/Stream.php +++ /dev/null @@ -1,183 +0,0 @@ -data = file_get_contents($path); - - /** - * If reading the file failed, update our local stat store - * to reflect the real stat of the file, then return on failure - */ - if ($this->data === false) { - $this->stat = stat($path); - return false; - } - - /** - * Convert to long-form and to - * - */ - $this->data = preg_replace('/\<\?\=/', "data); - $this->data = preg_replace('/<\?(?!xml|php)/s', 'data); - - /** - * file_get_contents() won't update PHP's stat cache, so we grab a stat - * of the file to prevent additional reads should the script be - * requested again, which will make include() happy. - */ - $this->stat = stat($path); - - return true; - } - - /** - * Included so that __FILE__ returns the appropriate info - * - * @return array - */ - public function url_stat() - { - return $this->stat; - } - - /** - * Reads from the stream. - * - * @param int $count - * @return string - */ - public function stream_read($count) - { - $ret = substr($this->data, $this->pos, $count); - $this->pos += strlen($ret); - return $ret; - } - - /** - * Tells the current position in the stream. - * - * @return int - */ - public function stream_tell() - { - return $this->pos; - } - - /** - * Tells if we are at the end of the stream. - * - * @return bool - */ - public function stream_eof() - { - return $this->pos >= strlen($this->data); - } - - /** - * Stream statistics. - * - * @return array - */ - public function stream_stat() - { - return $this->stat; - } - - /** - * Seek to a specific point in the stream. - * - * @param $offset - * @param $whence - * @return bool - */ - public function stream_seek($offset, $whence) - { - switch ($whence) { - case SEEK_SET: - if ($offset < strlen($this->data) && $offset >= 0) { - $this->pos = $offset; - return true; - } else { - return false; - } - break; - - case SEEK_CUR: - if ($offset >= 0) { - $this->pos += $offset; - return true; - } else { - return false; - } - break; - - case SEEK_END: - if (strlen($this->data) + $offset >= 0) { - $this->pos = strlen($this->data) + $offset; - return true; - } else { - return false; - } - break; - - default: - return false; - } - } -} diff --git a/library/Zend/View/Variables.php b/library/Zend/View/Variables.php deleted file mode 100755 index 17b14724c..000000000 --- a/library/Zend/View/Variables.php +++ /dev/null @@ -1,162 +0,0 @@ -setOptions($options); - } - - /** - * Configure object - * - * @param array $options - * @return Variables - */ - public function setOptions(array $options) - { - foreach ($options as $key => $value) { - switch (strtolower($key)) { - case 'strict_vars': - $this->setStrictVars($value); - break; - default: - // Unknown options are considered variables - $this[$key] = $value; - break; - } - } - return $this; - } - - /** - * Set status of "strict vars" flag - * - * @param bool $flag - * @return Variables - */ - public function setStrictVars($flag) - { - $this->strictVars = (bool) $flag; - return $this; - } - - /** - * Are we operating with strict variables? - * - * @return bool - */ - public function isStrict() - { - return $this->strictVars; - } - - /** - * Assign many values at once - * - * @param array|object $spec - * @return Variables - * @throws Exception\InvalidArgumentException - */ - public function assign($spec) - { - if (is_object($spec)) { - if (method_exists($spec, 'toArray')) { - $spec = $spec->toArray(); - } else { - $spec = (array) $spec; - } - } - if (!is_array($spec)) { - throw new Exception\InvalidArgumentException(sprintf( - 'assign() expects either an array or an object as an argument; received "%s"', - gettype($spec) - )); - } - foreach ($spec as $key => $value) { - $this[$key] = $value; - } - - return $this; - } - - /** - * Get the variable value - * - * If the value has not been defined, a null value will be returned; if - * strict vars on in place, a notice will also be raised. - * - * Otherwise, returns _escaped_ version of the value. - * - * @param mixed $key - * @return mixed - */ - public function offsetGet($key) - { - if (!$this->offsetExists($key)) { - if ($this->isStrict()) { - trigger_error(sprintf( - 'View variable "%s" does not exist', $key - ), E_USER_NOTICE); - } - return null; - } - - $return = parent::offsetGet($key); - - // If we have a closure/functor, invoke it, and return its return value - if (is_object($return) && is_callable($return)) { - $return = call_user_func($return); - } - - return $return; - } - - /** - * Clear all variables - * - * @return void - */ - public function clear() - { - $this->exchangeArray(array()); - } -} diff --git a/library/Zend/View/View.php b/library/Zend/View/View.php deleted file mode 100755 index aebae58a0..000000000 --- a/library/Zend/View/View.php +++ /dev/null @@ -1,264 +0,0 @@ -request = $request; - return $this; - } - - /** - * Set MVC response object - * - * @param Response $response - * @return View - */ - public function setResponse(Response $response) - { - $this->response = $response; - return $this; - } - - /** - * Get MVC request object - * - * @return null|Request - */ - public function getRequest() - { - return $this->request; - } - - /** - * Get MVC response object - * - * @return null|Response - */ - public function getResponse() - { - return $this->response; - } - - /** - * Set the event manager instance - * - * @param EventManagerInterface $events - * @return View - */ - public function setEventManager(EventManagerInterface $events) - { - $events->setIdentifiers(array( - __CLASS__, - get_class($this), - )); - $this->events = $events; - return $this; - } - - /** - * Retrieve the event manager instance - * - * Lazy-loads a default instance if none available - * - * @return EventManagerInterface - */ - public function getEventManager() - { - if (!$this->events instanceof EventManagerInterface) { - $this->setEventManager(new EventManager()); - } - return $this->events; - } - - /** - * Add a rendering strategy - * - * Expects a callable. Strategies should accept a ViewEvent object, and should - * return a Renderer instance if the strategy is selected. - * - * Internally, the callable provided will be subscribed to the "renderer" - * event, at the priority specified. - * - * @param callable $callable - * @param int $priority - * @return View - */ - public function addRenderingStrategy($callable, $priority = 1) - { - $this->getEventManager()->attach(ViewEvent::EVENT_RENDERER, $callable, $priority); - return $this; - } - - /** - * Add a response strategy - * - * Expects a callable. Strategies should accept a ViewEvent object. The return - * value will be ignored. - * - * Typical usages for a response strategy are to populate the Response object. - * - * Internally, the callable provided will be subscribed to the "response" - * event, at the priority specified. - * - * @param callable $callable - * @param int $priority - * @return View - */ - public function addResponseStrategy($callable, $priority = 1) - { - $this->getEventManager()->attach(ViewEvent::EVENT_RESPONSE, $callable, $priority); - return $this; - } - - /** - * Render the provided model. - * - * Internally, the following workflow is used: - * - * - Trigger the "renderer" event to select a renderer. - * - Call the selected renderer with the provided Model - * - Trigger the "response" event - * - * @triggers renderer(ViewEvent) - * @triggers response(ViewEvent) - * @param Model $model - * @throws Exception\RuntimeException - * @return void - */ - public function render(Model $model) - { - $event = $this->getEvent(); - $event->setModel($model); - $events = $this->getEventManager(); - $results = $events->trigger(ViewEvent::EVENT_RENDERER, $event, function ($result) { - return ($result instanceof Renderer); - }); - $renderer = $results->last(); - if (!$renderer instanceof Renderer) { - throw new Exception\RuntimeException(sprintf( - '%s: no renderer selected!', - __METHOD__ - )); - } - - $event->setRenderer($renderer); - $events->trigger(ViewEvent::EVENT_RENDERER_POST, $event); - - // If EVENT_RENDERER or EVENT_RENDERER_POST changed the model, make sure - // we use this new model instead of the current $model - $model = $event->getModel(); - - // If we have children, render them first, but only if: - // a) the renderer does not implement TreeRendererInterface, or - // b) it does, but canRenderTrees() returns false - if ($model->hasChildren() - && (!$renderer instanceof TreeRendererInterface - || !$renderer->canRenderTrees()) - ) { - $this->renderChildren($model); - } - - // Reset the model, in case it has changed, and set the renderer - $event->setModel($model); - $event->setRenderer($renderer); - - $rendered = $renderer->render($model); - - // If this is a child model, return the rendered content; do not - // invoke the response strategy. - $options = $model->getOptions(); - if (array_key_exists('has_parent', $options) && $options['has_parent']) { - return $rendered; - } - - $event->setResult($rendered); - - $events->trigger(ViewEvent::EVENT_RESPONSE, $event); - } - - /** - * Loop through children, rendering each - * - * @param Model $model - * @throws Exception\DomainException - * @return void - */ - protected function renderChildren(Model $model) - { - foreach ($model as $child) { - if ($child->terminate()) { - throw new Exception\DomainException('Inconsistent state; child view model is marked as terminal'); - } - $child->setOption('has_parent', true); - $result = $this->render($child); - $child->setOption('has_parent', null); - $capture = $child->captureTo(); - if (!empty($capture)) { - if ($child->isAppend()) { - $oldResult=$model->{$capture}; - $model->setVariable($capture, $oldResult . $result); - } else { - $model->setVariable($capture, $result); - } - } - } - } - - /** - * Create and return ViewEvent used by render() - * - * @return ViewEvent - */ - protected function getEvent() - { - $event = new ViewEvent(); - $event->setTarget($this); - if (null !== ($request = $this->getRequest())) { - $event->setRequest($request); - } - if (null !== ($response = $this->getResponse())) { - $event->setResponse($response); - } - return $event; - } -} diff --git a/library/Zend/View/ViewEvent.php b/library/Zend/View/ViewEvent.php deleted file mode 100755 index 34baa2136..000000000 --- a/library/Zend/View/ViewEvent.php +++ /dev/null @@ -1,258 +0,0 @@ -model = $model; - return $this; - } - - /** - * Set the MVC request object - * - * @param Request $request - * @return ViewEvent - */ - public function setRequest(Request $request) - { - $this->request = $request; - return $this; - } - - /** - * Set the MVC response object - * - * @param Response $response - * @return ViewEvent - */ - public function setResponse(Response $response) - { - $this->response = $response; - return $this; - } - - /** - * Set result of rendering - * - * @param mixed $result - * @return ViewEvent - */ - public function setResult($result) - { - $this->result = $result; - return $this; - } - - /** - * Retrieve the view model - * - * @return null|Model - */ - public function getModel() - { - return $this->model; - } - - /** - * Set value for renderer - * - * @param Renderer $renderer - * @return ViewEvent - */ - public function setRenderer(Renderer $renderer) - { - $this->renderer = $renderer; - return $this; - } - - /** - * Get value for renderer - * - * @return null|Renderer - */ - public function getRenderer() - { - return $this->renderer; - } - - /** - * Retrieve the MVC request object - * - * @return null|Request - */ - public function getRequest() - { - return $this->request; - } - - /** - * Retrieve the MVC response object - * - * @return null|Response - */ - public function getResponse() - { - return $this->response; - } - - /** - * Retrieve the result of rendering - * - * @return mixed - */ - public function getResult() - { - return $this->result; - } - - /** - * Get event parameter - * - * @param string $name - * @param mixed $default - * @return mixed - */ - public function getParam($name, $default = null) - { - switch ($name) { - case 'model': - return $this->getModel(); - case 'renderer': - return $this->getRenderer(); - case 'request': - return $this->getRequest(); - case 'response': - return $this->getResponse(); - case 'result': - return $this->getResult(); - default: - return parent::getParam($name, $default); - } - } - - /** - * Get all event parameters - * - * @return array|\ArrayAccess - */ - public function getParams() - { - $params = parent::getParams(); - $params['model'] = $this->getModel(); - $params['renderer'] = $this->getRenderer(); - $params['request'] = $this->getRequest(); - $params['response'] = $this->getResponse(); - $params['result'] = $this->getResult(); - return $params; - } - - /** - * Set event parameters - * - * @param array|object|ArrayAccess $params - * @return ViewEvent - */ - public function setParams($params) - { - parent::setParams($params); - if (!is_array($params) && !$params instanceof ArrayAccess) { - return $this; - } - - foreach (array('model', 'renderer', 'request', 'response', 'result') as $param) { - if (isset($params[$param])) { - $method = 'set' . $param; - $this->$method($params[$param]); - } - } - return $this; - } - - /** - * Set an individual event parameter - * - * @param string $name - * @param mixed $value - * @return ViewEvent - */ - public function setParam($name, $value) - { - switch ($name) { - case 'model': - $this->setModel($value); - break; - case 'renderer': - $this->setRenderer($value); - break; - case 'request': - $this->setRequest($value); - break; - case 'response': - $this->setResponse($value); - break; - case 'result': - $this->setResult($value); - break; - default: - parent::setParam($name, $value); - break; - } - return $this; - } -} diff --git a/library/Zend/View/composer.json b/library/Zend/View/composer.json deleted file mode 100755 index 44bb5c275..000000000 --- a/library/Zend/View/composer.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "zendframework/zend-view", - "description": "provides a system of helpers, output filters, and variable escaping", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "view" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\View\\": "" - } - }, - "target-dir": "Zend/View", - "require": { - "php": ">=5.3.23", - "zendframework/zend-eventmanager": "self.version", - "zendframework/zend-loader": "self.version", - "zendframework/zend-stdlib": "self.version" - }, - "require-dev": { - "zendframework/zend-authentication": "self.version", - "zendframework/zend-escaper": "self.version", - "zendframework/zend-feed": "self.version", - "zendframework/zend-filter": "self.version", - "zendframework/zend-http": "self.version", - "zendframework/zend-i18n": "self.version", - "zendframework/zend-json": "self.version", - "zendframework/zend-mvc": "self.version", - "zendframework/zend-navigation": "self.version", - "zendframework/zend-paginator": "self.version", - "zendframework/zend-permissions-acl": "self.version", - "zendframework/zend-servicemanager": "self.version", - "zendframework/zend-uri": "self.version" - }, - "suggest": { - "zendframework/zend-authentication": "Zend\\Authentication component", - "zendframework/zend-escaper": "Zend\\Escaper component", - "zendframework/zend-feed": "Zend\\Feed component", - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-http": "Zend\\Http component", - "zendframework/zend-i18n": "Zend\\I18n component", - "zendframework/zend-json": "Zend\\Json component", - "zendframework/zend-mvc": "Zend\\Mvc component", - "zendframework/zend-navigation": "Zend\\Navigation component", - "zendframework/zend-paginator": "Zend\\Paginator component", - "zendframework/zend-permissions-acl": "Zend\\Permissions\\Acl component", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component", - "zendframework/zend-uri": "Zend\\Uri component" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/Zend/XmlRpc/AbstractValue.php b/library/Zend/XmlRpc/AbstractValue.php deleted file mode 100755 index 221238a09..000000000 --- a/library/Zend/XmlRpc/AbstractValue.php +++ /dev/null @@ -1,462 +0,0 @@ -type; - } - - /** - * Get XML generator instance - * - * @return \Zend\XmlRpc\Generator\GeneratorInterface - */ - public static function getGenerator() - { - if (!static::$generator) { - if (extension_loaded('xmlwriter')) { - static::$generator = new Generator\XmlWriter(); - } else { - static::$generator = new Generator\DomDocument(); - } - } - - return static::$generator; - } - - /** - * Sets XML generator instance - * - * @param null|Generator\GeneratorInterface $generator - * @return void - */ - public static function setGenerator(Generator\GeneratorInterface $generator = null) - { - static::$generator = $generator; - } - - /** - * Changes the encoding of the generator - * - * @param string $encoding - * @return void - */ - public static function setEncoding($encoding) - { - $generator = static::getGenerator(); - $newGenerator = new $generator($encoding); - static::setGenerator($newGenerator); - } - - /** - * Return the value of this object, convert the XML-RPC native value into a PHP variable - * - * @return mixed - */ - abstract public function getValue(); - - - /** - * Return the XML code that represent a native MXL-RPC value - * - * @return string - */ - public function saveXml() - { - if (!$this->xml) { - $this->generateXml(); - $this->xml = (string) $this->getGenerator(); - } - return $this->xml; - } - - /** - * Generate XML code that represent a native XML/RPC value - * - * @return void - */ - public function generateXml() - { - $this->_generateXml(); - } - - /** - * Creates a Value* object, representing a native XML-RPC value - * A XmlRpcValue object can be created in 3 ways: - * 1. Autodetecting the native type out of a PHP variable - * (if $type is not set or equal to Value::AUTO_DETECT_TYPE) - * 2. By specifying the native type ($type is one of the Value::XMLRPC_TYPE_* constants) - * 3. From a XML string ($type is set to Value::XML_STRING) - * - * By default the value type is autodetected according to it's PHP type - * - * @param mixed $value - * @param Zend\XmlRpc\Value::constant $type - * @throws Exception\ValueException - * @return AbstractValue - */ - public static function getXmlRpcValue($value, $type = self::AUTO_DETECT_TYPE) - { - switch ($type) { - case self::AUTO_DETECT_TYPE: - // Auto detect the XML-RPC native type from the PHP type of $value - return static::_phpVarToNativeXmlRpc($value); - - case self::XML_STRING: - // Parse the XML string given in $value and get the XML-RPC value in it - return static::_xmlStringToNativeXmlRpc($value); - - case self::XMLRPC_TYPE_I4: - // fall through to the next case - case self::XMLRPC_TYPE_INTEGER: - return new Value\Integer($value); - - case self::XMLRPC_TYPE_I8: - // fall through to the next case - case self::XMLRPC_TYPE_APACHEI8: - return new Value\BigInteger($value); - - case self::XMLRPC_TYPE_DOUBLE: - return new Value\Double($value); - - case self::XMLRPC_TYPE_BOOLEAN: - return new Value\Boolean($value); - - case self::XMLRPC_TYPE_STRING: - return new Value\String($value); - - case self::XMLRPC_TYPE_BASE64: - return new Value\Base64($value); - - case self::XMLRPC_TYPE_NIL: - // fall through to the next case - case self::XMLRPC_TYPE_APACHENIL: - return new Value\Nil(); - - case self::XMLRPC_TYPE_DATETIME: - return new Value\DateTime($value); - - case self::XMLRPC_TYPE_ARRAY: - return new Value\ArrayValue($value); - - case self::XMLRPC_TYPE_STRUCT: - return new Value\Struct($value); - - default: - throw new Exception\ValueException('Given type is not a '. __CLASS__ .' constant'); - } - } - - /** - * Get XML-RPC type for a PHP native variable - * - * @static - * @param mixed $value - * @throws Exception\InvalidArgumentException - * @return string - */ - public static function getXmlRpcTypeByValue($value) - { - if (is_object($value)) { - if ($value instanceof AbstractValue) { - return $value->getType(); - } elseif ($value instanceof DateTime) { - return self::XMLRPC_TYPE_DATETIME; - } - return static::getXmlRpcTypeByValue(get_object_vars($value)); - } elseif (is_array($value)) { - if (!empty($value) && is_array($value) && (array_keys($value) !== range(0, count($value) - 1))) { - return self::XMLRPC_TYPE_STRUCT; - } - return self::XMLRPC_TYPE_ARRAY; - } elseif (is_int($value)) { - return ($value > PHP_INT_MAX) ? self::XMLRPC_TYPE_I8 : self::XMLRPC_TYPE_INTEGER; - } elseif (is_double($value)) { - return self::XMLRPC_TYPE_DOUBLE; - } elseif (is_bool($value)) { - return self::XMLRPC_TYPE_BOOLEAN; - } elseif (null === $value) { - return self::XMLRPC_TYPE_NIL; - } elseif (is_string($value)) { - return self::XMLRPC_TYPE_STRING; - } - throw new Exception\InvalidArgumentException(sprintf( - 'No matching XMLRPC type found for php type %s.', - gettype($value) - )); - } - - /** - * Transform a PHP native variable into a XML-RPC native value - * - * @param mixed $value The PHP variable for conversion - * - * @throws Exception\InvalidArgumentException - * @return AbstractValue - * @static - */ - protected static function _phpVarToNativeXmlRpc($value) - { - // @see http://framework.zend.com/issues/browse/ZF-8623 - if ($value instanceof AbstractValue) { - return $value; - } - - switch (static::getXmlRpcTypeByValue($value)) { - case self::XMLRPC_TYPE_DATETIME: - return new Value\DateTime($value); - - case self::XMLRPC_TYPE_ARRAY: - return new Value\ArrayValue($value); - - case self::XMLRPC_TYPE_STRUCT: - return new Value\Struct($value); - - case self::XMLRPC_TYPE_INTEGER: - return new Value\Integer($value); - - case self::XMLRPC_TYPE_DOUBLE: - return new Value\Double($value); - - case self::XMLRPC_TYPE_BOOLEAN: - return new Value\Boolean($value); - - case self::XMLRPC_TYPE_NIL: - return new Value\Nil; - - case self::XMLRPC_TYPE_STRING: - // Fall through to the next case - default: - // If type isn't identified (or identified as string), it treated as string - return new Value\String($value); - } - } - - /** - * Transform an XML string into a XML-RPC native value - * - * @param string|\SimpleXMLElement $xml A SimpleXMLElement object represent the XML string - * It can be also a valid XML string for conversion - * - * @throws Exception\ValueException - * @return \Zend\XmlRpc\AbstractValue - * @static - */ - protected static function _xmlStringToNativeXmlRpc($xml) - { - static::_createSimpleXMLElement($xml); - - static::_extractTypeAndValue($xml, $type, $value); - - switch ($type) { - // All valid and known XML-RPC native values - case self::XMLRPC_TYPE_I4: - // Fall through to the next case - case self::XMLRPC_TYPE_INTEGER: - $xmlrpcValue = new Value\Integer($value); - break; - case self::XMLRPC_TYPE_APACHEI8: - // Fall through to the next case - case self::XMLRPC_TYPE_I8: - $xmlrpcValue = new Value\BigInteger($value); - break; - case self::XMLRPC_TYPE_DOUBLE: - $xmlrpcValue = new Value\Double($value); - break; - case self::XMLRPC_TYPE_BOOLEAN: - $xmlrpcValue = new Value\Boolean($value); - break; - case self::XMLRPC_TYPE_STRING: - $xmlrpcValue = new Value\String($value); - break; - case self::XMLRPC_TYPE_DATETIME: // The value should already be in an iso8601 format - $xmlrpcValue = new Value\DateTime($value); - break; - case self::XMLRPC_TYPE_BASE64: // The value should already be base64 encoded - $xmlrpcValue = new Value\Base64($value, true); - break; - case self::XMLRPC_TYPE_NIL: - // Fall through to the next case - case self::XMLRPC_TYPE_APACHENIL: - // The value should always be NULL - $xmlrpcValue = new Value\Nil(); - break; - case self::XMLRPC_TYPE_ARRAY: - // PHP 5.2.4 introduced a regression in how empty($xml->value) - // returns; need to look for the item specifically - $data = null; - foreach ($value->children() as $key => $value) { - if ('data' == $key) { - $data = $value; - break; - } - } - - if (null === $data) { - throw new Exception\ValueException('Invalid XML for XML-RPC native '. self::XMLRPC_TYPE_ARRAY .' type: ARRAY tag must contain DATA tag'); - } - $values = array(); - // Parse all the elements of the array from the XML string - // (simple xml element) to Value objects - foreach ($data->value as $element) { - $values[] = static::_xmlStringToNativeXmlRpc($element); - } - $xmlrpcValue = new Value\ArrayValue($values); - break; - case self::XMLRPC_TYPE_STRUCT: - $values = array(); - // Parse all the members of the struct from the XML string - // (simple xml element) to Value objects - foreach ($value->member as $member) { - // @todo? If a member doesn't have a tag, we don't add it to the struct - // Maybe we want to throw an exception here ? - if (!isset($member->value) or !isset($member->name)) { - continue; - //throw new Value_Exception('Member of the '. self::XMLRPC_TYPE_STRUCT .' XML-RPC native type must contain a VALUE tag'); - } - $values[(string) $member->name] = static::_xmlStringToNativeXmlRpc($member->value); - } - $xmlrpcValue = new Value\Struct($values); - break; - default: - throw new Exception\ValueException('Value type \''. $type .'\' parsed from the XML string is not a known XML-RPC native type'); - break; - } - $xmlrpcValue->_setXML($xml->asXML()); - - return $xmlrpcValue; - } - - protected static function _createSimpleXMLElement(&$xml) - { - if ($xml instanceof \SimpleXMLElement) { - return; - } - - try { - $xml = new \SimpleXMLElement($xml); - } catch (\Exception $e) { - // The given string is not a valid XML - throw new Exception\ValueException('Failed to create XML-RPC value from XML string: ' . $e->getMessage(), $e->getCode(), $e); - } - } - - /** - * Extract XML/RPC type and value from SimpleXMLElement object - * - * @param \SimpleXMLElement $xml - * @param string &$type Type bind variable - * @param string &$value Value bind variable - * @return void - */ - protected static function _extractTypeAndValue(\SimpleXMLElement $xml, &$type, &$value) - { - list($type, $value) = each($xml); - if (!$type and $value === null) { - $namespaces = array('ex' => 'http://ws.apache.org/xmlrpc/namespaces/extensions'); - foreach ($namespaces as $namespaceName => $namespaceUri) { - $namespaceXml = $xml->children($namespaceUri); - list($type, $value) = each($namespaceXml); - if ($type !== null) { - $type = $namespaceName . ':' . $type; - break; - } - } - } - - // If no type was specified, the default is string - if (!$type) { - $type = self::XMLRPC_TYPE_STRING; - if (empty($value) and preg_match('#^.*$#', $xml->asXML())) { - $value = str_replace(array('', ''), '', $xml->asXML()); - } - } - } - - /** - * @param $xml - * @return void - */ - protected function _setXML($xml) - { - $this->xml = $this->getGenerator()->stripDeclaration($xml); - } -} diff --git a/library/Zend/XmlRpc/CONTRIBUTING.md b/library/Zend/XmlRpc/CONTRIBUTING.md deleted file mode 100755 index e77f5d2d5..000000000 --- a/library/Zend/XmlRpc/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# CONTRIBUTING - -Please don't open pull requests against this repository, please use https://github.com/zendframework/zf2. \ No newline at end of file diff --git a/library/Zend/XmlRpc/Client.php b/library/Zend/XmlRpc/Client.php deleted file mode 100755 index 504a3bf23..000000000 --- a/library/Zend/XmlRpc/Client.php +++ /dev/null @@ -1,343 +0,0 @@ -httpClient = new Http\Client(); - } else { - $this->httpClient = $httpClient; - } - - $this->introspector = new Client\ServerIntrospection($this); - $this->serverAddress = $server; - } - - - /** - * Sets the HTTP client object to use for connecting the XML-RPC server. - * - * @param \Zend\Http\Client $httpClient - * @return \Zend\Http\Client - */ - public function setHttpClient(Http\Client $httpClient) - { - return $this->httpClient = $httpClient; - } - - - /** - * Gets the HTTP client object. - * - * @return \Zend\Http\Client - */ - public function getHttpClient() - { - return $this->httpClient; - } - - - /** - * Sets the object used to introspect remote servers - * - * @param \Zend\XmlRpc\Client\ServerIntrospection - * @return \Zend\XmlRpc\Client\ServerIntrospection - */ - public function setIntrospector(Client\ServerIntrospection $introspector) - { - return $this->introspector = $introspector; - } - - - /** - * Gets the introspection object. - * - * @return \Zend\XmlRpc\Client\ServerIntrospection - */ - public function getIntrospector() - { - return $this->introspector; - } - - - /** - * The request of the last method call - * - * @return \Zend\XmlRpc\Request - */ - public function getLastRequest() - { - return $this->lastRequest; - } - - - /** - * The response received from the last method call - * - * @return \Zend\XmlRpc\Response - */ - public function getLastResponse() - { - return $this->lastResponse; - } - - - /** - * Returns a proxy object for more convenient method calls - * - * @param string $namespace Namespace to proxy or empty string for none - * @return \Zend\XmlRpc\Client\ServerProxy - */ - public function getProxy($namespace = '') - { - if (empty($this->proxyCache[$namespace])) { - $proxy = new Client\ServerProxy($this, $namespace); - $this->proxyCache[$namespace] = $proxy; - } - return $this->proxyCache[$namespace]; - } - - /** - * Set skip system lookup flag - * - * @param bool $flag - * @return \Zend\XmlRpc\Client - */ - public function setSkipSystemLookup($flag = true) - { - $this->skipSystemLookup = (bool) $flag; - return $this; - } - - /** - * Skip system lookup when determining if parameter should be array or struct? - * - * @return bool - */ - public function skipSystemLookup() - { - return $this->skipSystemLookup; - } - - /** - * Perform an XML-RPC request and return a response. - * - * @param \Zend\XmlRpc\Request $request - * @param null|\Zend\XmlRpc\Response $response - * @return void - * @throws \Zend\XmlRpc\Client\Exception\HttpException - */ - public function doRequest($request, $response = null) - { - $this->lastRequest = $request; - - if (PHP_VERSION_ID < 50600) { - iconv_set_encoding('input_encoding', 'UTF-8'); - iconv_set_encoding('output_encoding', 'UTF-8'); - iconv_set_encoding('internal_encoding', 'UTF-8'); - } else { - ini_set('default_charset', 'UTF-8'); - } - - $http = $this->getHttpClient(); - $httpRequest = $http->getRequest(); - if ($httpRequest->getUriString() === null) { - $http->setUri($this->serverAddress); - } - - $headers = $httpRequest->getHeaders(); - $headers->addHeaders(array( - 'Content-Type: text/xml; charset=utf-8', - 'Accept: text/xml', - )); - - if (!$headers->get('user-agent')) { - $headers->addHeaderLine('user-agent', 'Zend_XmlRpc_Client'); - } - - $xml = $this->lastRequest->__toString(); - $http->setRawBody($xml); - $httpResponse = $http->setMethod('POST')->send(); - - if (!$httpResponse->isSuccess()) { - /** - * Exception thrown when an HTTP error occurs - */ - throw new Client\Exception\HttpException( - $httpResponse->getReasonPhrase(), - $httpResponse->getStatusCode() - ); - } - - if ($response === null) { - $response = new Response(); - } - - $this->lastResponse = $response; - $this->lastResponse->loadXml(trim($httpResponse->getBody())); - } - - /** - * Send an XML-RPC request to the service (for a specific method) - * - * @param string $method Name of the method we want to call - * @param array $params Array of parameters for the method - * @return mixed - * @throws \Zend\XmlRpc\Client\Exception\FaultException - */ - public function call($method, $params=array()) - { - if (!$this->skipSystemLookup() && ('system.' != substr($method, 0, 7))) { - // Ensure empty array/struct params are cast correctly - // If system.* methods are not available, bypass. (ZF-2978) - $success = true; - try { - $signatures = $this->getIntrospector()->getMethodSignature($method); - } catch (\Zend\XmlRpc\Exception\ExceptionInterface $e) { - $success = false; - } - if ($success) { - $validTypes = array( - AbstractValue::XMLRPC_TYPE_ARRAY, - AbstractValue::XMLRPC_TYPE_BASE64, - AbstractValue::XMLRPC_TYPE_BOOLEAN, - AbstractValue::XMLRPC_TYPE_DATETIME, - AbstractValue::XMLRPC_TYPE_DOUBLE, - AbstractValue::XMLRPC_TYPE_I4, - AbstractValue::XMLRPC_TYPE_INTEGER, - AbstractValue::XMLRPC_TYPE_NIL, - AbstractValue::XMLRPC_TYPE_STRING, - AbstractValue::XMLRPC_TYPE_STRUCT, - ); - - if (!is_array($params)) { - $params = array($params); - } - foreach ($params as $key => $param) { - if ($param instanceof AbstractValue) { - continue; - } - - if (count($signatures) > 1) { - $type = AbstractValue::getXmlRpcTypeByValue($param); - foreach ($signatures as $signature) { - if (!is_array($signature)) { - continue; - } - if (isset($signature['parameters'][$key])) { - if ($signature['parameters'][$key] == $type) { - break; - } - } - } - } elseif (isset($signatures[0]['parameters'][$key])) { - $type = $signatures[0]['parameters'][$key]; - } else { - $type = null; - } - - if (empty($type) || !in_array($type, $validTypes)) { - $type = AbstractValue::AUTO_DETECT_TYPE; - } - - $params[$key] = AbstractValue::getXmlRpcValue($param, $type); - } - } - } - - $request = $this->_createRequest($method, $params); - - $this->doRequest($request); - - if ($this->lastResponse->isFault()) { - $fault = $this->lastResponse->getFault(); - /** - * Exception thrown when an XML-RPC fault is returned - */ - throw new Client\Exception\FaultException( - $fault->getMessage(), - $fault->getCode() - ); - } - - return $this->lastResponse->getReturnValue(); - } - - /** - * Create request object - * - * @param string $method - * @param array $params - * @return \Zend\XmlRpc\Request - */ - protected function _createRequest($method, $params) - { - return new Request($method, $params); - } -} diff --git a/library/Zend/XmlRpc/Client/Exception/ExceptionInterface.php b/library/Zend/XmlRpc/Client/Exception/ExceptionInterface.php deleted file mode 100755 index 03c09959c..000000000 --- a/library/Zend/XmlRpc/Client/Exception/ExceptionInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -system = $client->getProxy('system'); - } - - /** - * Returns the signature for each method on the server, - * autodetecting whether system.multicall() is supported and - * using it if so. - * - * @return array - */ - public function getSignatureForEachMethod() - { - $methods = $this->listMethods(); - - try { - $signatures = $this->getSignatureForEachMethodByMulticall($methods); - } catch (Exception\FaultException $e) { - // degrade to looping - } - - if (empty($signatures)) { - $signatures = $this->getSignatureForEachMethodByLooping($methods); - } - - return $signatures; - } - - /** - * Attempt to get the method signatures in one request via system.multicall(). - * This is a boxcar feature of XML-RPC and is found on fewer servers. However, - * can significantly improve performance if present. - * - * @param array $methods - * @throws Exception\IntrospectException - * @return array array(array(return, param, param, param...)) - */ - public function getSignatureForEachMethodByMulticall($methods = null) - { - if ($methods === null) { - $methods = $this->listMethods(); - } - - $multicallParams = array(); - foreach ($methods as $method) { - $multicallParams[] = array('methodName' => 'system.methodSignature', - 'params' => array($method)); - } - - $serverSignatures = $this->system->multicall($multicallParams); - - if (! is_array($serverSignatures)) { - $type = gettype($serverSignatures); - $error = "Multicall return is malformed. Expected array, got $type"; - throw new Exception\IntrospectException($error); - } - - if (count($serverSignatures) != count($methods)) { - $error = 'Bad number of signatures received from multicall'; - throw new Exception\IntrospectException($error); - } - - // Create a new signatures array with the methods name as keys and the signature as value - $signatures = array(); - foreach ($serverSignatures as $i => $signature) { - $signatures[$methods[$i]] = $signature; - } - - return $signatures; - } - - /** - * Get the method signatures for every method by - * successively calling system.methodSignature - * - * @param array $methods - * @return array - */ - public function getSignatureForEachMethodByLooping($methods = null) - { - if ($methods === null) { - $methods = $this->listMethods(); - } - - $signatures = array(); - foreach ($methods as $method) { - $signatures[$method] = $this->getMethodSignature($method); - } - - return $signatures; - } - - /** - * Call system.methodSignature() for the given method - * - * @param array $method - * @throws Exception\IntrospectException - * @return array array(array(return, param, param, param...)) - */ - public function getMethodSignature($method) - { - $signature = $this->system->methodSignature($method); - if (!is_array($signature)) { - $error = 'Invalid signature for method "' . $method . '"'; - throw new Exception\IntrospectException($error); - } - return $signature; - } - - /** - * Call system.listMethods() - * - * @return array array(method, method, method...) - */ - public function listMethods() - { - return $this->system->listMethods(); - } -} diff --git a/library/Zend/XmlRpc/Client/ServerProxy.php b/library/Zend/XmlRpc/Client/ServerProxy.php deleted file mode 100755 index 861b61590..000000000 --- a/library/Zend/XmlRpc/Client/ServerProxy.php +++ /dev/null @@ -1,79 +0,0 @@ -foo->bar->baz()". - */ -class ServerProxy -{ - /** - * @var \Zend\XmlRpc\Client - */ - private $client = null; - - /** - * @var string - */ - private $namespace = ''; - - - /** - * @var array of \Zend\XmlRpc\Client\ServerProxy - */ - private $cache = array(); - - - /** - * Class constructor - * - * @param \Zend\XmlRpc\Client $client - * @param string $namespace - */ - public function __construct(XMLRPCClient $client, $namespace = '') - { - $this->client = $client; - $this->namespace = $namespace; - } - - - /** - * Get the next successive namespace - * - * @param string $namespace - * @return \Zend\XmlRpc\Client\ServerProxy - */ - public function __get($namespace) - { - $namespace = ltrim("$this->namespace.$namespace", '.'); - if (!isset($this->cache[$namespace])) { - $this->cache[$namespace] = new $this($this->client, $namespace); - } - return $this->cache[$namespace]; - } - - - /** - * Call a method in this namespace. - * - * @param string $method - * @param array $args - * @return mixed - */ - public function __call($method, $args) - { - $method = ltrim("{$this->namespace}.{$method}", '.'); - return $this->client->call($method, $args); - } -} diff --git a/library/Zend/XmlRpc/Exception/BadMethodCallException.php b/library/Zend/XmlRpc/Exception/BadMethodCallException.php deleted file mode 100755 index db36424ab..000000000 --- a/library/Zend/XmlRpc/Exception/BadMethodCallException.php +++ /dev/null @@ -1,14 +0,0 @@ - messages - * @var array - */ - protected $internal = array( - 404 => 'Unknown Error', - - // 610 - 619 reflection errors - 610 => 'Invalid method class', - 611 => 'Unable to attach function or callback; not callable', - 612 => 'Unable to load array; not an array', - 613 => 'One or more method records are corrupt or otherwise unusable', - - // 620 - 629 dispatch errors - 620 => 'Method does not exist', - 621 => 'Error instantiating class to invoke method', - 622 => 'Method missing implementation', - 623 => 'Calling parameters do not match signature', - - // 630 - 639 request errors - 630 => 'Unable to read request', - 631 => 'Failed to parse request', - 632 => 'Invalid request, no method passed; request must contain a \'methodName\' tag', - 633 => 'Param must contain a value', - 634 => 'Invalid method name', - 635 => 'Invalid XML provided to request', - 636 => 'Error creating xmlrpc value', - - // 640 - 649 system.* errors - 640 => 'Method does not exist', - - // 650 - 659 response errors - 650 => 'Invalid XML provided for response', - 651 => 'Failed to parse response', - 652 => 'Invalid response', - 653 => 'Invalid XMLRPC value in response', - ); - - /** - * Constructor - * - */ - public function __construct($code = 404, $message = '') - { - $this->setCode($code); - $code = $this->getCode(); - - if (empty($message) && isset($this->internal[$code])) { - $message = $this->internal[$code]; - } elseif (empty($message)) { - $message = 'Unknown error'; - } - $this->setMessage($message); - } - - /** - * Set the fault code - * - * @param int $code - * @return Fault - */ - public function setCode($code) - { - $this->code = (int) $code; - return $this; - } - - /** - * Return fault code - * - * @return int - */ - public function getCode() - { - return $this->code; - } - - /** - * Retrieve fault message - * - * @param string - * @return Fault - */ - public function setMessage($message) - { - $this->message = (string) $message; - return $this; - } - - /** - * Retrieve fault message - * - * @return string - */ - public function getMessage() - { - return $this->message; - } - - /** - * Set encoding to use in fault response - * - * @param string $encoding - * @return Fault - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - AbstractValue::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current fault encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Load an XMLRPC fault from XML - * - * @param string $fault - * @return bool Returns true if successfully loaded fault response, false - * if response was not a fault response - * @throws Exception\ExceptionInterface if no or faulty XML provided, or if fault - * response does not contain either code or message - */ - public function loadXml($fault) - { - if (!is_string($fault)) { - throw new Exception\InvalidArgumentException('Invalid XML provided to fault'); - } - - $xmlErrorsFlag = libxml_use_internal_errors(true); - try { - $xml = XmlSecurity::scan($fault); - } catch (\ZendXml\Exception\RuntimeException $e) { - // Unsecure XML - throw new Exception\RuntimeException('Failed to parse XML fault: ' . $e->getMessage(), 500, $e); - } - if (!$xml instanceof SimpleXMLElement) { - $errors = libxml_get_errors(); - $errors = array_reduce($errors, function ($result, $item) { - if (empty($result)) { - return $item->message; - } - return $result . '; ' . $item->message; - }, ''); - libxml_use_internal_errors($xmlErrorsFlag); - throw new Exception\InvalidArgumentException('Failed to parse XML fault: ' . $errors, 500); - } - libxml_use_internal_errors($xmlErrorsFlag); - - // Check for fault - if (!$xml->fault) { - // Not a fault - return false; - } - - if (!$xml->fault->value->struct) { - // not a proper fault - throw new Exception\InvalidArgumentException('Invalid fault structure', 500); - } - - $structXml = $xml->fault->value->asXML(); - $struct = AbstractValue::getXmlRpcValue($structXml, AbstractValue::XML_STRING); - $struct = $struct->getValue(); - - if (isset($struct['faultCode'])) { - $code = $struct['faultCode']; - } - if (isset($struct['faultString'])) { - $message = $struct['faultString']; - } - - if (empty($code) && empty($message)) { - throw new Exception\InvalidArgumentException('Fault code and string required'); - } - - if (empty($code)) { - $code = '404'; - } - - if (empty($message)) { - if (isset($this->internal[$code])) { - $message = $this->internal[$code]; - } else { - $message = 'Unknown Error'; - } - } - - $this->setCode($code); - $this->setMessage($message); - - return true; - } - - /** - * Determine if an XML response is an XMLRPC fault - * - * @param string $xml - * @return bool - */ - public static function isFault($xml) - { - $fault = new static(); - try { - $isFault = $fault->loadXml($xml); - } catch (Exception\ExceptionInterface $e) { - $isFault = false; - } - - return $isFault; - } - - /** - * Serialize fault to XML - * - * @return string - */ - public function saveXml() - { - // Create fault value - $faultStruct = array( - 'faultCode' => $this->getCode(), - 'faultString' => $this->getMessage() - ); - $value = AbstractValue::getXmlRpcValue($faultStruct); - - $generator = AbstractValue::getGenerator(); - $generator->openElement('methodResponse') - ->openElement('fault'); - $value->generateXml(); - $generator->closeElement('fault') - ->closeElement('methodResponse'); - - return $generator->flush(); - } - - /** - * Return XML fault response - * - * @return string - */ - public function __toString() - { - return $this->saveXML(); - } -} diff --git a/library/Zend/XmlRpc/Generator/AbstractGenerator.php b/library/Zend/XmlRpc/Generator/AbstractGenerator.php deleted file mode 100755 index 693f026c0..000000000 --- a/library/Zend/XmlRpc/Generator/AbstractGenerator.php +++ /dev/null @@ -1,151 +0,0 @@ -setEncoding($encoding); - $this->_init(); - } - - /** - * Initialize internal objects - * - * @return void - */ - abstract protected function _init(); - - /** - * Start XML element - * - * Method opens a new XML element with an element name and an optional value - * - * @param string $name XML tag name - * @param string $value Optional value of the XML tag - * @return AbstractGenerator Fluent interface - */ - public function openElement($name, $value = null) - { - $this->_openElement($name); - if ($value !== null) { - $this->_writeTextData($value); - } - - return $this; - } - - /** - * End of an XML element - * - * Method marks the end of an XML element - * - * @param string $name XML tag name - * @return AbstractGenerator Fluent interface - */ - public function closeElement($name) - { - $this->_closeElement($name); - - return $this; - } - - /** - * Return encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set XML encoding - * - * @param string $encoding - * @return AbstractGenerator - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - return $this; - } - - /** - * Returns the XML as a string and flushes all internal buffers - * - * @return string - */ - public function flush() - { - $xml = $this->saveXml(); - $this->_init(); - return $xml; - } - - /** - * Returns XML without document declaration - * - * @return string - */ - public function __toString() - { - return $this->stripDeclaration($this->saveXml()); - } - - /** - * Removes XML declaration from a string - * - * @param string $xml - * @return string - */ - public function stripDeclaration($xml) - { - return preg_replace('/<\?xml version="1.0"( encoding="[^\"]*")?\?>\n/u', '', $xml); - } - - /** - * Start XML element - * - * @param string $name XML element name - */ - abstract protected function _openElement($name); - - /** - * Write XML text data into the currently opened XML element - * - * @param string $text - */ - abstract protected function _writeTextData($text); - - /** - * End XML element - * - * @param string $name - */ - abstract protected function _closeElement($name); -} diff --git a/library/Zend/XmlRpc/Generator/DomDocument.php b/library/Zend/XmlRpc/Generator/DomDocument.php deleted file mode 100755 index 47e7a7223..000000000 --- a/library/Zend/XmlRpc/Generator/DomDocument.php +++ /dev/null @@ -1,85 +0,0 @@ -dom->createElement($name); - - $this->currentElement = $this->currentElement->appendChild($newElement); - } - - /** - * Write XML text data into the currently opened XML element - * - * @param string $text - */ - protected function _writeTextData($text) - { - $this->currentElement->appendChild($this->dom->createTextNode($text)); - } - - /** - * Close a previously opened XML element - * - * Resets $currentElement to the next parent node in the hierarchy - * - * @param string $name - * @return void - */ - protected function _closeElement($name) - { - if (isset($this->currentElement->parentNode)) { - $this->currentElement = $this->currentElement->parentNode; - } - } - - /** - * Save XML as a string - * - * @return string - */ - public function saveXml() - { - return $this->dom->saveXml(); - } - - /** - * Initializes internal objects - * - * @return void - */ - protected function _init() - { - $this->dom = new \DOMDocument('1.0', $this->encoding); - $this->currentElement = $this->dom; - } -} diff --git a/library/Zend/XmlRpc/Generator/GeneratorInterface.php b/library/Zend/XmlRpc/Generator/GeneratorInterface.php deleted file mode 100755 index ca2af243b..000000000 --- a/library/Zend/XmlRpc/Generator/GeneratorInterface.php +++ /dev/null @@ -1,32 +0,0 @@ -xmlWriter = new \XMLWriter(); - $this->xmlWriter->openMemory(); - $this->xmlWriter->startDocument('1.0', $this->encoding); - } - - - /** - * Open a new XML element - * - * @param string $name XML element name - * @return void - */ - protected function _openElement($name) - { - $this->xmlWriter->startElement($name); - } - - /** - * Write XML text data into the currently opened XML element - * - * @param string $text XML text data - * @return void - */ - protected function _writeTextData($text) - { - $this->xmlWriter->text($text); - } - - /** - * Close a previously opened XML element - * - * @param string $name - * @return XmlWriter - */ - protected function _closeElement($name) - { - $this->xmlWriter->endElement(); - - return $this; - } - - /** - * Emit XML document - * - * @return string - */ - public function saveXml() - { - return $this->xmlWriter->flush(false); - } -} diff --git a/library/Zend/XmlRpc/README.md b/library/Zend/XmlRpc/README.md deleted file mode 100755 index f003296a4..000000000 --- a/library/Zend/XmlRpc/README.md +++ /dev/null @@ -1,15 +0,0 @@ -XML-RPC Component from ZF2 -========================== - -This is the XML-RPC component for ZF2. - -- File issues at https://github.com/zendframework/zf2/issues -- Create pull requests against https://github.com/zendframework/zf2 -- Documentation is at http://framework.zend.com/docs - -LICENSE -------- - -The files in this archive are released under the [Zend Framework -license](http://framework.zend.com/license), which is a 3-clause BSD license. - diff --git a/library/Zend/XmlRpc/Request.php b/library/Zend/XmlRpc/Request.php deleted file mode 100755 index 82a7eedbe..000000000 --- a/library/Zend/XmlRpc/Request.php +++ /dev/null @@ -1,444 +0,0 @@ -setMethod($method); - } - - if ($params !== null) { - $this->setParams($params); - } - } - - - /** - * Set encoding to use in request - * - * @param string $encoding - * @return \Zend\XmlRpc\Request - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - AbstractValue::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current request encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set method to call - * - * @param string $method - * @return bool Returns true on success, false if method name is invalid - */ - public function setMethod($method) - { - if (!is_string($method) || !preg_match('/^[a-z0-9_.:\\\\\/]+$/i', $method)) { - $this->fault = new Fault(634, 'Invalid method name ("' . $method . '")'); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - $this->method = $method; - return true; - } - - /** - * Retrieve call method - * - * @return string - */ - public function getMethod() - { - return $this->method; - } - - /** - * Add a parameter to the parameter stack - * - * Adds a parameter to the parameter stack, associating it with the type - * $type if provided - * - * @param mixed $value - * @param string $type Optional; type hinting - * @return void - */ - public function addParam($value, $type = null) - { - $this->params[] = $value; - if (null === $type) { - // Detect type if not provided explicitly - if ($value instanceof AbstractValue) { - $type = $value->getType(); - } else { - $xmlRpcValue = AbstractValue::getXmlRpcValue($value); - $type = $xmlRpcValue->getType(); - } - } - $this->types[] = $type; - $this->xmlRpcParams[] = array('value' => $value, 'type' => $type); - } - - /** - * Set the parameters array - * - * If called with a single, array value, that array is used to set the - * parameters stack. If called with multiple values or a single non-array - * value, the arguments are used to set the parameters stack. - * - * Best is to call with array of the format, in order to allow type hinting - * when creating the XMLRPC values for each parameter: - * - * $array = array( - * array( - * 'value' => $value, - * 'type' => $type - * )[, ... ] - * ); - * - * - * @access public - * @return void - */ - public function setParams() - { - $argc = func_num_args(); - $argv = func_get_args(); - if (0 == $argc) { - return; - } - - if ((1 == $argc) && is_array($argv[0])) { - $params = array(); - $types = array(); - $wellFormed = true; - foreach ($argv[0] as $arg) { - if (!is_array($arg) || !isset($arg['value'])) { - $wellFormed = false; - break; - } - $params[] = $arg['value']; - - if (!isset($arg['type'])) { - $xmlRpcValue = AbstractValue::getXmlRpcValue($arg['value']); - $arg['type'] = $xmlRpcValue->getType(); - } - $types[] = $arg['type']; - } - if ($wellFormed) { - $this->xmlRpcParams = $argv[0]; - $this->params = $params; - $this->types = $types; - } else { - $this->params = $argv[0]; - $this->types = array(); - $xmlRpcParams = array(); - foreach ($argv[0] as $arg) { - if ($arg instanceof AbstractValue) { - $type = $arg->getType(); - } else { - $xmlRpcValue = AbstractValue::getXmlRpcValue($arg); - $type = $xmlRpcValue->getType(); - } - $xmlRpcParams[] = array('value' => $arg, 'type' => $type); - $this->types[] = $type; - } - $this->xmlRpcParams = $xmlRpcParams; - } - return; - } - - $this->params = $argv; - $this->types = array(); - $xmlRpcParams = array(); - foreach ($argv as $arg) { - if ($arg instanceof AbstractValue) { - $type = $arg->getType(); - } else { - $xmlRpcValue = AbstractValue::getXmlRpcValue($arg); - $type = $xmlRpcValue->getType(); - } - $xmlRpcParams[] = array('value' => $arg, 'type' => $type); - $this->types[] = $type; - } - $this->xmlRpcParams = $xmlRpcParams; - } - - /** - * Retrieve the array of parameters - * - * @return array - */ - public function getParams() - { - return $this->params; - } - - /** - * Return parameter types - * - * @return array - */ - public function getTypes() - { - return $this->types; - } - - /** - * Load XML and parse into request components - * - * @param string $request - * @throws Exception\ValueException if invalid XML - * @return bool True on success, false if an error occurred. - */ - public function loadXml($request) - { - if (!is_string($request)) { - $this->fault = new Fault(635); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - // @see ZF-12293 - disable external entities for security purposes - $loadEntities = libxml_disable_entity_loader(true); - $xmlErrorsFlag = libxml_use_internal_errors(true); - try { - $dom = new DOMDocument; - $dom->loadXML($request); - foreach ($dom->childNodes as $child) { - if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { - throw new Exception\ValueException( - 'Invalid XML: Detected use of illegal DOCTYPE' - ); - } - } - ErrorHandler::start(); - $xml = simplexml_import_dom($dom); - $error = ErrorHandler::stop(); - libxml_disable_entity_loader($loadEntities); - libxml_use_internal_errors($xmlErrorsFlag); - } catch (\Exception $e) { - // Not valid XML - $this->fault = new Fault(631); - $this->fault->setEncoding($this->getEncoding()); - libxml_disable_entity_loader($loadEntities); - libxml_use_internal_errors($xmlErrorsFlag); - return false; - } - if (!$xml instanceof SimpleXMLElement || $error) { - // Not valid XML - $this->fault = new Fault(631); - $this->fault->setEncoding($this->getEncoding()); - libxml_use_internal_errors($xmlErrorsFlag); - return false; - } - - // Check for method name - if (empty($xml->methodName)) { - // Missing method name - $this->fault = new Fault(632); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - $this->method = (string) $xml->methodName; - - // Check for parameters - if (!empty($xml->params)) { - $types = array(); - $argv = array(); - foreach ($xml->params->children() as $param) { - if (!isset($param->value)) { - $this->fault = new Fault(633); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - try { - $param = AbstractValue::getXmlRpcValue($param->value, AbstractValue::XML_STRING); - $types[] = $param->getType(); - $argv[] = $param->getValue(); - } catch (\Exception $e) { - $this->fault = new Fault(636); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - } - - $this->types = $types; - $this->params = $argv; - } - - $this->xml = $request; - - return true; - } - - /** - * Does the current request contain errors and should it return a fault - * response? - * - * @return bool - */ - public function isFault() - { - return $this->fault instanceof Fault; - } - - /** - * Retrieve the fault response, if any - * - * @return null|\Zend\XmlRpc\Fault - */ - public function getFault() - { - return $this->fault; - } - - /** - * Retrieve method parameters as XMLRPC values - * - * @return array - */ - protected function _getXmlRpcParams() - { - $params = array(); - if (is_array($this->xmlRpcParams)) { - foreach ($this->xmlRpcParams as $param) { - $value = $param['value']; - $type = $param['type'] ?: AbstractValue::AUTO_DETECT_TYPE; - - if (!$value instanceof AbstractValue) { - $value = AbstractValue::getXmlRpcValue($value, $type); - } - $params[] = $value; - } - } - - return $params; - } - - /** - * Create XML request - * - * @return string - */ - public function saveXml() - { - $args = $this->_getXmlRpcParams(); - $method = $this->getMethod(); - - $generator = AbstractValue::getGenerator(); - $generator->openElement('methodCall') - ->openElement('methodName', $method) - ->closeElement('methodName'); - - if (is_array($args) && count($args)) { - $generator->openElement('params'); - - foreach ($args as $arg) { - $generator->openElement('param'); - $arg->generateXml(); - $generator->closeElement('param'); - } - $generator->closeElement('params'); - } - $generator->closeElement('methodCall'); - - return $generator->flush(); - } - - /** - * Return XML request - * - * @return string - */ - public function __toString() - { - return $this->saveXML(); - } -} diff --git a/library/Zend/XmlRpc/Request/Http.php b/library/Zend/XmlRpc/Request/Http.php deleted file mode 100755 index d42a8331d..000000000 --- a/library/Zend/XmlRpc/Request/Http.php +++ /dev/null @@ -1,108 +0,0 @@ -fault = new Fault(630); - return; - } - - $this->xml = $xml; - - $this->loadXml($xml); - } - - /** - * Retrieve the raw XML request - * - * @return string - */ - public function getRawRequest() - { - return $this->xml; - } - - /** - * Get headers - * - * Gets all headers as key => value pairs and returns them. - * - * @return array - */ - public function getHeaders() - { - if (null === $this->headers) { - $this->headers = array(); - foreach ($_SERVER as $key => $value) { - if ('HTTP_' == substr($key, 0, 5)) { - $header = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5))))); - $this->headers[$header] = $value; - } - } - } - - return $this->headers; - } - - /** - * Retrieve the full HTTP request, including headers and XML - * - * @return string - */ - public function getFullRequest() - { - $request = ''; - foreach ($this->getHeaders() as $key => $value) { - $request .= $key . ': ' . $value . "\n"; - } - - $request .= $this->xml; - - return $request; - } -} diff --git a/library/Zend/XmlRpc/Request/Stdin.php b/library/Zend/XmlRpc/Request/Stdin.php deleted file mode 100755 index bcf748e95..000000000 --- a/library/Zend/XmlRpc/Request/Stdin.php +++ /dev/null @@ -1,66 +0,0 @@ -fault = new Fault(630); - return; - } - - $xml = ''; - while (!feof($fh)) { - $xml .= fgets($fh); - } - fclose($fh); - - $this->xml = $xml; - - $this->loadXml($xml); - } - - /** - * Retrieve the raw XML request - * - * @return string - */ - public function getRawRequest() - { - return $this->xml; - } -} diff --git a/library/Zend/XmlRpc/Response.php b/library/Zend/XmlRpc/Response.php deleted file mode 100755 index f8537584e..000000000 --- a/library/Zend/XmlRpc/Response.php +++ /dev/null @@ -1,224 +0,0 @@ -setReturnValue($return, $type); - } - - /** - * Set encoding to use in response - * - * @param string $encoding - * @return \Zend\XmlRpc\Response - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - AbstractValue::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current response encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Set the return value - * - * Sets the return value, with optional type hinting if provided. - * - * @param mixed $value - * @param string $type - * @return void - */ - public function setReturnValue($value, $type = null) - { - $this->return = $value; - $this->type = (string) $type; - } - - /** - * Retrieve the return value - * - * @return mixed - */ - public function getReturnValue() - { - return $this->return; - } - - /** - * Retrieve the XMLRPC value for the return value - * - * @return \Zend\XmlRpc\AbstractValue - */ - protected function _getXmlRpcReturn() - { - return AbstractValue::getXmlRpcValue($this->return); - } - - /** - * Is the response a fault response? - * - * @return bool - */ - public function isFault() - { - return $this->fault instanceof Fault; - } - - /** - * Returns the fault, if any. - * - * @return null|\Zend\XmlRpc\Fault - */ - public function getFault() - { - return $this->fault; - } - - /** - * Load a response from an XML response - * - * Attempts to load a response from an XMLRPC response, autodetecting if it - * is a fault response. - * - * @param string $response - * @throws Exception\ValueException if invalid XML - * @return bool True if a valid XMLRPC response, false if a fault - * response or invalid input - */ - public function loadXml($response) - { - if (!is_string($response)) { - $this->fault = new Fault(650); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - try { - $xml = XmlSecurity::scan($response); - } catch (\ZendXml\Exception\RuntimeException $e) { - $this->fault = new Fault(651); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - if (!empty($xml->fault)) { - // fault response - $this->fault = new Fault(); - $this->fault->setEncoding($this->getEncoding()); - $this->fault->loadXml($response); - return false; - } - - if (empty($xml->params)) { - // Invalid response - $this->fault = new Fault(652); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - try { - if (!isset($xml->params) || !isset($xml->params->param) || !isset($xml->params->param->value)) { - throw new Exception\ValueException('Missing XML-RPC value in XML'); - } - $valueXml = $xml->params->param->value->asXML(); - $value = AbstractValue::getXmlRpcValue($valueXml, AbstractValue::XML_STRING); - } catch (Exception\ValueException $e) { - $this->fault = new Fault(653); - $this->fault->setEncoding($this->getEncoding()); - return false; - } - - $this->setReturnValue($value->getValue()); - return true; - } - - /** - * Return response as XML - * - * @return string - */ - public function saveXml() - { - $value = $this->_getXmlRpcReturn(); - $generator = AbstractValue::getGenerator(); - $generator->openElement('methodResponse') - ->openElement('params') - ->openElement('param'); - $value->generateXml(); - $generator->closeElement('param') - ->closeElement('params') - ->closeElement('methodResponse'); - - return $generator->flush(); - } - - /** - * Return XML response - * - * @return string - */ - public function __toString() - { - return $this->saveXML(); - } -} diff --git a/library/Zend/XmlRpc/Response/Http.php b/library/Zend/XmlRpc/Response/Http.php deleted file mode 100755 index 00ae07cc9..000000000 --- a/library/Zend/XmlRpc/Response/Http.php +++ /dev/null @@ -1,32 +0,0 @@ -getEncoding())); - } - - return parent::__toString(); - } -} diff --git a/library/Zend/XmlRpc/Server.php b/library/Zend/XmlRpc/Server.php deleted file mode 100755 index e2cfcea6b..000000000 --- a/library/Zend/XmlRpc/Server.php +++ /dev/null @@ -1,609 +0,0 @@ - - * use Zend\XmlRpc; - * - * // Instantiate server - * $server = new XmlRpc\Server(); - * - * // Allow some exceptions to report as fault responses: - * XmlRpc\Server\Fault::attachFaultException('My\\Exception'); - * XmlRpc\Server\Fault::attachObserver('My\\Fault\\Observer'); - * - * // Get or build dispatch table: - * if (!XmlRpc\Server\Cache::get($filename, $server)) { - * - * // Attach Some_Service_Class in 'some' namespace - * $server->setClass('Some\\Service\\Class', 'some'); - * - * // Attach Another_Service_Class in 'another' namespace - * $server->setClass('Another\\Service\\Class', 'another'); - * - * // Create dispatch table cache file - * XmlRpc\Server\Cache::save($filename, $server); - * } - * - * $response = $server->handle(); - * echo $response; - * - */ -class Server extends AbstractServer -{ - /** - * Character encoding - * @var string - */ - protected $encoding = 'UTF-8'; - - /** - * Request processed - * @var null|Request - */ - protected $request = null; - - /** - * Class to use for responses; defaults to {@link Response\Http} - * @var string - */ - protected $responseClass = 'Zend\XmlRpc\Response\Http'; - - /** - * Dispatch table of name => method pairs - * @var Definition - */ - protected $table; - - /** - * PHP types => XML-RPC types - * @var array - */ - protected $typeMap = array( - 'i4' => 'i4', - 'int' => 'int', - 'integer' => 'int', - 'i8' => 'i8', - 'ex:i8' => 'i8', - 'double' => 'double', - 'float' => 'double', - 'real' => 'double', - 'boolean' => 'boolean', - 'bool' => 'boolean', - 'true' => 'boolean', - 'false' => 'boolean', - 'string' => 'string', - 'str' => 'string', - 'base64' => 'base64', - 'dateTime.iso8601' => 'dateTime.iso8601', - 'date' => 'dateTime.iso8601', - 'time' => 'dateTime.iso8601', - 'DateTime' => 'dateTime.iso8601', - 'array' => 'array', - 'struct' => 'struct', - 'null' => 'nil', - 'nil' => 'nil', - 'ex:nil' => 'nil', - 'void' => 'void', - 'mixed' => 'struct', - ); - - /** - * Send arguments to all methods or just constructor? - * - * @var bool - */ - protected $sendArgumentsToAllMethods = true; - - /** - * Flag: whether or not {@link handle()} should return a response instead - * of automatically emitting it. - * @var bool - */ - protected $returnResponse = false; - - /** - * Last response results. - * @var Response - */ - protected $response; - - /** - * Constructor - * - * Creates system.* methods. - * - */ - public function __construct() - { - $this->table = new Definition(); - $this->registerSystemMethods(); - } - - /** - * Proxy calls to system object - * - * @param string $method - * @param array $params - * @return mixed - * @throws Server\Exception\BadMethodCallException - */ - public function __call($method, $params) - { - $system = $this->getSystem(); - if (!method_exists($system, $method)) { - throw new Server\Exception\BadMethodCallException('Unknown instance method called on server: ' . $method); - } - return call_user_func_array(array($system, $method), $params); - } - - /** - * Attach a callback as an XMLRPC method - * - * Attaches a callback as an XMLRPC method, prefixing the XMLRPC method name - * with $namespace, if provided. Reflection is done on the callback's - * docblock to create the methodHelp for the XMLRPC method. - * - * Additional arguments to pass to the function at dispatch may be passed; - * any arguments following the namespace will be aggregated and passed at - * dispatch time. - * - * @param string|array|callable $function Valid callback - * @param string $namespace Optional namespace prefix - * @throws Server\Exception\InvalidArgumentException - * @return void - */ - public function addFunction($function, $namespace = '') - { - if (!is_string($function) && !is_array($function)) { - throw new Server\Exception\InvalidArgumentException('Unable to attach function; invalid', 611); - } - - $argv = null; - if (2 < func_num_args()) { - $argv = func_get_args(); - $argv = array_slice($argv, 2); - } - - $function = (array) $function; - foreach ($function as $func) { - if (!is_string($func) || !function_exists($func)) { - throw new Server\Exception\InvalidArgumentException('Unable to attach function; invalid', 611); - } - $reflection = Reflection::reflectFunction($func, $argv, $namespace); - $this->_buildSignature($reflection); - } - } - - /** - * Attach class methods as XMLRPC method handlers - * - * $class may be either a class name or an object. Reflection is done on the - * class or object to determine the available public methods, and each is - * attached to the server as an available method; if a $namespace has been - * provided, that namespace is used to prefix the XMLRPC method names. - * - * Any additional arguments beyond $namespace will be passed to a method at - * invocation. - * - * @param string|object $class - * @param string $namespace Optional - * @param mixed $argv Optional arguments to pass to methods - * @return void - * @throws Server\Exception\InvalidArgumentException on invalid input - */ - public function setClass($class, $namespace = '', $argv = null) - { - if (is_string($class) && !class_exists($class)) { - throw new Server\Exception\InvalidArgumentException('Invalid method class', 610); - } - - if (2 < func_num_args()) { - $argv = func_get_args(); - $argv = array_slice($argv, 2); - } - - $dispatchable = Reflection::reflectClass($class, $argv, $namespace); - foreach ($dispatchable->getMethods() as $reflection) { - $this->_buildSignature($reflection, $class); - } - } - - /** - * Raise an xmlrpc server fault - * - * @param string|\Exception $fault - * @param int $code - * @return Server\Fault - */ - public function fault($fault = null, $code = 404) - { - if (!$fault instanceof \Exception) { - $fault = (string) $fault; - if (empty($fault)) { - $fault = 'Unknown Error'; - } - $fault = new Server\Exception\RuntimeException($fault, $code); - } - - return Server\Fault::getInstance($fault); - } - - /** - * Set return response flag - * - * If true, {@link handle()} will return the response instead of - * automatically sending it back to the requesting client. - * - * The response is always available via {@link getResponse()}. - * - * @param bool $flag - * @return Server - */ - public function setReturnResponse($flag = true) - { - $this->returnResponse = ($flag) ? true : false; - return $this; - } - - /** - * Retrieve return response flag - * - * @return bool - */ - public function getReturnResponse() - { - return $this->returnResponse; - } - - /** - * Handle an xmlrpc call - * - * @param Request $request Optional - * @return Response|Fault - */ - public function handle($request = false) - { - // Get request - if ((!$request || !$request instanceof Request) - && (null === ($request = $this->getRequest())) - ) { - $request = new Request\Http(); - $request->setEncoding($this->getEncoding()); - } - - $this->setRequest($request); - - if ($request->isFault()) { - $response = $request->getFault(); - } else { - try { - $response = $this->handleRequest($request); - } catch (\Exception $e) { - $response = $this->fault($e); - } - } - - // Set output encoding - $response->setEncoding($this->getEncoding()); - $this->response = $response; - - if (!$this->returnResponse) { - echo $response; - return; - } - - return $response; - } - - /** - * Load methods as returned from {@link getFunctions} - * - * Typically, you will not use this method; it will be called using the - * results pulled from {@link Zend\XmlRpc\Server\Cache::get()}. - * - * @param array|Definition $definition - * @return void - * @throws Server\Exception\InvalidArgumentException on invalid input - */ - public function loadFunctions($definition) - { - if (!is_array($definition) && (!$definition instanceof Definition)) { - if (is_object($definition)) { - $type = get_class($definition); - } else { - $type = gettype($definition); - } - throw new Server\Exception\InvalidArgumentException('Unable to load server definition; must be an array or Zend\Server\Definition, received ' . $type, 612); - } - - $this->table->clearMethods(); - $this->registerSystemMethods(); - - if ($definition instanceof Definition) { - $definition = $definition->getMethods(); - } - - foreach ($definition as $key => $method) { - if ('system.' == substr($key, 0, 7)) { - continue; - } - $this->table->addMethod($method, $key); - } - } - - /** - * Set encoding - * - * @param string $encoding - * @return Server - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - AbstractValue::setEncoding($encoding); - return $this; - } - - /** - * Retrieve current encoding - * - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Do nothing; persistence is handled via {@link Zend\XmlRpc\Server\Cache} - * - * @param mixed $mode - * @return void - */ - public function setPersistence($mode) - { - } - - /** - * Set the request object - * - * @param string|Request $request - * @return Server - * @throws Server\Exception\InvalidArgumentException on invalid request class or object - */ - public function setRequest($request) - { - if (is_string($request) && class_exists($request)) { - $request = new $request(); - if (!$request instanceof Request) { - throw new Server\Exception\InvalidArgumentException('Invalid request class'); - } - $request->setEncoding($this->getEncoding()); - } elseif (!$request instanceof Request) { - throw new Server\Exception\InvalidArgumentException('Invalid request object'); - } - - $this->request = $request; - return $this; - } - - /** - * Return currently registered request object - * - * @return null|Request - */ - public function getRequest() - { - return $this->request; - } - - /** - * Last response. - * - * @return Response - */ - public function getResponse() - { - return $this->response; - } - - /** - * Set the class to use for the response - * - * @param string $class - * @throws Server\Exception\InvalidArgumentException if invalid response class - * @return bool True if class was set, false if not - */ - public function setResponseClass($class) - { - if (!class_exists($class) || !static::isSubclassOf($class, 'Zend\XmlRpc\Response')) { - throw new Server\Exception\InvalidArgumentException('Invalid response class'); - } - $this->responseClass = $class; - return true; - } - - /** - * Retrieve current response class - * - * @return string - */ - public function getResponseClass() - { - return $this->responseClass; - } - - /** - * Retrieve dispatch table - * - * @return array - */ - public function getDispatchTable() - { - return $this->table; - } - - /** - * Returns a list of registered methods - * - * Returns an array of dispatchables (Zend\Server\Reflection\ReflectionFunction, - * ReflectionMethod, and ReflectionClass items). - * - * @return array - */ - public function getFunctions() - { - return $this->table->toArray(); - } - - /** - * Retrieve system object - * - * @return Server\System - */ - public function getSystem() - { - return $this->system; - } - - /** - * Send arguments to all methods? - * - * If setClass() is used to add classes to the server, this flag defined - * how to handle arguments. If set to true, all methods including constructor - * will receive the arguments. If set to false, only constructor will receive the - * arguments - */ - public function sendArgumentsToAllMethods($flag = null) - { - if ($flag === null) { - return $this->sendArgumentsToAllMethods; - } - - $this->sendArgumentsToAllMethods = (bool) $flag; - return $this; - } - - /** - * Map PHP type to XML-RPC type - * - * @param string $type - * @return string - */ - protected function _fixType($type) - { - if (isset($this->typeMap[$type])) { - return $this->typeMap[$type]; - } - return 'void'; - } - - /** - * Handle an xmlrpc call (actual work) - * - * @param Request $request - * @return Response - * @throws Server\Exception\RuntimeException - * Zend\XmlRpc\Server\Exceptions are thrown for internal errors; otherwise, - * any other exception may be thrown by the callback - */ - protected function handleRequest(Request $request) - { - $method = $request->getMethod(); - - // Check for valid method - if (!$this->table->hasMethod($method)) { - throw new Server\Exception\RuntimeException('Method "' . $method . '" does not exist', 620); - } - - $info = $this->table->getMethod($method); - $params = $request->getParams(); - $argv = $info->getInvokeArguments(); - if (0 < count($argv) and $this->sendArgumentsToAllMethods()) { - $params = array_merge($params, $argv); - } - - // Check calling parameters against signatures - $matched = false; - $sigCalled = $request->getTypes(); - - $sigLength = count($sigCalled); - $paramsLen = count($params); - if ($sigLength < $paramsLen) { - for ($i = $sigLength; $i < $paramsLen; ++$i) { - $xmlRpcValue = AbstractValue::getXmlRpcValue($params[$i]); - $sigCalled[] = $xmlRpcValue->getType(); - } - } - - $signatures = $info->getPrototypes(); - foreach ($signatures as $signature) { - $sigParams = $signature->getParameters(); - if ($sigCalled === $sigParams) { - $matched = true; - break; - } - } - if (!$matched) { - throw new Server\Exception\RuntimeException('Calling parameters do not match signature', 623); - } - - $return = $this->_dispatch($info, $params); - $responseClass = $this->getResponseClass(); - return new $responseClass($return); - } - - /** - * Register system methods with the server - * - * @return void - */ - protected function registerSystemMethods() - { - $system = new Server\System($this); - $this->system = $system; - $this->setClass($system, 'system'); - } - - /** - * Checks if the object has this class as one of its parents - * - * @see https://bugs.php.net/bug.php?id=53727 - * @see https://github.com/zendframework/zf2/pull/1807 - * - * @param string $className - * @param string $type - * @return bool - */ - protected static function isSubclassOf($className, $type) - { - if (is_subclass_of($className, $type)) { - return true; - } - if (PHP_VERSION_ID >= 50307) { - return false; - } - if (!interface_exists($type)) { - return false; - } - $r = new ReflectionClass($className); - return $r->implementsInterface($type); - } -} diff --git a/library/Zend/XmlRpc/Server/Cache.php b/library/Zend/XmlRpc/Server/Cache.php deleted file mode 100755 index f4e643ea6..000000000 --- a/library/Zend/XmlRpc/Server/Cache.php +++ /dev/null @@ -1,26 +0,0 @@ - true); - - /** - * @var array Array of fault observers - */ - protected static $observers = array(); - - /** - * Constructor - * - * @param \Exception $e - * @return Fault - */ - public function __construct(\Exception $e) - { - $this->exception = $e; - $code = 404; - $message = 'Unknown error'; - - foreach (array_keys(static::$faultExceptionClasses) as $class) { - if ($e instanceof $class) { - $code = $e->getCode(); - $message = $e->getMessage(); - break; - } - } - - parent::__construct($code, $message); - - // Notify exception observers, if present - if (!empty(static::$observers)) { - foreach (array_keys(static::$observers) as $observer) { - $observer::observe($this); - } - } - } - - /** - * Return Zend\XmlRpc\Server\Fault instance - * - * @param \Exception $e - * @return Fault - */ - public static function getInstance(\Exception $e) - { - return new static($e); - } - - /** - * Attach valid exceptions that can be used to define xmlrpc faults - * - * @param string|array $classes Class name or array of class names - * @return void - */ - public static function attachFaultException($classes) - { - if (!is_array($classes)) { - $classes = (array) $classes; - } - - foreach ($classes as $class) { - if (is_string($class) && class_exists($class)) { - static::$faultExceptionClasses[$class] = true; - } - } - } - - /** - * Detach fault exception classes - * - * @param string|array $classes Class name or array of class names - * @return void - */ - public static function detachFaultException($classes) - { - if (!is_array($classes)) { - $classes = (array) $classes; - } - - foreach ($classes as $class) { - if (is_string($class) && isset(static::$faultExceptionClasses[$class])) { - unset(static::$faultExceptionClasses[$class]); - } - } - } - - /** - * Attach an observer class - * - * Allows observation of xmlrpc server faults, thus allowing logging or mail - * notification of fault responses on the xmlrpc server. - * - * Expects a valid class name; that class must have a public static method - * 'observe' that accepts an exception as its sole argument. - * - * @param string $class - * @return bool - */ - public static function attachObserver($class) - { - if (!is_string($class) - || !class_exists($class) - || !is_callable(array($class, 'observe')) - ) { - return false; - } - - if (!isset(static::$observers[$class])) { - static::$observers[$class] = true; - } - - return true; - } - - /** - * Detach an observer - * - * @param string $class - * @return bool - */ - public static function detachObserver($class) - { - if (!isset(static::$observers[$class])) { - return false; - } - - unset(static::$observers[$class]); - return true; - } - - /** - * Retrieve the exception - * - * @access public - * @return \Exception - */ - public function getException() - { - return $this->exception; - } -} diff --git a/library/Zend/XmlRpc/Server/System.php b/library/Zend/XmlRpc/Server/System.php deleted file mode 100755 index 8a57838b1..000000000 --- a/library/Zend/XmlRpc/Server/System.php +++ /dev/null @@ -1,144 +0,0 @@ -server = $server; - } - - /** - * List all available XMLRPC methods - * - * Returns an array of methods. - * - * @return array - */ - public function listMethods() - { - $table = $this->server->getDispatchTable()->getMethods(); - return array_keys($table); - } - - /** - * Display help message for an XMLRPC method - * - * @param string $method - * @throws Exception\InvalidArgumentException - * @return string - */ - public function methodHelp($method) - { - $table = $this->server->getDispatchTable(); - if (!$table->hasMethod($method)) { - throw new Exception\InvalidArgumentException('Method "' . $method . '" does not exist', 640); - } - - return $table->getMethod($method)->getMethodHelp(); - } - - /** - * Return a method signature - * - * @param string $method - * @throws Exception\InvalidArgumentException - * @return array - */ - public function methodSignature($method) - { - $table = $this->server->getDispatchTable(); - if (!$table->hasMethod($method)) { - throw new Exception\InvalidArgumentException('Method "' . $method . '" does not exist', 640); - } - $method = $table->getMethod($method)->toArray(); - return $method['prototypes']; - } - - /** - * Multicall - boxcar feature of XML-RPC for calling multiple methods - * in a single request. - * - * Expects an array of structs representing method calls, each element - * having the keys: - * - methodName - * - params - * - * Returns an array of responses, one for each method called, with the value - * returned by the method. If an error occurs for a given method, returns a - * struct with a fault response. - * - * @see http://www.xmlrpc.com/discuss/msgReader$1208 - * @param array $methods - * @return array - */ - public function multicall($methods) - { - $responses = array(); - foreach ($methods as $method) { - $fault = false; - if (!is_array($method)) { - $fault = $this->server->fault('system.multicall expects each method to be a struct', 601); - } elseif (!isset($method['methodName'])) { - $fault = $this->server->fault('Missing methodName: ' . var_export($methods, 1), 602); - } elseif (!isset($method['params'])) { - $fault = $this->server->fault('Missing params', 603); - } elseif (!is_array($method['params'])) { - $fault = $this->server->fault('Params must be an array', 604); - } else { - if ('system.multicall' == $method['methodName']) { - // don't allow recursive calls to multicall - $fault = $this->server->fault('Recursive system.multicall forbidden', 605); - } - } - - if (!$fault) { - try { - $request = new \Zend\XmlRpc\Request(); - $request->setMethod($method['methodName']); - $request->setParams($method['params']); - $response = $this->server->handle($request); - if ($response instanceof \Zend\XmlRpc\Fault - || $response->isFault() - ) { - $fault = $response; - } else { - $responses[] = $response->getReturnValue(); - } - } catch (\Exception $e) { - $fault = $this->server->fault($e); - } - } - - if ($fault) { - $responses[] = array( - 'faultCode' => $fault->getCode(), - 'faultString' => $fault->getMessage() - ); - } - } - - return $responses; - } -} diff --git a/library/Zend/XmlRpc/Value/AbstractCollection.php b/library/Zend/XmlRpc/Value/AbstractCollection.php deleted file mode 100755 index ed4f8193f..000000000 --- a/library/Zend/XmlRpc/Value/AbstractCollection.php +++ /dev/null @@ -1,48 +0,0 @@ - $value) { - // If the elements of the given array are not Zend\XmlRpc\Value objects, - // we need to convert them as such (using auto-detection from PHP value) - if (!$value instanceof parent) { - $value = static::getXmlRpcValue($value, self::AUTO_DETECT_TYPE); - } - $this->value[$key] = $value; - } - } - - - /** - * Return the value of this object, convert the XML-RPC native collection values into a PHP array - * - * @return array - */ - public function getValue() - { - $values = (array) $this->value; - foreach ($values as $key => $value) { - $values[$key] = $value->getValue(); - } - return $values; - } -} diff --git a/library/Zend/XmlRpc/Value/AbstractScalar.php b/library/Zend/XmlRpc/Value/AbstractScalar.php deleted file mode 100755 index 3e7b8eacb..000000000 --- a/library/Zend/XmlRpc/Value/AbstractScalar.php +++ /dev/null @@ -1,30 +0,0 @@ -getGenerator(); - - $generator->openElement('value') - ->openElement($this->type, $this->value) - ->closeElement($this->type) - ->closeElement('value'); - } -} diff --git a/library/Zend/XmlRpc/Value/ArrayValue.php b/library/Zend/XmlRpc/Value/ArrayValue.php deleted file mode 100755 index 99d77437b..000000000 --- a/library/Zend/XmlRpc/Value/ArrayValue.php +++ /dev/null @@ -1,47 +0,0 @@ -type = self::XMLRPC_TYPE_ARRAY; - parent::__construct($value); - } - - - /** - * Generate the XML code that represent an array native MXL-RPC value - * - * @return void - */ - protected function _generateXml() - { - $generator = $this->getGenerator(); - $generator->openElement('value') - ->openElement('array') - ->openElement('data'); - - if (is_array($this->value)) { - foreach ($this->value as $val) { - $val->generateXml(); - } - } - $generator->closeElement('data') - ->closeElement('array') - ->closeElement('value'); - } -} diff --git a/library/Zend/XmlRpc/Value/Base64.php b/library/Zend/XmlRpc/Value/Base64.php deleted file mode 100755 index 9ba44acea..000000000 --- a/library/Zend/XmlRpc/Value/Base64.php +++ /dev/null @@ -1,42 +0,0 @@ -type = self::XMLRPC_TYPE_BASE64; - - $value = (string) $value; // Make sure this value is string - if (!$alreadyEncoded) { - $value = base64_encode($value); // We encode it in base64 - } - $this->value = $value; - } - - /** - * Return the value of this object, convert the XML-RPC native base64 value into a PHP string - * We return this value decoded (a normal string) - * - * @return string - */ - public function getValue() - { - return base64_decode($this->value); - } -} diff --git a/library/Zend/XmlRpc/Value/BigInteger.php b/library/Zend/XmlRpc/Value/BigInteger.php deleted file mode 100755 index e85ef9537..000000000 --- a/library/Zend/XmlRpc/Value/BigInteger.php +++ /dev/null @@ -1,34 +0,0 @@ -value = BigIntegerMath::factory()->init($value, 10); - $this->type = self::XMLRPC_TYPE_I8; - } - - /** - * Return bigint value object - * - * @return string - */ - public function getValue() - { - return $this->value; - } -} diff --git a/library/Zend/XmlRpc/Value/Boolean.php b/library/Zend/XmlRpc/Value/Boolean.php deleted file mode 100755 index 5ec6b7932..000000000 --- a/library/Zend/XmlRpc/Value/Boolean.php +++ /dev/null @@ -1,37 +0,0 @@ -type = self::XMLRPC_TYPE_BOOLEAN; - // Make sure the value is boolean and then convert it into an integer - // The double conversion is because a bug in the ZendOptimizer in PHP version 5.0.4 - $this->value = (int)(bool) $value; - } - - /** - * Return the value of this object, convert the XML-RPC native boolean value into a PHP boolean - * - * @return bool - */ - public function getValue() - { - return (bool) $this->value; - } -} diff --git a/library/Zend/XmlRpc/Value/DateTime.php b/library/Zend/XmlRpc/Value/DateTime.php deleted file mode 100755 index 9ec7253e6..000000000 --- a/library/Zend/XmlRpc/Value/DateTime.php +++ /dev/null @@ -1,67 +0,0 @@ -type = self::XMLRPC_TYPE_DATETIME; - - if ($value instanceof \DateTime) { - $this->value = $value->format($this->phpFormatString); - } elseif (is_numeric($value)) { // The value is numeric, we make sure it is an integer - $this->value = date($this->phpFormatString, (int) $value); - } else { - try { - $dateTime = new \DateTime($value); - } catch (\Exception $e) { - throw new Exception\ValueException($e->getMessage(), $e->getCode(), $e); - } - - $this->value = $dateTime->format($this->phpFormatString); // Convert the DateTime to iso8601 format - } - } - - /** - * Return the value of this object as iso8601 dateTime value - * - * @return int As a Unix timestamp - */ - public function getValue() - { - return $this->value; - } -} diff --git a/library/Zend/XmlRpc/Value/Double.php b/library/Zend/XmlRpc/Value/Double.php deleted file mode 100755 index 722012000..000000000 --- a/library/Zend/XmlRpc/Value/Double.php +++ /dev/null @@ -1,36 +0,0 @@ -type = self::XMLRPC_TYPE_DOUBLE; - $precision = (int) ini_get('precision'); - $formatString = '%1.' . $precision . 'F'; - $this->value = rtrim(sprintf($formatString, (float) $value), '0'); - } - - /** - * Return the value of this object, convert the XML-RPC native double value into a PHP float - * - * @return float - */ - public function getValue() - { - return (float) $this->value; - } -} diff --git a/library/Zend/XmlRpc/Value/Integer.php b/library/Zend/XmlRpc/Value/Integer.php deleted file mode 100755 index 40d938664..000000000 --- a/library/Zend/XmlRpc/Value/Integer.php +++ /dev/null @@ -1,41 +0,0 @@ - PHP_INT_MAX) { - throw new Exception\ValueException('Overlong integer given'); - } - - $this->type = self::XMLRPC_TYPE_INTEGER; - $this->value = (int) $value; // Make sure this value is integer - } - - /** - * Return the value of this object, convert the XML-RPC native integer value into a PHP integer - * - * @return int - */ - public function getValue() - { - return $this->value; - } -} diff --git a/library/Zend/XmlRpc/Value/Nil.php b/library/Zend/XmlRpc/Value/Nil.php deleted file mode 100755 index 49f3c7511..000000000 --- a/library/Zend/XmlRpc/Value/Nil.php +++ /dev/null @@ -1,33 +0,0 @@ -type = self::XMLRPC_TYPE_NIL; - $this->value = null; - } - - /** - * Return the value of this object, convert the XML-RPC native nill value into a PHP NULL - * - * @return null - */ - public function getValue() - { - return null; - } -} diff --git a/library/Zend/XmlRpc/Value/String.php b/library/Zend/XmlRpc/Value/String.php deleted file mode 100755 index 66fa441b0..000000000 --- a/library/Zend/XmlRpc/Value/String.php +++ /dev/null @@ -1,36 +0,0 @@ -type = self::XMLRPC_TYPE_STRING; - - // Make sure this value is string and all XML characters are encoded - $this->value = (string) $value; - } - - /** - * Return the value of this object, convert the XML-RPC native string value into a PHP string - * - * @return string - */ - public function getValue() - { - return (string) $this->value; - } -} diff --git a/library/Zend/XmlRpc/Value/Struct.php b/library/Zend/XmlRpc/Value/Struct.php deleted file mode 100755 index 99d55bb84..000000000 --- a/library/Zend/XmlRpc/Value/Struct.php +++ /dev/null @@ -1,49 +0,0 @@ -type = self::XMLRPC_TYPE_STRUCT; - parent::__construct($value); - } - - - /** - * Generate the XML code that represent struct native MXL-RPC value - * - * @return void - */ - protected function _generateXML() - { - $generator = $this->getGenerator(); - $generator->openElement('value') - ->openElement('struct'); - - if (is_array($this->value)) { - foreach ($this->value as $name => $val) { - $generator->openElement('member') - ->openElement('name', $name) - ->closeElement('name'); - $val->generateXml(); - $generator->closeElement('member'); - } - } - $generator->closeElement('struct') - ->closeElement('value'); - } -} diff --git a/library/Zend/XmlRpc/composer.json b/library/Zend/XmlRpc/composer.json deleted file mode 100755 index 1520a41e4..000000000 --- a/library/Zend/XmlRpc/composer.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "zendframework/zend-xmlrpc", - "description": " ", - "license": "BSD-3-Clause", - "keywords": [ - "zf2", - "xmlrpc" - ], - "homepage": "https://github.com/zendframework/zf2", - "autoload": { - "psr-0": { - "Zend\\XmlRpc\\": "" - } - }, - "target-dir": "Zend/XmlRpc", - "require": { - "php": ">=5.3.23", - "zendframework/zend-http": "self.version", - "zendframework/zend-math": "self.version", - "zendframework/zend-server": "self.version", - "zendframework/zend-stdlib": "self.version", - "zendframework/zendxml": "1.*" - }, - "extra": { - "branch-alias": { - "dev-master": "2.3-dev", - "dev-develop": "2.4-dev" - } - } -} diff --git a/library/ajax/avatar.php b/library/ajax/avatar.php index ef61deacf..08ae4a057 100644 --- a/library/ajax/avatar.php +++ b/library/ajax/avatar.php @@ -1,35 +1,45 @@ request['mode']; -$user_id = (int) $this->request['user_id']; - -if (!$user_id OR !$u_data = get_userdata($user_id)) -{ - $this->ajax_die('Invalid user_id'); +if (!defined('IN_AJAX')) { + die(basename(__FILE__)); } -if (!IS_ADMIN && $user_id != $user->id) -{ - $this->ajax_die($lang['NOT_ADMIN']); +global $lang, $user; + +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); } -switch ($mode) -{ - case 'delete': - delete_avatar($user_id, $u_data['avatar_ext_id']); - $new_ext_id = 0; - $response = ''. $user_id .''; - break; - default: - $this->ajax_die('Invalid mode'); +$user_id = (int)$this->request['user_id']; +if (!$user_id or !$u_data = get_userdata($user_id)) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); } -DB()->query("UPDATE ". BB_USERS ." SET avatar_ext_id = $new_ext_id WHERE user_id = $user_id LIMIT 1"); +if (!IS_ADMIN && $user_id != $user->id) { + $this->ajax_die($lang['NOT_AUTHORISED']); +} -cache_rm_user_sessions($user_id); +$new_ext_id = 0; +$response = ''; -$this->response['avatar_html'] = $response; \ No newline at end of file +switch ($mode) { + case 'delete': + delete_avatar($user_id, $u_data['avatar_ext_id']); + $response = get_avatar($user_id, $new_ext_id); + break; + default: + $this->ajax_die('Invalid mode: ' . $mode); +} + +DB()->query("UPDATE " . BB_USERS . " SET avatar_ext_id = $new_ext_id WHERE user_id = $user_id LIMIT 1"); + +\TorrentPier\Sessions::cache_rm_user_sessions($user_id); + +$this->response['avatar_html'] = $response; diff --git a/library/ajax/callseed.php b/library/ajax/callseed.php new file mode 100644 index 000000000..9ef54a72d --- /dev/null +++ b/library/ajax/callseed.php @@ -0,0 +1,93 @@ +get('callseed')) { + $this->ajax_die($lang['MODULE_OFF']); +} + +if (!$topic_id = (int)$this->request['topic_id']) { + $this->ajax_die($lang['INVALID_TOPIC_ID']); +} + +if (!$t_data = topic_info($topic_id)) { + $this->ajax_die($lang['INVALID_TOPIC_ID_DB']); +} + +$forum_id = $t_data['forum_id']; + +if ($t_data['seeders'] >= 3) { + $this->ajax_die(sprintf($lang['CALLSEED_HAVE_SEED'], $t_data['seeders'])); +} elseif ($t_data['call_seed_time'] >= (TIMENOW - 86400)) { + $time_left = delta_time($t_data['call_seed_time'] + 86400, TIMENOW, 'days'); + $this->ajax_die(sprintf($lang['CALLSEED_MSG_SPAM'], $time_left)); +} elseif (isset(config()->get('tor_no_tor_act')[$t_data['tor_status']])) { + $this->ajax_die($lang['NOT_AVAILABLE']); +} + +$banned_users = ($get_banned_users = get_banned_users()) ? (', ' . implode(', ', $get_banned_users)) : ''; + +$user_list = DB()->fetch_rowset(" + SELECT DISTINCT dl.user_id, u.user_opt, tr.user_id as active_dl + FROM " . BB_BT_DLSTATUS . " dl + LEFT JOIN " . BB_USERS . " u ON(u.user_id = dl.user_id) + LEFT JOIN " . BB_BT_TRACKER . " tr ON(tr.user_id = dl.user_id) + WHERE dl.topic_id = $topic_id + AND dl.user_status IN (" . DL_STATUS_COMPLETE . ", " . DL_STATUS_DOWN . ") + AND dl.user_id NOT IN ({$userdata['user_id']}, " . EXCLUDED_USERS . $banned_users . ") + AND u.user_active = 1 + GROUP BY dl.user_id +"); + +$subject = sprintf($lang['CALLSEED_SUBJECT'], $t_data['topic_title']); +$message = sprintf($lang['CALLSEED_TEXT'], make_url(TOPIC_URL . $topic_id), $t_data['topic_title'], make_url(DL_URL . $t_data['attach_id'])); + +if ($user_list) { + foreach ($user_list as $row) { + if (!empty($row['active_dl'])) { + continue; + } + + if (bf($row['user_opt'], 'user_opt', 'user_callseed')) { + send_pm($row['user_id'], $subject, $message, BOT_UID); + } + } +} else { + send_pm($t_data['poster_id'], $subject, $message, BOT_UID); +} + +DB()->query("UPDATE " . BB_BT_TORRENTS . " SET call_seed_time = " . TIMENOW . " WHERE topic_id = $topic_id LIMIT 1"); + +function topic_info($topic_id) +{ + global $lang; + + $sql = " + SELECT + tor.poster_id, tor.forum_id, tor.attach_id, tor.call_seed_time, tor.tor_status, + t.topic_title, sn.seeders + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_TOPICS . " t USING(topic_id) + LEFT JOIN " . BB_BT_TRACKER_SNAP . " sn USING(topic_id) + WHERE tor.topic_id = $topic_id + "; + + if (!$torrent = DB()->fetch_row($sql)) { + bb_die($lang['TOPIC_POST_NOT_EXIST'], 404); + } + + return $torrent; +} + +$this->response['response'] = $lang['CALLSEED_MSG_OK']; diff --git a/library/ajax/change_tor_status.php b/library/ajax/change_tor_status.php index fe7698c1c..ae534774c 100644 --- a/library/ajax/change_tor_status.php +++ b/library/ajax/change_tor_status.php @@ -1,106 +1,139 @@ request['attach_id'])) $this->ajax_die($lang['EMPTY_ATTACH_ID']); +if (!$attach_id = (int)$this->request['attach_id']) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); +} -$attach_id = (int) $this->request['attach_id']; -$mode = (string) $this->request['mode']; +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} -if ($bb_cfg['tor_comment']) -{ - $comment = (string) $this->request['comment']; +$comment = false; +if (config()->get('tor_comment')) { + $comment = (string)$this->request['comment']; } $tor = DB()->fetch_row(" SELECT tor.poster_id, tor.forum_id, tor.topic_id, tor.tor_status, tor.checked_time, tor.checked_user_id, f.cat_id, t.topic_title - FROM ". BB_BT_TORRENTS ." tor - INNER JOIN ". BB_FORUMS ." f ON(f.forum_id = tor.forum_id) - INNER JOIN ". BB_TOPICS ." t ON(t.topic_id = tor.topic_id) + FROM " . BB_BT_TORRENTS . " tor + INNER JOIN " . BB_FORUMS . " f ON(f.forum_id = tor.forum_id) + INNER JOIN " . BB_TOPICS . " t ON(t.topic_id = tor.topic_id) WHERE tor.attach_id = $attach_id LIMIT 1 "); -if (!$tor) $this->ajax_die($lang['TORRENT_FAILED']); - -switch ($mode) -{ - case 'status': - $new_status = (int) $this->request['status']; - - // Валидность статуса - if (!isset($lang['TOR_STATUS_NAME'][$new_status])) $this->ajax_die($lang['TOR_STATUS_FAILED']); - if (!isset($this->request['status'])) $this->ajax_die($lang['TOR_DONT_CHANGE']); - if (!IS_AM) $this->ajax_die($lang['NOT_MODERATOR']); - - // Тот же статус - if ($tor['tor_status'] == $new_status) - { - $this->ajax_die($lang['TOR_STATUS_DUB']); - } - - // Запрет на изменение/присвоение CH-статуса модератором - if ($new_status == TOR_CLOSED_CPHOLD && !IS_ADMIN) - { - $this->ajax_die($lang['TOR_DONT_CHANGE']); - } - - // Права на изменение статуса - if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) - { - if (!IS_ADMIN) $this->verify_mod_rights($tor['forum_id']); - DB()->query("UPDATE ". BB_TOPICS ." SET topic_status = ". TOPIC_UNLOCKED ." WHERE topic_id = {$tor['topic_id']} LIMIT 1"); - } - else - { - $this->verify_mod_rights($tor['forum_id']); - } - - // Подтверждение изменения статуса, выставленного другим модератором - if ($tor['tor_status'] != TOR_NOT_APPROVED && $tor['checked_user_id'] != $userdata['user_id'] && $tor['checked_time'] + 2*3600 > TIMENOW) - { - if (empty($this->request['confirmed'])) - { - $msg = $lang['TOR_STATUS_OF'] ." {$lang['TOR_STATUS_NAME'][$tor['tor_status']]}\n\n"; - $msg .= ($username = get_username($tor['checked_user_id'])) ? $lang['TOR_STATUS_CHANGED'] . html_entity_decode($username) .", ". delta_time($tor['checked_time']) . $lang['TOR_BACK'] ."\n\n" : ""; - $msg .= $lang['PROCEED'] .'?'; - $this->prompt_for_confirm($msg); - } - } - - change_tor_status($attach_id, $new_status); - - $this->response['status'] = $bb_cfg['tor_icons'][$new_status] .' '. $lang['TOR_STATUS_NAME'][$new_status]. ' · '. profile_url($userdata) .' · '. delta_time(TIMENOW) . $lang['TOR_BACK']. ''; - - if ($bb_cfg['tor_comment'] && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, $bb_cfg['tor_reply']))) - { - if ($tor['poster_id'] > 0) - { - $subject = sprintf($lang['TOR_MOD_TITLE'], $tor['topic_title']); - $message = sprintf($lang['TOR_MOD_MSG'], get_username($tor['poster_id']), make_url(TOPIC_URL . $tor['topic_id']), $bb_cfg['tor_icons'][$new_status] .' '.$lang['TOR_STATUS_NAME'][$new_status]); - - if ($comment && $comment != $lang['COMMENT']) $message .= "\n\n[b]". $lang['COMMENT'] .'[/b]: '. $comment; - - send_pm($tor['poster_id'], $subject, $message, $userdata['user_id']); - cache_rm_user_sessions($tor['poster_id']); - } - } - break; - - case 'status_reply': - if (!$bb_cfg['tor_comment']) $this->ajax_die($lang['MODULE_OFF']); - - $subject = sprintf($lang['TOR_AUTH_TITLE'], $tor['topic_title']); - $message = sprintf($lang['TOR_AUTH_MSG'], get_username($tor['checked_user_id']), make_url(TOPIC_URL . $tor['topic_id']), $tor['topic_title']); - - if ($comment && $comment != $lang['COMMENT']) $message .= "\n\n[b]". $lang['COMMENT'] .'[/b]: '. $comment; - - send_pm($tor['checked_user_id'], $subject, $message, $userdata['user_id']); - cache_rm_user_sessions($tor['checked_user_id']); - break; +if (!$tor) { + $this->ajax_die($lang['TORRENT_FAILED']); } -$this->response['attach_id'] = $attach_id; \ No newline at end of file +switch ($mode) { + case 'status': + $new_status = (int)$this->request['status']; + + // Check status validity + if (!isset($lang['TOR_STATUS_NAME'][$new_status])) { + $this->ajax_die($lang['TOR_STATUS_FAILED']); + } + if (!isset($this->request['status'])) { + $this->ajax_die($lang['TOR_DONT_CHANGE']); + } + if (!IS_AM) { + $this->ajax_die($lang['NOT_MODERATOR']); + } + + // Error if same status + if ($tor['tor_status'] == $new_status) { + $this->ajax_die($lang['TOR_STATUS_DUB']); + } + + // Prohibition on changing/assigning CH-status by moderator + if ($new_status == TOR_CLOSED_CPHOLD && !IS_ADMIN) { + $this->ajax_die($lang['TOR_DONT_CHANGE']); + } + + // Check rights to change status + if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) { + if (!IS_ADMIN) { + $this->verify_mod_rights($tor['forum_id']); + } + DB()->query("UPDATE " . BB_TOPICS . " SET topic_status = " . TOPIC_UNLOCKED . " WHERE topic_id = {$tor['topic_id']} LIMIT 1"); + } else { + $this->verify_mod_rights($tor['forum_id']); + } + + // Confirmation of status change set by another moderator + if ($tor['tor_status'] != TOR_NOT_APPROVED && $tor['checked_user_id'] != $userdata['user_id'] && $tor['checked_time'] + 2 * 3600 > TIMENOW) { + if (empty($this->request['confirmed'])) { + $msg = $lang['TOR_STATUS_OF'] . " {$lang['TOR_STATUS_NAME'][$tor['tor_status']]}\n\n"; + $msg .= ($username = get_username($tor['checked_user_id'])) ? $lang['TOR_STATUS_CHANGED'] . html_entity_decode($username) . ", " . delta_time($tor['checked_time']) . $lang['TOR_BACK'] . "\n\n" : ""; + $msg .= $lang['PROCEED'] . '?'; + $this->prompt_for_confirm($msg); + } + } + + \TorrentPier\Legacy\Torrent::change_tor_status($attach_id, $new_status); + + // Log action + $log_msg = sprintf($lang['TOR_STATUS_LOG_ACTION'], config()->get('tor_icons')[$new_status] . ' ' . $lang['TOR_STATUS_NAME'][$new_status] . '', config()->get('tor_icons')[$tor['tor_status']] . ' ' . $lang['TOR_STATUS_NAME'][$tor['tor_status']] . ''); + if ($comment && $comment != $lang['COMMENT']) { + $log_msg .= "
    {$lang['COMMENT']}: $comment."; + } + $log_action->mod('mod_topic_change_tor_status', [ + 'forum_id' => $tor['forum_id'], + 'topic_id' => $tor['topic_id'], + 'topic_title' => $tor['topic_title'], + 'log_msg' => $log_msg . '
    -------------', + ]); + + $this->response['status'] = config()->get('tor_icons')[$new_status] . ' ' . $lang['TOR_STATUS_NAME'][$new_status] . ' · ' . profile_url($userdata) . ' · ' . delta_time(TIMENOW) . $lang['TOR_BACK'] . ''; + + if (config()->get('tor_comment') && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, config()->get('tor_reply')))) { + if ($tor['poster_id'] > 0) { + $subject = sprintf($lang['TOR_MOD_TITLE'], $tor['topic_title']); + $message = sprintf($lang['TOR_MOD_MSG'], get_username($tor['poster_id']), make_url(TOPIC_URL . $tor['topic_id']), config()->get('tor_icons')[$new_status] . ' ' . $lang['TOR_STATUS_NAME'][$new_status]); + + if ($comment && $comment != $lang['COMMENT']) { + $message .= "\n\n[b]" . $lang['COMMENT'] . '[/b]: ' . $comment; + } + + send_pm($tor['poster_id'], $subject, $message, $userdata['user_id']); + \TorrentPier\Sessions::cache_rm_user_sessions($tor['poster_id']); + } + } + break; + + case 'status_reply': + if (!config()->get('tor_comment')) { + $this->ajax_die($lang['MODULE_OFF']); + } + + $subject = sprintf($lang['TOR_AUTH_TITLE'], $tor['topic_title']); + $message = sprintf($lang['TOR_AUTH_MSG'], get_username($tor['checked_user_id']), make_url(TOPIC_URL . $tor['topic_id']), $tor['topic_title']); + + if ($comment && $comment != $lang['COMMENT']) { + $message .= "\n\n[b]" . $lang['COMMENT'] . '[/b]: ' . $comment; + } + + send_pm($tor['checked_user_id'], $subject, $message, $userdata['user_id']); + \TorrentPier\Sessions::cache_rm_user_sessions($tor['checked_user_id']); + break; + + default: + $this->ajax_die('Invalid mode: ' . $mode); +} + +$this->response['attach_id'] = $attach_id; diff --git a/library/ajax/change_torrent.php b/library/ajax/change_torrent.php index 6d1445a66..dbcef89c8 100644 --- a/library/ajax/change_torrent.php +++ b/library/ajax/change_torrent.php @@ -1,104 +1,97 @@ request['attach_id'])) -{ - $this->ajax_die($lang['EMPTY_ATTACH_ID']); +if (!defined('IN_AJAX')) { + die(basename(__FILE__)); } -if (!isset($this->request['type'])) -{ - $this->ajax_die('type'); + +global $userdata, $lang, $log_action; + +if (!isset($this->request['attach_id'])) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); } -$attach_id = (int) $this->request['attach_id']; -$type = (string) $this->request['type']; - -$torrent = DB()->fetch_row(" - SELECT - a.post_id, d.physical_filename, d.extension, d.tracker_status, - t.topic_first_post_id, - p.poster_id, p.topic_id, p.forum_id, - f.allow_reg_tracker - FROM - ". BB_ATTACHMENTS ." a, - ". BB_ATTACHMENTS_DESC ." d, - ". BB_POSTS ." p, - ". BB_TOPICS ." t, - ". BB_FORUMS ." f - WHERE - a.attach_id = $attach_id - AND d.attach_id = $attach_id - AND p.post_id = a.post_id - AND t.topic_id = p.topic_id - AND f.forum_id = p.forum_id - LIMIT 1 - "); - -if (!$torrent) $this->ajax_die($lang['INVALID_ATTACH_ID']); - -if ($torrent['poster_id'] == $userdata['user_id'] && !IS_AM) -{ - if ($type == 'del_torrent' || $type == 'reg' || $type == 'unreg') - { - true; - } - else - { - $this->ajax_die($lang['ONLY_FOR_MOD']); - } +if (!isset($this->request['type'])) { + $this->ajax_die('empty type'); } -elseif (!IS_AM) -{ - $this->ajax_die($lang['ONLY_FOR_MOD']); + +$attach_id = (int)$this->request['attach_id']; +$type = (string)$this->request['type']; + +if (!$torrent = \TorrentPier\Legacy\Torrent::get_torrent_info($attach_id)) { + $this->ajax_die($lang['INVALID_ATTACH_ID']); +} + +if ($torrent['poster_id'] == $userdata['user_id'] && !IS_AM) { + if ($type == 'del_torrent' || $type == 'reg' || $type == 'unreg') { + } else { + $this->ajax_die($lang['ONLY_FOR_MOD']); + } +} elseif (!IS_AM) { + $this->ajax_die($lang['ONLY_FOR_MOD']); } $title = $url = ''; -switch ($type) -{ - case 'set_gold'; - case 'set_silver'; - case 'unset_silver_gold'; - if ($type == 'set_silver') - { - $tor_type = TOR_TYPE_SILVER; - } - elseif ($type == 'set_gold') - { - $tor_type = TOR_TYPE_GOLD; - } - else - { - $tor_type = 0; - } - change_tor_type($attach_id, $tor_type); - $title = $lang['CHANGE_TOR_TYPE']; - $url = make_url(TOPIC_URL . $torrent['topic_id']); - break; +switch ($type) { + case 'set_gold': + case 'set_silver': + case 'unset_silver_gold': + if ($type == 'set_silver') { + $tor_type = TOR_TYPE_SILVER; + $tor_type_lang = $lang['SILVER']; + } elseif ($type == 'set_gold') { + $tor_type = TOR_TYPE_GOLD; + $tor_type_lang = $lang['GOLD']; + } else { + $tor_type = TOR_TYPE_DEFAULT; + $tor_type_lang = "{$lang['UNSET_GOLD_TORRENT']} / {$lang['UNSET_SILVER_TORRENT']}"; + } - case 'reg'; - tracker_register($attach_id); - $url = (TOPIC_URL . $torrent['topic_id']); - break; + \TorrentPier\Legacy\Torrent::change_tor_type($attach_id, $tor_type); - case 'unreg'; - tracker_unregister($attach_id); - $url = (TOPIC_URL . $torrent['topic_id']); - break; + // Log action + $log_action->mod('mod_topic_change_tor_type', [ + 'forum_id' => $torrent['forum_id'], + 'topic_id' => $torrent['topic_id'], + 'topic_title' => $torrent['topic_title'], + 'log_msg' => sprintf($lang['TOR_TYPE_LOG_ACTION'], $tor_type_lang), + ]); - case 'del_torrent'; - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_TORRENT']); - delete_torrent($attach_id); - $url = make_url(TOPIC_URL . $torrent['topic_id']); - break; + $title = $lang['CHANGE_TOR_TYPE']; + $url = make_url(TOPIC_URL . $torrent['topic_id']); + break; - case 'del_torrent_move_topic'; - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); - delete_torrent($attach_id); - $url = make_url("modcp.php?t={$torrent['topic_id']}&mode=move&sid={$userdata['session_id']}"); - break; + case 'reg': + \TorrentPier\Legacy\Torrent::tracker_register($attach_id); + $url = (TOPIC_URL . $torrent['topic_id']); + break; + + case 'unreg': + \TorrentPier\Legacy\Torrent::tracker_unregister($attach_id); + $url = (TOPIC_URL . $torrent['topic_id']); + break; + + case 'del_torrent': + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DEL_TORRENT']); + } + \TorrentPier\Legacy\Torrent::delete_torrent($attach_id); + $url = make_url(TOPIC_URL . $torrent['topic_id']); + break; + + case 'del_torrent_move_topic': + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); + } + \TorrentPier\Legacy\Torrent::delete_torrent($attach_id); + $url = make_url("modcp.php?" . POST_TOPIC_URL . "={$torrent['topic_id']}&mode=move&sid={$userdata['session_id']}"); + break; } -$this->response['url'] = $url; -$this->response['title'] = $title; \ No newline at end of file +$this->response['url'] = $url; +$this->response['title'] = $title; diff --git a/library/ajax/change_user_opt.php b/library/ajax/change_user_opt.php index 5cf33d2ef..a129bfcd9 100644 --- a/library/ajax/change_user_opt.php +++ b/library/ajax/change_user_opt.php @@ -1,33 +1,38 @@ request['user_id']; -$new_opt = bb_json_decode($this->request['user_opt']); +$user_id = (int)$this->request['user_id']; +$new_opt = json_decode($this->request['user_opt'], true, 512, JSON_THROW_ON_ERROR); -if (!$user_id OR !$u_data = get_userdata($user_id)) -{ - $this->ajax_die('invalid user_id'); +if (!$user_id or !$u_data = get_userdata($user_id)) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); } -if (!is_array($new_opt)) -{ - $this->ajax_die('invalid new_opt'); +if (!is_array($new_opt)) { + $this->ajax_die('invalid new_opt'); } -foreach ($bf['user_opt'] as $opt_name => $opt_bit) -{ - if (isset($new_opt[$opt_name])) - { - setbit($u_data['user_opt'], $opt_bit, !empty($new_opt[$opt_name])); - } +foreach ($bf['user_opt'] as $opt_name => $opt_bit) { + if (isset($new_opt[$opt_name])) { + setbit($u_data['user_opt'], $opt_bit, !empty($new_opt[$opt_name])); + } } -DB()->query("UPDATE ". BB_USERS ." SET user_opt = {$u_data['user_opt']} WHERE user_id = $user_id LIMIT 1"); +DB()->query("UPDATE " . BB_USERS . " SET user_opt = {$u_data['user_opt']} WHERE user_id = $user_id LIMIT 1"); -// Удаляем данные из кеша -cache_rm_user_sessions ($user_id); +// Remove data from cache +\TorrentPier\Sessions::cache_rm_user_sessions($user_id); -$this->response['resp_html'] = $lang['SAVED']; \ No newline at end of file +$this->response['resp_html'] = $lang['SAVED']; diff --git a/library/ajax/change_user_rank.php b/library/ajax/change_user_rank.php index a6d283aa0..4057da73b 100644 --- a/library/ajax/change_user_rank.php +++ b/library/ajax/change_user_rank.php @@ -1,27 +1,38 @@ get('ranks'); -$rank_id = intval($this->request['rank_id']); - -if (!$user_id = intval($this->request['user_id']) OR !$profiledata = get_userdata($user_id)) -{ - $this->ajax_die("invalid user_id: $user_id"); +if (!$ranks = $datastore->get('ranks')) { + $datastore->update('ranks'); + $ranks = $datastore->get('ranks'); } -if ($rank_id != 0 && !isset($ranks[$rank_id])) -{ - $this->ajax_die("invalid rank_id: $rank_id"); +$rank_id = (int)$this->request['rank_id']; + +if (!$user_id = (int)$this->request['user_id'] or !$profiledata = get_userdata($user_id)) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); } -DB()->query("UPDATE ". BB_USERS ." SET user_rank = $rank_id WHERE user_id = $user_id LIMIT 1"); +if ($rank_id != 0 && !isset($ranks[$rank_id])) { + $this->ajax_die("invalid rank_id: $rank_id"); +} -cache_rm_user_sessions($user_id); +DB()->query("UPDATE " . BB_USERS . " SET user_rank = $rank_id WHERE user_id = $user_id LIMIT 1"); -$user_rank = ($rank_id) ? ''. $ranks[$rank_id]['rank_title'] .'' : ''; +\TorrentPier\Sessions::cache_rm_user_sessions($user_id); -$this->response['html'] = ($rank_id) ? $lang['AWARDED_RANK'] . " $user_rank " : $lang['SHOT_RANK']; -$this->response['rank_name'] = ($rank_id) ? $user_rank : $lang['USER']; +$user_rank = $rank_id ? '' . $ranks[$rank_id]['rank_title'] . '' : ''; + +$this->response['html'] = $rank_id ? $lang['AWARDED_RANK'] . " $user_rank " : $lang['SHOT_RANK']; +$this->response['rank_name'] = $rank_id ? $user_rank : $lang['USER']; diff --git a/library/ajax/edit_group_profile.php b/library/ajax/edit_group_profile.php index 5c0cc9e54..f66911ed1 100644 --- a/library/ajax/edit_group_profile.php +++ b/library/ajax/edit_group_profile.php @@ -1,52 +1,54 @@ request['group_id']) OR !$group_info = get_group_data($group_id)) -{ - $this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']); -} -if (!$mode = (string) $this->request['mode']) -{ - $this->ajax_die('No mode specified'); +if (!defined('IN_AJAX')) { + die(basename(__FILE__)); } -$value = $this->request['value'] = (string) (isset($this->request['value'])) ? $this->request['value'] : 0; +global $userdata, $lang; -if (!IS_ADMIN && $userdata['user_id'] != $group_info['group_moderator']) -{ - $this->ajax_die($lang['ONLY_FOR_MOD']); +if (!$group_id = (int)$this->request['group_id'] or !$group_info = \TorrentPier\Legacy\Group::get_group_data($group_id)) { + $this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']); +} +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('No mode specified'); } -switch ($mode) -{ - case 'group_name': - case 'group_signature': - case 'group_description': - $value = htmlCHR($value, false, ENT_NOQUOTES); - $this->response['new_value'] = $value; - break; +$value = $this->request['value'] = (string)(isset($this->request['value'])) ? $this->request['value'] : 0; - case 'group_type': - $this->response['new_value'] = $value; - break; +if (!IS_ADMIN && $userdata['user_id'] != $group_info['group_moderator']) { + $this->ajax_die($lang['ONLY_FOR_MOD']); +} - case 'release_group': - $this->response['new_value'] = $value; - break; +switch ($mode) { + case 'group_name': + case 'group_signature': + case 'group_description': + $value = htmlCHR($value, false, ENT_NOQUOTES); + $this->response['new_value'] = $value; + break; - case 'delete_avatar': - delete_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']); - $value = 0; - $mode = 'avatar_ext_id'; - $this->response['act'] = $value; - break; + case 'release_group': + case 'group_type': + $this->response['new_value'] = $value; + break; - default: - $this->ajax_die('Unknown mode'); + case 'delete_avatar': + delete_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']); + $value = 0; + $mode = 'avatar_ext_id'; + $this->response['remove_avatar'] = get_avatar(GROUP_AVATAR_MASK . $group_id, $value); + break; + + default: + $this->ajax_die('Unknown mode'); } $value_sql = DB()->escape($value, true); -DB()->query("UPDATE ". BB_GROUPS ." SET $mode = $value_sql WHERE group_id = $group_id LIMIT 1"); \ No newline at end of file +DB()->query("UPDATE " . BB_GROUPS . " SET $mode = $value_sql WHERE group_id = $group_id LIMIT 1"); diff --git a/library/ajax/edit_user_profile.php b/library/ajax/edit_user_profile.php index 04e11f890..8cfc342f7 100644 --- a/library/ajax/edit_user_profile.php +++ b/library/ajax/edit_user_profile.php @@ -1,168 +1,159 @@ request['user_id']) OR !$profiledata = get_userdata($user_id)) -{ - $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +if (!defined('IN_AJAX')) { + die(basename(__FILE__)); } -if (!$field = (string) $this->request['field']) -{ - $this->ajax_die('invalid profile field'); + +global $lang; + +if (!$user_id = (int)$this->request['user_id'] or !$profiledata = get_userdata($user_id)) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +} + +if (!$field = (string)$this->request['field']) { + $this->ajax_die('invalid profile field'); +} + +// Check for demo mode +if (IN_DEMO_MODE && in_array($field, ['username', 'user_email'])) { + $this->ajax_die($lang['CANT_EDIT_IN_DEMO_MODE']); } $table = BB_USERS; -$value = $this->request['value'] = (string) (isset($this->request['value'])) ? $this->request['value'] : 0; +$value = $this->request['value'] = (string)(isset($this->request['value'])) ? $this->request['value'] : 0; -switch ($field) -{ - case 'username': - require_once(INC_DIR .'functions_validate.php'); - $value = clean_username($value); - if ($err = validate_username($value)) - { - $this->ajax_die(strip_tags($err)); - } - $this->response['new_value'] = $this->request['value']; - break; +switch ($field) { + case 'username': + $value = clean_username($value); + if ($err = \TorrentPier\Validate::username($value)) { + $this->ajax_die($err); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_email': - require_once(INC_DIR .'functions_validate.php'); - $value = htmlCHR($value); - if ($err = validate_email($value)) - { - $this->ajax_die($err); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_email': + $value = htmlCHR($value); + if ($err = \TorrentPier\Validate::email($value)) { + $this->ajax_die($err); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_website': - if ($value == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $value)) - { - $this->response['new_value'] = htmlCHR($value); - } - else $this->ajax_die($lang['WEBSITE_ERROR']); - break; + case 'user_website': + if ($value == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $value)) { + $this->response['new_value'] = htmlCHR($value); + } else { + $this->ajax_die($lang['WEBSITE_ERROR']); + } + break; - case 'user_gender': - if (!$bb_cfg['gender']) $this->ajax_die($lang['MODULE_OFF']); - if (!isset($lang['GENDER_SELECT'][$value])) - { - $this->ajax_die($lang['ERROR']); - } - else $this->response['new_value'] = $lang['GENDER_SELECT'][$value]; - break; + case 'user_gender': + if (!config()->get('gender')) { + $this->ajax_die($lang['MODULE_OFF']); + } + if (!isset($lang['GENDER_SELECT'][$value])) { + $this->ajax_die($lang['ERROR']); + } + $this->response['new_value'] = $lang['GENDER_SELECT'][$value]; + break; - case 'user_birthday': - if (!$bb_cfg['birthday_enabled']) $this->ajax_die($lang['MODULE_OFF']); - $birthday_date = date_parse($value); + case 'user_birthday': + if (!config()->get('birthday_enabled')) { + $this->ajax_die($lang['MODULE_OFF']); + } + $birthday_date = date_parse($value); - if (!empty($birthday_date['year'])) - { - if (strtotime($value) >= TIMENOW) - { - $this->ajax_die($lang['WRONG_BIRTHDAY_FORMAT']); - } - elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] > $bb_cfg['birthday_max_age']) - { - $this->ajax_die(sprintf($lang['BIRTHDAY_TO_HIGH'], $bb_cfg['birthday_max_age'])); - } - elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] < $bb_cfg['birthday_min_age']) - { - $this->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], $bb_cfg['birthday_min_age'])); - } - } + if (!empty($birthday_date['year'])) { + if (strtotime($value) >= TIMENOW) { + $this->ajax_die($lang['WRONG_BIRTHDAY_FORMAT']); + } elseif (bb_date(TIMENOW, 'Y', false) - $birthday_date['year'] > config()->get('birthday_max_age')) { + $this->ajax_die(sprintf($lang['BIRTHDAY_TO_HIGH'], config()->get('birthday_max_age'))); + } elseif (bb_date(TIMENOW, 'Y', false) - $birthday_date['year'] < config()->get('birthday_min_age')) { + $this->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], config()->get('birthday_min_age'))); + } + } - $this->response['new_value'] = $this->request['value']; - break; + $this->response['new_value'] = $this->request['value']; + break; - case 'user_icq': - if ($value && !preg_match('#^\d{6,15}$#', $value)) - { - $this->ajax_die($lang['ICQ_ERROR']); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_icq': + if ($value && !preg_match('#^\d{6,15}$#', $value)) { + $this->ajax_die($lang['ICQ_ERROR']); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_skype': - if ($value && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $value)) - { - $this->ajax_die($lang['SKYPE_ERROR']); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_skype': + if ($value && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $value)) { + $this->ajax_die($lang['SKYPE_ERROR']); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_twitter': - if ($value && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $value)) - { - $this->ajax_die($lang['TWITTER_ERROR']); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_twitter': + if ($value && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $value)) { + $this->ajax_die($lang['TWITTER_ERROR']); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_from': - case 'user_occ': - case 'user_interests': - $value = htmlCHR($value); - $this->response['new_value'] = $value; - break; + case 'user_occ': + case 'user_interests': + $this->response['new_value'] = htmlCHR($value); + break; - case 'user_regdate': - case 'user_lastvisit': - $tz = TIMENOW + (3600 * $bb_cfg['board_timezone']); - if (($value = strtotime($value, $tz)) < $bb_cfg['board_startdate'] OR $value > TIMENOW) - { - $this->ajax_die($lang['INVALID_DATE'] . $this->request['value']); - } - $this->response['new_value'] = bb_date($value, 'Y-m-d H:i', false); - break; + case 'u_up_total': + case 'u_down_total': + case 'u_up_release': + case 'u_up_bonus': + if (!IS_ADMIN) { + $this->ajax_die($lang['NOT_ADMIN']); + } - case 'u_up_total': - case 'u_down_total': - case 'u_up_release': - case 'u_up_bonus': - if (!IS_ADMIN) $this->ajax_die($lang['NOT_ADMIN']); + $table = BB_BT_USERS; + $value = (int)$this->request['value']; - $table = BB_BT_USERS; - $value = (float) str_replace(',', '.', $this->request['value']); + if ($value < 0) { + $this->ajax_die($lang['WRONG_INPUT']); + } - foreach (array('KB'=>1,'MB'=>2,'GB'=>3,'TB'=>4) as $s => $m) - { - if (strpos($this->request['value'], $s) !== false) - { - $value *= pow(1024, $m); - break; - } - } - $value = sprintf('%.0f', $value); - $this->response['new_value'] = humn_size($value, null, null, ' '); + foreach (['KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8] as $s => $m) { + if (stripos($this->request['value'], $s) !== false) { + $value *= (1024 ** $m); + break; + } + } + $this->response['new_value'] = humn_size($value, space: ' '); - if (!$btu = get_bt_userdata($user_id)) - { - require(INC_DIR .'functions_torrent.php'); - generate_passkey($user_id, true); - $btu = get_bt_userdata($user_id); - } - $btu[$field] = $value; - $this->response['update_ids']['u_ratio'] = (string) get_bt_ratio($btu); - break; + $btu = get_bt_userdata($user_id); + $btu[$field] = $value; + $this->response['update_ids']['u_ratio'] = (string)get_bt_ratio($btu); + CACHE('bb_cache')->rm('btu_' . $user_id); + break; - case 'user_points': - $value = htmlCHR($value); - $value = (float) str_replace(',', '.', $this->request['value']); - $value = sprintf('%.2f', $value); - $this->response['new_value'] = $value; - break; + case 'user_points': + $value = (float)str_replace(',', '.', $this->request['value']); + $value = sprintf('%.2f', $value); + if ($value < 0.0 || strlen(strstr($value, '.', true)) > 14) { + $this->ajax_die($lang['WRONG_INPUT']); + } + $this->response['new_value'] = $value; + break; - default: - $this->ajax_die("invalid profile field: $field"); + default: + $this->ajax_die("invalid profile field: $field"); } $value_sql = DB()->escape($value, true); DB()->query("UPDATE $table SET $field = $value_sql WHERE user_id = $user_id LIMIT 1"); -cache_rm_user_sessions ($user_id); +\TorrentPier\Sessions::cache_rm_user_sessions($user_id); -$this->response['edit_id'] = $this->request['edit_id']; \ No newline at end of file +$this->response['edit_id'] = $this->request['edit_id']; diff --git a/library/ajax/ffprobe_info.php b/library/ajax/ffprobe_info.php new file mode 100644 index 000000000..c2b8e7e5c --- /dev/null +++ b/library/ajax/ffprobe_info.php @@ -0,0 +1,154 @@ +get('torr_server.enabled')) { + $this->ajax_die($lang['MODULE_OFF']); +} + +if (config()->get('torr_server.disable_for_guest') && IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); +} + +$attach_id = $this->request['attach_id'] ?? ''; +if (empty($attach_id) || !is_numeric($attach_id)) { + $this->ajax_die($lang['INVALID_ATTACH_ID']); +} + +$file_index = $this->request['file_index'] ?? ''; +if (empty($file_index) || !is_numeric($file_index)) { + $this->ajax_die("Invalid file index: $file_index"); +} + +if (!$info_hash = (string)$this->request['info_hash'] or !ctype_xdigit($info_hash)) { + $this->ajax_die("Invalid info_hash: $info_hash"); +} + +$isAudio = isset($this->request['is_audio']) && $this->request['is_audio']; + +// Get ffprobe info from TorrServer +$ffpInfo = (new \TorrentPier\TorrServerAPI())->getFfpInfo($info_hash, $file_index, $attach_id); +$ffpInfo = $ffpInfo->{$file_index}; +if (isset($ffpInfo->streams)) { + // Video codec information + $videoCodecIndex = array_search('video', array_column($ffpInfo->streams, 'codec_type')); + if (is_int($videoCodecIndex)) { + $videoCodecInfo = $ffpInfo->streams[$videoCodecIndex]; + } + // Audio codec information + $audioTracks = array_filter($ffpInfo->streams, function ($e) { + return $e->codec_type === 'audio'; + }); + // Audio tracks information + $audioDub = array_map(function ($stream) { + global $lang; + + $result = '' . sprintf($lang['AUDIO_TRACK'], (!isset($stream->index) || $stream->index === 0) ? 1 : $stream->index) . '
    '; + if (isset($stream->tags->language)) { + if (isset($stream->tags->title)) { + $result .= '' . mb_strtoupper($stream->tags->language, DEFAULT_CHARSET) . ' (' . $stream->tags->title . ')' . ''; + } else { + $result .= '' . mb_strtoupper($stream->tags->language, DEFAULT_CHARSET) . ''; + } + $result .= '
    '; + } + + if (!empty($stream->codec_name)) { + $result .= sprintf($lang['AUDIO_CODEC'], $stream->codec_long_name, mb_strtoupper($stream->codec_name, DEFAULT_CHARSET)) . '
    '; + } + if (!empty($stream->bit_rate)) { + $result .= sprintf($lang['BITRATE'], humn_bitrate((int)$stream->bit_rate)) . '
    '; + } + if (!empty($stream->sample_rate)) { + $result .= sprintf($lang['SAMPLE_RATE'], humn_sample_rate((int)$stream->sample_rate)) . '
    '; + } + if (!empty($stream->channels)) { + $result .= sprintf($lang['CHANNELS'], $stream->channels) . '
    '; + } + if (!empty($stream->channel_layout)) { + $result .= sprintf($lang['CHANNELS_LAYOUT'], $stream->channel_layout); + } + + return $result; + }, $audioTracks); + + // Generate output data + $data = [ + 'filesize' => sprintf($lang['FILESIZE'] . ': %s', humn_size($ffpInfo->format->size)), + 'resolution' => (!$isAudio && isset($videoCodecInfo)) ? sprintf($lang['RESOLUTION'], $videoCodecInfo->width . 'x' . $videoCodecInfo->height) : '', + 'video_codec' => (!$isAudio && isset($videoCodecInfo->codec_name)) ? sprintf($lang['VIDEO_CODEC'], $videoCodecInfo->codec_long_name, mb_strtoupper($videoCodecInfo->codec_name, DEFAULT_CHARSET)) : '', + 'audio_dub' => implode('
    ', $audioDub) + ]; + + // Validate output data + $result = '
    '; + if (!empty($data['resolution'])) { + $result .= $data['resolution'] . '
    '; + } + if (!empty($data['filesize'])) { + $result .= $data['filesize'] . '
    '; + } + if (!empty($data['video_codec'])) { + $result .= $data['video_codec']; + } + if (!empty($data['audio_dub'])) { + $result .= '
    ' . $data['audio_dub']; + } + + $this->response['ffprobe_data'] = $result; +} + +/** + * Bitrate to human-readable format + * + * @param int $bitrate + * @param string $space + * @return string + */ +function humn_bitrate(int $bitrate, string $space = ' '): string +{ + if ($bitrate >= 1000000) { + $unit = 'Mbps'; + $bitrate /= 1000000; + } elseif ($bitrate >= 1000) { + $unit = 'kbps'; + $bitrate /= 1000; + } else { + $unit = 'bps'; + } + + return sprintf('%d', commify($bitrate)) . $space . $unit; +} + +/** + * Sample rate to human-readable format + * + * @param int $sample_rate + * @param string $space + * @return string + */ +function humn_sample_rate(int $sample_rate, string $space = ' '): string +{ + if ($sample_rate >= 1000000) { + $unit = 'Mhz'; + } elseif ($sample_rate >= 1000) { + $unit = 'kHz'; + } else { + $unit = 'Hz'; + } + + return sprintf('%.1f', commify($sample_rate)) . $space . $unit; +} + +$this->response['file_index'] = $file_index; diff --git a/library/ajax/gen_passkey.php b/library/ajax/gen_passkey.php deleted file mode 100644 index a3d94bb08..000000000 --- a/library/ajax/gen_passkey.php +++ /dev/null @@ -1,25 +0,0 @@ -request['user_id']; - -if ($req_uid == $userdata['user_id'] || IS_ADMIN) -{ - if (empty($this->request['confirmed'])) - { - $this->prompt_for_confirm($lang['BT_GEN_PASSKEY_NEW']); - } - - if (!$passkey = generate_passkey($req_uid, IS_ADMIN)) - { - $this->ajax_die('Could not insert passkey'); - } - - tracker_rm_user($req_uid); - - $this->response['passkey'] = $passkey; -} -else $this->ajax_die($lang['NOT_AUTHORISED']); \ No newline at end of file diff --git a/library/ajax/group_membership.php b/library/ajax/group_membership.php index 78b9c3071..78c3d7e07 100644 --- a/library/ajax/group_membership.php +++ b/library/ajax/group_membership.php @@ -1,69 +1,67 @@ request['user_id']) OR !$profiledata = get_userdata($user_id)) -{ - $this->ajax_die("invalid user_id: $user_id"); +if (!$user_id = (int)$this->request['user_id'] or !$profiledata = get_userdata($user_id)) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); } -if (!$mode = (string) $this->request['mode']) -{ - $this->ajax_die('invalid mode (empty)'); +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); } -switch ($mode) -{ - case 'get_group_list': - $sql = " +switch ($mode) { + case 'get_group_list': + $sql = " SELECT ug.user_pending, g.group_id, g.group_type, g.group_name, g.group_moderator, self.user_id AS can_view - FROM ". BB_USER_GROUP ." ug - INNER JOIN ". BB_GROUPS ." g ON(g.group_id = ug.group_id AND g.group_single_user = 0) - LEFT JOIN ". BB_USER_GROUP ." self ON(self.group_id = g.group_id AND self.user_id = {$user->id} AND self.user_pending = 0) + FROM " . BB_USER_GROUP . " ug + INNER JOIN " . BB_GROUPS . " g ON(g.group_id = ug.group_id AND g.group_single_user = 0) + LEFT JOIN " . BB_USER_GROUP . " self ON(self.group_id = g.group_id AND self.user_id = {$user->id} AND self.user_pending = 0) WHERE ug.user_id = $user_id ORDER BY g.group_name "; - $html = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $class = ($row['user_pending']) ? 'med' : 'med bold'; - $class .= ($row['group_moderator'] == $user_id) ? ' colorMod' : ''; - $href = "group.php?g={$row['group_id']}"; + $html = []; + foreach (DB()->fetch_rowset($sql) as $row) { + $class = ($row['user_pending']) ? 'med' : 'med bold'; + $class .= ($row['group_moderator'] == $user_id) ? ' colorMod' : ''; + $href = GROUP_URL . $row['group_id']; - if (IS_ADMIN) - { - $href .= "&u=$user_id"; - $link = ''. htmlCHR($row['group_name']) .''; - $html[] = $link; - } - else - { - // скрытая группа и сам юзер не является ее членом - if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) - { - continue; - } - if ($row['group_moderator'] == $user->id) - { - $class .= ' selfMod'; - $href .= "&u=$user_id"; // сам юзер модератор этой группы - } - $link = ''. htmlCHR($row['group_name']) .''; - $html[] = $link; - } - } - if ($html) - { - $this->response['group_list_html'] = '
    • '. join('
    • ', $html) .'
    '; - } - else - { - $this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN']; - } - break; + if (IS_ADMIN) { + $href .= "&" . POST_USERS_URL . "=$user_id"; + $link = '' . htmlCHR($row['group_name']) . ''; + $html[] = $link; + } else { + // hidden group and the user himself is not a member of it + if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) { + continue; + } + if ($row['group_moderator'] == $user->id) { + // the user himself is the moderator of this group + $class .= ' selfMod'; + $href .= "&" . POST_USERS_URL . "=$user_id"; + } + $link = '' . htmlCHR($row['group_name']) . ''; + $html[] = $link; + } + } + if ($html) { + $this->response['group_list_html'] = '
    • ' . implode('
    • ', $html) . '
    '; + } else { + $this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN']; + } + break; - default: - $this->ajax_die("invalid mode: $mode"); -} \ No newline at end of file + default: + $this->ajax_die("invalid mode: $mode"); +} diff --git a/library/ajax/index_data.php b/library/ajax/index_data.php index 47447c854..95fdaacda 100644 --- a/library/ajax/index_data.php +++ b/library/ajax/index_data.php @@ -1,132 +1,203 @@ request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} -$mode = (string) $this->request['mode']; $html = ''; +switch ($mode) { + case 'birthday_week': + $datastore->enqueue([ + 'stats' + ]); + $stats = $datastore->get('stats'); -switch($mode) -{ - case 'birthday_week': - $stats = $datastore->get('stats'); - $datastore->enqueue(array( - 'stats', - )); + $users = []; - if ($stats['birthday_week_list']) - { - foreach($stats['birthday_week_list'] as $week) - { - $html[] = profile_url($week) .' ('. birthday_age($week['user_birthday']) .')'; - } - $html = sprintf($lang['BIRTHDAY_WEEK'], $bb_cfg['birthday_check_day'], join(', ', $html)); - } - else $html = sprintf($lang['NOBIRTHDAY_WEEK'], $bb_cfg['birthday_check_day']); - break; + if ($stats['birthday_week_list']) { + foreach ($stats['birthday_week_list'] as $week) { + $users[] = profile_url($week) . ' (' . birthday_age(date('Y-m-d', strtotime('-1 year', strtotime($week['user_birthday'])))) . ')'; + } + $html = sprintf($lang['BIRTHDAY_WEEK'], config()->get('birthday_check_day'), implode(', ', $users)); + } else { + $html = sprintf($lang['NOBIRTHDAY_WEEK'], config()->get('birthday_check_day')); + } + break; - case 'birthday_today': - $stats = $datastore->get('stats'); - $datastore->enqueue(array( - 'stats', - )); + case 'birthday_today': + $datastore->enqueue([ + 'stats' + ]); + $stats = $datastore->get('stats'); - if ($stats['birthday_today_list']) - { - foreach($stats['birthday_today_list'] as $today) - { - $html[] = profile_url($today) .' ('. birthday_age($today['user_birthday']) .')'; - } - $html = $lang['BIRTHDAY_TODAY'] . join(', ', $html); - } - else $html = $lang['NOBIRTHDAY_TODAY']; - break; + $users = []; - case 'get_forum_mods': - $forum_id = (int) $this->request['forum_id']; + if ($stats['birthday_today_list']) { + foreach ($stats['birthday_today_list'] as $today) { + $users[] = profile_url($today) . ' (' . birthday_age($today['user_birthday']) . ')'; + } + $html = $lang['BIRTHDAY_TODAY'] . implode(', ', $users); + } else { + $html = $lang['NOBIRTHDAY_TODAY']; + } + break; - $datastore->enqueue(array( - 'moderators', - )); + case 'get_forum_mods': + $forum_id = (int)$this->request['forum_id']; - $moderators = array(); - $mod = $datastore->get('moderators'); + $datastore->enqueue([ + 'moderators' + ]); - if (isset($mod['mod_users'][$forum_id])) - { - foreach ($mod['mod_users'][$forum_id] as $user_id) - { - $moderators[] = ''. $mod['name_users'][$user_id] .''; - } - } + $moderators = []; + $mod = $datastore->get('moderators'); - if (isset($mod['mod_groups'][$forum_id])) - { - foreach ($mod['mod_groups'][$forum_id] as $group_id) - { - $moderators[] = ''. $mod['name_groups'][$group_id] .''; - } - } + if (isset($mod['mod_users'][$forum_id])) { + foreach ($mod['mod_users'][$forum_id] as $user_id) { + $moderators[] = '' . $mod['name_users'][$user_id] . ''; + } + } - $html = ': '; - $html .= ($moderators) ? join(', ', $moderators) : $lang['NONE']; - unset($moderators, $mod); - $datastore->rm('moderators'); - break; + if (isset($mod['mod_groups'][$forum_id])) { + foreach ($mod['mod_groups'][$forum_id] as $group_id) { + $moderators[] = '' . $mod['name_groups'][$group_id] . ''; + } + } - case 'change_tz': - $tz = (int) $this->request['tz']; - if ($tz < -12) $tz = -12; - if ($tz > 13) $tz = 13; - if ($tz != $bb_cfg['board_timezone']) - { - // Set current user timezone - DB()->query("UPDATE ". BB_USERS ." SET user_timezone = $tz WHERE user_id = ". $userdata['user_id'] ." LIMIT 1"); - $bb_cfg['board_timezone'] = $tz; - cache_rm_user_sessions ($userdata['user_id']); - } - break; + $html = ': '; + $html .= ($moderators) ? implode(', ', $moderators) : $lang['NONE']; + unset($moderators, $mod); + $datastore->rm('moderators'); + break; - case 'get_traf_stats': - $user_id = (int) $this->request['user_id']; - $btu = get_bt_userdata($user_id); - $profiledata = get_userdata($user_id); + case 'null_ratio': + if (!config()->get('ratio_null_enabled') || !RATIO_ENABLED) { + $this->ajax_die($lang['MODULE_OFF']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['BT_NULL_RATIO_ALERT']); + } - $speed_up = ($btu['speed_up']) ? humn_size($btu['speed_up']).'/s' : '0 KB/s'; - $speed_down = ($btu['speed_down']) ? humn_size($btu['speed_down']).'/s' : '0 KB/s'; - $user_ratio = ($btu['u_down_total'] > MIN_DL_FOR_RATIO) ? ''. get_bt_ratio($btu) .'' : $lang['IT_WILL_BE_DOWN'] .' '. humn_size(MIN_DL_FOR_RATIO) .''; + $user_id = (int)$this->request['user_id']; + if (!IS_ADMIN && $user_id != $userdata['user_id']) { + $this->ajax_die($lang['NOT_AUTHORISED']); + } - $html = ' + $btu = get_bt_userdata($user_id); + $ratio_nulled = (bool)$btu['ratio_nulled']; + $user_ratio = get_bt_ratio($btu); + + if (($user_ratio === null) && !IS_ADMIN) { + $this->ajax_die($lang['BT_NULL_RATIO_NONE']); + } + if ($ratio_nulled && !IS_ADMIN) { + $this->ajax_die($lang['BT_NULL_RATIO_AGAIN']); + } + if (($user_ratio >= config()->get('ratio_to_null')) && !IS_ADMIN) { + $this->ajax_die(sprintf($lang['BT_NULL_RATIO_NOT_NEEDED'], config()->get('ratio_to_null'))); + } + + $ratio_nulled_sql = !IS_ADMIN ? ', ratio_nulled = 1' : ''; + DB()->query("UPDATE " . BB_BT_USERS . " SET u_up_total = 0, u_down_total = 0, u_up_release = 0, u_up_bonus = 0 $ratio_nulled_sql WHERE user_id = " . $user_id); + CACHE('bb_cache')->rm('btu_' . $user_id); + $this->ajax_die($lang['BT_NULL_RATIO_SUCCESS']); + break; + + case 'releaser_stats': + if (IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } + + $user_id = (int)$this->request['user_id']; + + $sql = " + SELECT COUNT(tor.poster_id) as total_releases, SUM(tor.size) as total_size, SUM(tor.complete_count) as total_complete, SUM(ad.download_count) as total_dl_count + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_USERS . " u ON(u.user_id = tor.poster_id) + LEFT JOIN " . BB_ATTACHMENTS_DESC . " ad ON(ad.attach_id = tor.attach_id) + LEFT JOIN " . BB_BT_USERS . " ut ON(ut.user_id = tor.poster_id) + WHERE u.user_id = $user_id + GROUP BY tor.poster_id + LIMIT 1 + "; + + $total_releases_size = $total_releases = $total_releases_completed = $total_releases_downloaded = 0; + if ($row = DB()->fetch_row($sql)) { + $total_releases = $row['total_releases']; + $total_releases_size = $row['total_size']; + $total_releases_downloaded = $row['total_dl_count']; + $total_releases_completed = $row['total_complete']; + } + + $html = '[ + ' . $lang['RELEASES'] . ': ' . $total_releases . ' | + ' . $lang['RELEASER_STAT_SIZE'] . ' ' . humn_size($total_releases_size) . ' | + ' . $lang['DOWNLOADED'] . ': ' . declension((int)$total_releases_downloaded, 'times') . ' ]'; + break; + + case 'get_traf_stats': + if (!RATIO_ENABLED) { + $this->ajax_die($lang['MODULE_OFF']); + } + + if (IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } + + $user_id = (int)$this->request['user_id']; + $btu = get_bt_userdata($user_id); + $profiledata = get_userdata($user_id); + + $speed_up = ($btu['speed_up']) ? humn_size($btu['speed_up']) . '/s' : '0 KB/s'; + $speed_down = ($btu['speed_down']) ? humn_size($btu['speed_down']) . '/s' : '0 KB/s'; + $user_ratio = ($btu['u_down_total'] > MIN_DL_FOR_RATIO) ? '' . get_bt_ratio($btu) . '' : $lang['IT_WILL_BE_DOWN'] . ' ' . humn_size(MIN_DL_FOR_RATIO) . ''; + + $html = ' - '. $lang['DOWNLOADED'] .' - '. $lang['UPLOADED'] .' - '. $lang['RELEASED'] .' - '. $lang['BONUS'] .''; - $html .= ($bb_cfg['seed_bonus_enabled']) ? ''. $lang['SEED_BONUS'] .'' : ''; - $html .= ' + ' . $lang['DOWNLOADED'] . ' + ' . $lang['UPLOADED'] . ' + ' . $lang['RELEASED'] . ' + ' . $lang['BONUS'] . ''; + $html .= config()->get('seed_bonus_enabled') ? '' . $lang['SEED_BONUS'] . '' : ''; + $html .= ' - '. $lang['TOTAL_TRAF'] .' - '. humn_size($btu['u_down_total']) .' - ' .humn_size($btu['u_up_total']) .' - '. humn_size($btu['u_up_release']) .' - '. humn_size($btu['u_up_bonus']) .''; - $html .= ($bb_cfg['seed_bonus_enabled']) ? ''. $profiledata['user_points'] .'' : ''; - $html .= ' + ' . $lang['TOTAL_TRAF'] . ' + ' . humn_size($btu['u_down_total']) . ' + ' . humn_size($btu['u_up_total']) . ' + ' . humn_size($btu['u_up_release']) . ' + ' . humn_size($btu['u_up_bonus']) . ''; + $html .= config()->get('seed_bonus_enabled') ? '' . $profiledata['user_points'] . '' : ''; + $html .= ' - '. $lang['MAX_SPEED'] .' - '. $lang['DL_DL_SPEED'] .': '. $speed_down .' - '. $lang['DL_UL_SPEED'] .': '. $speed_up .''; - $html .= ($bb_cfg['seed_bonus_enabled']) ? '' : ''; - $html .= ''; + ' . $lang['MAX_SPEED'] . ' + ' . $lang['DL_DL_SPEED'] . ': ' . $speed_down . ' + ' . $lang['DL_UL_SPEED'] . ': ' . $speed_up . ''; + $html .= config()->get('seed_bonus_enabled') ? '' : ''; + $html .= ''; - $this->response['user_ratio'] = ' - '. $lang['USER_RATIO'] .': - '. $user_ratio .' + $this->response['user_ratio'] = ' + ' . $lang['USER_RATIO'] . ': + ' . $user_ratio . ' '; - break; + break; + + default: + $this->ajax_die('Invalid mode: ' . $mode); } $this->response['html'] = $html; -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/manage_admin.php b/library/ajax/manage_admin.php index 74311b2ac..29ecbb3bc 100644 --- a/library/ajax/manage_admin.php +++ b/library/ajax/manage_admin.php @@ -1,115 +1,89 @@ request['mode']; - -switch ($mode) -{ - case 'clear_cache': - - foreach ($bb_cfg['cache']['engines'] as $cache_name => $cache_val) - { - if (!in_array('db_sqlite', $cache_val)) - { - CACHE($cache_name)->rm(); - } - } - - $this->response['cache_html'] = ''. $lang['ALL_CACHE_CLEARED'] .''; - - break; - - case 'clear_datastore': - - global $datastore; - - $datastore->clean(); - - $this->response['datastore_html'] = ''. $lang['DATASTORE_CLEARED'] .''; - - break; - - case 'clear_template_cache': - - global $template; - - $match = 'tpl_'; - $match_len = strlen($match); - $dir = $template->cachedir; - $res = @opendir($dir); - while (($file = readdir($res)) !== false) - { - if (substr($file, 0, $match_len) === $match) - { - @unlink($dir . $file); - } - } - closedir($res); - - $this->response['template_cache_html'] = ''. $lang['ALL_TEMPLATE_CLEARED'] .''; - - break; - - case 'indexer': - - exec("indexer --config {$bb_cfg['sphinx_config_path']} --all --rotate", $result); - - if (!is_file($bb_cfg['sphinx_config_path'].".log")) - { - file_put_contents($bb_cfg['sphinx_config_path'].".log", "####Logger from dimka3210.####".date("H:i:s", TIMENOW)."##############################\r\n\r\n\r\n\r\n", FILE_APPEND); - } - - file_put_contents($bb_cfg['sphinx_config_path'].".log", "##############################".date("H:i:s", TIMENOW)."##############################\r\n", FILE_APPEND); - - foreach ($result as $row) - { - file_put_contents($bb_cfg['sphinx_config_path'].".log", $row."\r\n", FILE_APPEND); - } - - file_put_contents($bb_cfg['sphinx_config_path'].".log", "\r\n", FILE_APPEND); - file_put_contents($bb_cfg['sphinx_config_path'].".log", "\r\n", FILE_APPEND); - - $this->response['indexer_html'] = ''. $lang['INDEXER'] .''; - - break; - - case 'update_user_level': - - require(INC_DIR .'functions_group.php'); - - update_user_level('all'); - - $this->response['update_user_level_html'] = ''. $lang['USER_LEVELS_UPDATED'] .''; - - break; - - case 'sync_topics': - - sync('topic', 'all'); - sync_all_forums(); - - $this->response['sync_topics_html'] = ''. $lang['TOPICS_DATA_SYNCHRONIZED'] .''; - - break; - - case 'sync_user_posts': - - sync('user_posts', 'all'); - - $this->response['sync_user_posts_html'] = ''. $lang['USER_POSTS_COUNT_SYNCHRONIZED'] .''; - - break; - - case 'unlock_cron': - - cron_enable_board(); - - $this->response['unlock_cron_html'] = ''. $lang['ADMIN_UNLOCKED'] .''; - - break; +if (!defined('IN_AJAX')) { + die(basename(__FILE__)); } -$this->response['mode'] = $mode; \ No newline at end of file +global $userdata, $lang; + +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} + +switch ($mode) { + case 'clear_cache': + foreach (config()->get('cache.engines') as $cache_name => $cache_val) { + CACHE($cache_name)->rm(); + } + + $this->response['cache_html'] = '' . $lang['ALL_CACHE_CLEARED'] . ''; + break; + case 'clear_datastore': + global $datastore; + + $datastore->clean(); + + $this->response['datastore_html'] = '' . $lang['DATASTORE_CLEARED'] . ''; + break; + case 'clear_template_cache': + global $template; + + $match = XS_TPL_PREFIX; + $dir = $template->cachedir; + $res = @opendir($dir); + while (($file = readdir($res)) !== false) { + if (str_starts_with($file, $match)) { + @unlink($dir . $file); + } + } + closedir($res); + + $this->response['template_cache_html'] = '' . $lang['ALL_TEMPLATE_CLEARED'] . ''; + break; + case 'indexer': + exec("indexer --config " . config()->get('sphinx_config_path') . " --all --rotate", $result); + + if (!is_file(config()->get('sphinx_config_path') . ".log")) { + file_put_contents(config()->get('sphinx_config_path') . ".log", "##############################" . date("H:i:s", TIMENOW) . "##############################\r\n\r\n\r\n\r\n", FILE_APPEND); + } + + file_put_contents(config()->get('sphinx_config_path') . ".log", "##############################" . date("H:i:s", TIMENOW) . "##############################\r\n", FILE_APPEND); + + foreach ($result as $row) { + file_put_contents(config()->get('sphinx_config_path') . ".log", $row . "\r\n", FILE_APPEND); + } + + file_put_contents(config()->get('sphinx_config_path') . ".log", "\r\n", FILE_APPEND); + file_put_contents(config()->get('sphinx_config_path') . ".log", "\r\n", FILE_APPEND); + + $this->response['indexer_html'] = '' . $lang['INDEXER'] . ''; + break; + case 'update_user_level': + \TorrentPier\Legacy\Group::update_user_level('all'); + $this->response['update_user_level_html'] = '' . $lang['USER_LEVELS_UPDATED'] . ''; + break; + case 'sync_topics': + \TorrentPier\Legacy\Admin\Common::sync('topic', 'all'); + \TorrentPier\Legacy\Admin\Common::sync_all_forums(); + $this->response['sync_topics_html'] = '' . $lang['TOPICS_DATA_SYNCHRONIZED'] . ''; + break; + case 'sync_user_posts': + \TorrentPier\Legacy\Admin\Common::sync('user_posts', 'all'); + $this->response['sync_user_posts_html'] = '' . $lang['USER_POSTS_COUNT_SYNCHRONIZED'] . ''; + break; + case 'unlock_cron': + \TorrentPier\Helpers\CronHelper::enableBoard(); + $this->response['unlock_cron_html'] = '' . $lang['ADMIN_UNLOCKED'] . ''; + break; + default: + $this->ajax_die('Invalid mode: ' . $mode); +} + +$this->response['mode'] = $mode; diff --git a/library/ajax/manage_user.php b/library/ajax/manage_user.php index b1783e083..3925b739f 100644 --- a/library/ajax/manage_user.php +++ b/library/ajax/manage_user.php @@ -1,84 +1,97 @@ request['mode']; -$user_id = $this->request['user_id']; +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} -switch ($mode) -{ - case 'delete_profile': +if (!$user_id = (int)$this->request['user_id']) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +} - if ($userdata['user_id'] == $user_id) $this->ajax_die($lang['USER_DELETE_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['USER_DELETE_CONFIRM']); +// Check for demo mode +if (IN_DEMO_MODE) { + $this->ajax_die($lang['CANT_EDIT_IN_DEMO_MODE']); +} - if ($user_id != BOT_UID) - { - delete_user_sessions($user_id); - user_delete($user_id); +switch ($mode) { + case 'delete_profile': + if ($userdata['user_id'] == $user_id) { + $this->ajax_die($lang['USER_DELETE_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['USER_DELETE_CONFIRM']); + } - $this->response['info'] = $lang['USER_DELETED']; - } - else $this->ajax_die($lang['USER_DELETE_CSV']); + if (!in_array($user_id, explode(',', EXCLUDED_USERS))) { + \TorrentPier\Sessions::delete_user_sessions($user_id); + \TorrentPier\Legacy\Admin\Common::user_delete($user_id); - break; + $user_id = $userdata['user_id']; // Store self user_id for redirect after successful deleting + $this->response['info'] = $lang['USER_DELETED']; + } else { + $this->ajax_die($lang['USER_DELETE_CSV']); + } + break; + case 'delete_topics': + if ($userdata['user_id'] == $user_id) { + $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DELETE_USER_ALL_POSTS_CONFIRM']); + } - case 'delete_topics': + $user_topics = DB()->fetch_rowset("SELECT topic_id FROM " . BB_TOPICS . " WHERE topic_poster = $user_id", 'topic_id'); + $deleted_topics = \TorrentPier\Legacy\Admin\Common::topic_delete($user_topics); + $deleted_posts = \TorrentPier\Legacy\Admin\Common::post_delete('user', $user_id); + $this->response['info'] = $lang['USER_DELETED_POSTS']; + break; + case 'delete_message': + if ($userdata['user_id'] == $user_id) { + $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DELETE_USER_POSTS_CONFIRM']); + } - if (empty($this->request['confirmed']) && $userdata['user_id'] == $user_id) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DELETE_USER_ALL_POSTS_CONFIRM']); + \TorrentPier\Legacy\Admin\Common::post_delete('user', $user_id); + $this->response['info'] = $lang['USER_DELETED_POSTS']; + break; + case 'user_activate': + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DEACTIVATE_CONFIRM']); + } - if (IS_ADMIN) - { - $user_topics = DB()->fetch_rowset("SELECT topic_id FROM ". BB_TOPICS ." WHERE topic_poster = $user_id", 'topic_id'); - $deleted_topics = topic_delete($user_topics); - $deleted_posts = post_delete('user', $user_id); + DB()->query("UPDATE " . BB_USERS . " SET user_active = 1 WHERE user_id = " . $user_id); + $this->response['info'] = $lang['USER_ACTIVATE_ON']; + break; + case 'user_deactivate': + if ($userdata['user_id'] == $user_id) { + $this->ajax_die($lang['USER_DEACTIVATE_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['ACTIVATE_CONFIRM']); + } - $this->response['info'] = $lang['USER_DELETED_POSTS']; - } - else $this->ajax_die($lang['NOT_ADMIN']); - - break; - - case 'delete_message': - - if (empty($this->request['confirmed']) && $userdata['user_id'] == $user_id) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_CONFIRM']); - - if (IS_ADMIN) - { - post_delete('user', $user_id); - - $this->response['info'] = $lang['USER_DELETED_POSTS']; - } - else $this->ajax_die($lang['NOT_ADMIN']); - - break; - - case 'user_activate': - - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEACTIVATE_CONFIRM']); - - DB()->query("UPDATE ". BB_USERS ." SET user_active = '1' WHERE user_id = ". $user_id); - - $this->response['info'] = $lang['USER_ACTIVATE_ON']; - - break; - - case 'user_deactivate': - - if ($userdata['user_id'] == $user_id) $this->ajax_die($lang['USER_DEACTIVATE_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['ACTIVATE_CONFIRM']); - - DB()->query("UPDATE ". BB_USERS ." SET user_active = '0' WHERE user_id = ". $user_id); - delete_user_sessions($user_id); - - $this->response['info'] = $lang['USER_ACTIVATE_OFF']; - - break; + DB()->query("UPDATE " . BB_USERS . " SET user_active = 0 WHERE user_id = " . $user_id); + \TorrentPier\Sessions::delete_user_sessions($user_id); + $this->response['info'] = $lang['USER_ACTIVATE_OFF']; + break; + default: + $this->ajax_die('Invalid mode'); } $this->response['mode'] = $mode; -$this->response['url'] = html_entity_decode(make_url('/') . PROFILE_URL . $user_id); \ No newline at end of file +$this->response['url'] = html_entity_decode(make_url('/') . PROFILE_URL . $user_id); diff --git a/library/ajax/mod_action.php b/library/ajax/mod_action.php index 80153be06..a82c122a0 100644 --- a/library/ajax/mod_action.php +++ b/library/ajax/mod_action.php @@ -1,130 +1,176 @@ request['mode']; +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} -switch ($mode) -{ - case 'tor_status': - $topics = (string) $this->request['topic_ids']; - $status = (int) $this->request['status']; +switch ($mode) { + case 'tor_status': + $topics = (string)$this->request['topic_ids']; + $status = (int)$this->request['status']; - // Валидность статуса - if (!isset($lang['TOR_STATUS_NAME'][$status])) - { - $this->ajax_die($lang['STATUS_DOES_EXIST'] . $new_status); - } + // Check status validity + if (!isset($lang['TOR_STATUS_NAME'][$status])) { + $this->ajax_die($lang['TOR_STATUS_FAILED']); + } - $topic_ids = DB()->fetch_rowset("SELECT attach_id FROM ". BB_BT_TORRENTS ." WHERE topic_id IN($topics)", 'attach_id'); + $topic_ids = DB()->fetch_rowset("SELECT attach_id FROM " . BB_BT_TORRENTS . " WHERE topic_id IN($topics)", 'attach_id'); - foreach($topic_ids as $attach_id) - { - change_tor_status($attach_id, $status); - } - $this->response['status'] = $bb_cfg['tor_icons'][$status]; - $this->response['topics'] = explode(',', $topics); - break; + foreach ($topic_ids as $attach_id) { + $tor = DB()->fetch_row(" + SELECT + tor.forum_id, tor.topic_id, t.topic_title, tor.tor_status + FROM " . BB_BT_TORRENTS . " tor + INNER JOIN " . BB_TOPICS . " t ON(t.topic_id = tor.topic_id) + WHERE tor.attach_id = $attach_id LIMIT 1"); - case 'edit_topic_title': - $topic_id = (int) $this->request['topic_id']; - $topic_title = (string) $this->request['topic_title']; - $new_title = clean_title($topic_title); + if (!$tor) { + $this->ajax_die($lang['TORRENT_FAILED']); + } - if (!$topic_id) $this->ajax_die($lang['INVALID_TOPIC_ID']); - if ($new_title == '') $this->ajax_die($lang['DONT_MESSAGE_TITLE']); + \TorrentPier\Legacy\Torrent::change_tor_status($attach_id, $status); - if (!$t_data = DB()->fetch_row("SELECT forum_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id LIMIT 1")) - { - $this->ajax_die($lang['INVALID_TOPIC_ID_DB']); - } - $this->verify_mod_rights($t_data['forum_id']); + // Log action + $log_msg = sprintf($lang['TOR_STATUS_LOG_ACTION'], config()->get('tor_icons')[$status] . ' ' . $lang['TOR_STATUS_NAME'][$status] . '', config()->get('tor_icons')[$tor['tor_status']] . ' ' . $lang['TOR_STATUS_NAME'][$tor['tor_status']] . ''); + $log_action->mod('mod_topic_change_tor_status', [ + 'forum_id' => $tor['forum_id'], + 'topic_id' => $tor['topic_id'], + 'topic_title' => $tor['topic_title'], + 'log_msg' => $log_msg . '
    -------------', + ]); + } + $this->response['status'] = config()->get('tor_icons')[$status]; + $this->response['topics'] = explode(',', $topics); + break; - $topic_title_sql = DB()->escape($new_title); + case 'edit_topic_title': + $topic_id = (int)$this->request['topic_id']; + $old_title = get_topic_title($topic_id); + $new_title = clean_title((string)$this->request['topic_title']); - DB()->query("UPDATE ". BB_TOPICS ." SET topic_title = '$topic_title_sql' WHERE topic_id = $topic_id LIMIT 1"); + if (!$topic_id) { + $this->ajax_die($lang['INVALID_TOPIC_ID']); + } + if ($new_title == '') { + $this->ajax_die($lang['DONT_MESSAGE_TITLE']); + } - // Обновление кеша новостей на главной - $news_forums = array_flip(explode(',', $bb_cfg['latest_news_forum_id'])); - if (isset($news_forums[$t_data['forum_id']]) && $bb_cfg['show_latest_news']) - { - $datastore->enqueue('latest_news'); - $datastore->update('latest_news'); - } + if (!$t_data = DB()->fetch_row("SELECT forum_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id LIMIT 1")) { + $this->ajax_die($lang['INVALID_TOPIC_ID_DB']); + } + $this->verify_mod_rights($t_data['forum_id']); - $net_forums = array_flip(explode(',', $bb_cfg['network_news_forum_id'])); - if (isset($net_forums[$t_data['forum_id']]) && $bb_cfg['show_network_news']) - { - $datastore->enqueue('network_news'); - $datastore->update('network_news'); - } + $topic_title_sql = DB()->escape($new_title); - $this->response['topic_id'] = $topic_id; - $this->response['topic_title'] = $new_title; - break; + DB()->query("UPDATE " . BB_TOPICS . " SET topic_title = '$topic_title_sql' WHERE topic_id = $topic_id LIMIT 1"); - case 'profile_ip': - $user_id = (int) $this->request['user_id']; - $profiledata = get_userdata($user_id); + // Update the news cache on the index page + $news_forums = array_flip(explode(',', config()->get('latest_news_forum_id'))); + if (isset($news_forums[$t_data['forum_id']]) && config()->get('show_latest_news')) { + $datastore->enqueue([ + 'latest_news' + ]); + $datastore->update('latest_news'); + } - if (!$user_id) $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); + $net_forums = array_flip(explode(',', config()->get('network_news_forum_id'))); + if (isset($net_forums[$t_data['forum_id']]) && config()->get('show_network_news')) { + $datastore->enqueue([ + 'network_news' + ]); + $datastore->update('network_news'); + } - $reg_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM ". BB_USERS ." + // Log action + $log_action->mod('mod_topic_renamed', [ + 'forum_id' => $t_data['forum_id'], + 'topic_id' => $topic_id, + 'topic_id_new' => $topic_id, + 'topic_title' => $old_title, + 'topic_title_new' => $new_title + ]); + + $this->response['topic_id'] = $topic_id; + $this->response['topic_title'] = $new_title; + break; + + case 'profile_ip': + $user_id = (int)$this->request['user_id']; + $profiledata = get_userdata($user_id); + + if (!$user_id) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); + } + + $reg_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM " . BB_USERS . " WHERE user_reg_ip = '{$profiledata['user_reg_ip']}' - AND user_reg_ip != '' + AND user_reg_ip != 0 AND user_id != {$profiledata['user_id']} ORDER BY username ASC"); - $last_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM " .BB_USERS ." + $last_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM " . BB_USERS . " WHERE user_last_ip = '{$profiledata['user_last_ip']}' - AND user_last_ip != '' + AND user_last_ip != 0 AND user_id != {$profiledata['user_id']}"); - $link_reg_ip = $link_last_ip = ''; + $link_reg_ip = $link_last_ip = ''; - if (!empty($reg_ip)) - { - $link_reg_ip .= $lang['OTHER_IP'] .' '; - foreach ($reg_ip as $row) - { - $link_reg_ip .= profile_url($row) .' '; - } - } + if (!empty($reg_ip)) { + $link_reg_ip .= $lang['OTHER_IP'] . ' '; + foreach ($reg_ip as $row) { + $link_reg_ip .= profile_url($row) . ', '; + } + $link_reg_ip = rtrim($link_reg_ip, ', '); + } - if (!empty($last_ip)) - { - $link_last_ip .= $lang['OTHER_IP'] .' '; - foreach ($last_ip as $row) - { - $link_last_ip .= profile_url($row) .' '; - } - } + if (!empty($last_ip)) { + $link_last_ip .= $lang['OTHER_IP'] . ' '; + foreach ($last_ip as $row) { + $link_last_ip .= profile_url($row) . ', '; + } + $link_last_ip = rtrim($link_last_ip, ', '); + } - if ($profiledata['user_level'] == ADMIN && !IS_ADMIN) $reg_ip = $last_ip = $lang['HIDDEN']; - elseif ($profiledata['user_level'] == MOD && IS_MOD) $reg_ip = $last_ip = $lang['HIDDEN']; - else - { - $user_reg_ip = decode_ip($profiledata['user_reg_ip']); - $user_last_ip = decode_ip($profiledata['user_last_ip']); - $reg_ip = ''. $user_reg_ip .''; - $last_ip = ''. $user_last_ip .''; - } + if ($profiledata['user_level'] == ADMIN && !IS_ADMIN) { + $reg_ip = $last_ip = $lang['HIDDEN']; + } elseif ($profiledata['user_level'] == MOD && !IS_AM) { + $reg_ip = $last_ip = $lang['HIDDEN']; + } else { + $user_reg_ip = \TorrentPier\Helpers\IPHelper::long2ip_extended($profiledata['user_reg_ip']); + $user_last_ip = \TorrentPier\Helpers\IPHelper::long2ip_extended($profiledata['user_last_ip']); + $reg_ip = '' . $user_reg_ip . ''; + $last_ip = '' . $user_last_ip . ''; + } - $this->response['ip_list_html'] = ' + $this->response['ip_list_html'] = '
    - - - + + + - - - + + +
    '. $lang['REG_IP'] .''. $reg_ip .'
    '. $link_reg_ip .'
    ' . $lang['REG_IP'] . '' . $reg_ip . '
    ' . $link_reg_ip . '
    '. $lang['LAST_IP'] .''. $last_ip .'
    '. $link_last_ip .'
    ' . $lang['LAST_IP'] . '' . $last_ip . '
    ' . $link_last_ip . '

    '; - break; -} \ No newline at end of file + break; + + default: + $this->ajax_die('Invalid mode: ' . $mode); +} diff --git a/library/ajax/passkey.php b/library/ajax/passkey.php new file mode 100644 index 000000000..3cf156ecf --- /dev/null +++ b/library/ajax/passkey.php @@ -0,0 +1,43 @@ +request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} + +if (!$req_uid = (int)$this->request['user_id']) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +} + +if (!IS_ADMIN && $req_uid != $userdata['user_id']) { + $this->ajax_die($lang['NOT_AUTHORISED']); +} + +switch ($mode) { + case 'generate': + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['BT_GEN_PASSKEY_NEW']); + } + + if (!$passkey = \TorrentPier\Legacy\Torrent::generate_passkey($req_uid, IS_ADMIN)) { + $this->ajax_die('Could not insert passkey'); + } + + \TorrentPier\Legacy\Torrent::tracker_rm_user($req_uid); + $this->response['passkey'] = $passkey; + break; + default: + $this->ajax_die('Invalid mode: ' . $mode); +} diff --git a/library/ajax/post_mod_comment.php b/library/ajax/post_mod_comment.php index 3cc5e0f5a..cca1c8e30 100644 --- a/library/ajax/post_mod_comment.php +++ b/library/ajax/post_mod_comment.php @@ -1,60 +1,61 @@ request['post_id']; -$mc_type = (int) $this->request['mc_type']; -$mc_text = (string) $this->request['mc_text']; -if (!$mc_text = prepare_message($mc_text)) $this->ajax_die($lang['EMPTY_MESSAGE']); +$post_id = (int)$this->request['post_id']; +$mc_type = (int)$this->request['mc_type']; +$mc_text = (string)$this->request['mc_text']; +if ($mc_type != 0 && !$mc_text = prepare_message($mc_text)) { + $this->ajax_die($lang['EMPTY_MESSAGE']); +} $post = DB()->fetch_row(" SELECT p.post_id, p.poster_id - FROM ". BB_POSTS ." p + FROM " . BB_POSTS . " p WHERE p.post_id = $post_id "); -if (!$post) $this->ajax_die('not post'); +if (!$post) { + $this->ajax_die('not post'); +} -$data = array( - 'mc_comment' => ($mc_type) ? $mc_text : '', - 'mc_type' => $mc_type, - 'mc_user_id' => ($mc_type) ? $userdata['user_id'] : 0, -); +$data = [ + 'mc_comment' => ($mc_type) ? $mc_text : '', + 'mc_type' => $mc_type, + 'mc_user_id' => ($mc_type) ? $userdata['user_id'] : 0 +]; $sql_args = DB()->build_array('UPDATE', $data); -DB()->query("UPDATE ". BB_POSTS ." SET $sql_args WHERE post_id = $post_id"); +DB()->query("UPDATE " . BB_POSTS . " SET $sql_args WHERE post_id = $post_id"); -if ($mc_type && $post['poster_id'] != $userdata['user_id']) -{ - $subject = sprintf($lang['MC_COMMENT_PM_SUBJECT'], $lang['MC_COMMENT'][$mc_type]['type']); - $message = sprintf($lang['MC_COMMENT_PM_MSG'], get_username($post['poster_id']), make_url(POST_URL ."$post_id#$post_id"), $lang['MC_COMMENT'][$mc_type]['type'], $mc_text); +if ($mc_type && $post['poster_id'] != $userdata['user_id']) { + $subject = sprintf($lang['MC_COMMENT_PM_SUBJECT'], $lang['MC_COMMENT'][$mc_type]['type']); + $message = sprintf($lang['MC_COMMENT_PM_MSG'], get_username($post['poster_id']), make_url(POST_URL . "$post_id#$post_id"), $lang['MC_COMMENT'][$mc_type]['type'], $mc_text); - send_pm($post['poster_id'], $subject, $message); - cache_rm_user_sessions($post['poster_id']); + send_pm($post['poster_id'], $subject, $message); + \TorrentPier\Sessions::cache_rm_user_sessions($post['poster_id']); } -switch($mc_type) -{ - case 1: // Комментарий - $mc_class = 'success'; - break; - case 2: // Информация - $mc_class = 'info'; - break; - case 3: // Предупреждение - $mc_class = 'warning'; - break; - case 4: // Нарушение - $mc_class = 'danger'; - break; - default: - $mc_class = ''; - break; -} +$mc_class = match ($mc_type) { + 1 => 'success', + 2 => 'info', + 3 => 'warning', + 4 => 'danger', + default => '', +}; -$this->response['mc_type'] = $mc_type; -$this->response['post_id'] = $post_id; +$this->response['mc_type'] = $mc_type; +$this->response['post_id'] = $post_id; $this->response['mc_title'] = sprintf($lang['MC_COMMENT'][$mc_type]['title'], profile_url($userdata)); -$this->response['mc_text'] = bbcode2html($mc_text); -$this->response['mc_class'] = $mc_class; \ No newline at end of file +$this->response['mc_text'] = bbcode2html($mc_text); +$this->response['mc_class'] = $mc_class; diff --git a/library/ajax/posts.php b/library/ajax/posts.php index ccfe534a5..2cff05d00 100644 --- a/library/ajax/posts.php +++ b/library/ajax/posts.php @@ -1,212 +1,187 @@ request['type'])) -{ - $this->ajax_die('empty type'); +if (!defined('IN_AJAX')) { + die(basename(__FILE__)); } -if (isset($this->request['post_id'])) -{ - $post_id = (int) $this->request['post_id']; - $post = DB()->fetch_row("SELECT t.*, f.*, p.*, pt.post_text - FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f, ". BB_POSTS ." p, ". BB_POSTS_TEXT ." pt + +global $lang, $userdata; + +if (!isset($this->request['type'])) { + $this->ajax_die('empty type'); +} +if (isset($this->request['post_id'])) { + $post_id = (int)$this->request['post_id']; + $post = DB()->fetch_row("SELECT t.*, f.*, p.*, pt.post_text + FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f, " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt WHERE p.post_id = $post_id AND t.topic_id = p.topic_id AND f.forum_id = t.forum_id AND p.post_id = pt.post_id LIMIT 1"); - if(!$post) $this->ajax_die('not post'); + if (!$post) { + $this->ajax_die('not post'); + } - $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); - if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['TOPIC_LOCKED']); - } -} -elseif (isset($this->request['topic_id'])) -{ - $topic_id = (int) $this->request['topic_id']; - $post = DB()->fetch_row("SELECT t.*, f.* - FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f + $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); + if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + $this->ajax_die($lang['TOPIC_LOCKED']); + } +} elseif (isset($this->request['topic_id'])) { + $topic_id = (int)$this->request['topic_id']; + $post = DB()->fetch_row("SELECT t.*, f.* + FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f WHERE t.topic_id = $topic_id AND f.forum_id = t.forum_id LIMIT 1"); - if(!$post) $this->ajax_die('not post'); + if (!$post) { + $this->ajax_die($lang['INVALID_TOPIC_ID_DB']); + } - $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); + $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); } -if (!defined('WORD_LIST_OBTAINED')) -{ - $orig_word = array(); - $replace_word = array(); - obtain_word_list($orig_word, $replace_word); - define('WORD_LIST_OBTAINED', true); -} +switch ($this->request['type']) { + case 'delete': + if ($post['post_id'] != $post['topic_first_post_id'] && $is_auth['auth_delete'] && ($is_auth['auth_mod'] || ($userdata['user_id'] == $post['poster_id'] && $post['topic_last_post_id'] == $post['post_id'] && $post['post_time'] + 3600 * 3 > TIMENOW))) { + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['CONFIRM_DELETE']); + } + \TorrentPier\Legacy\Admin\Common::post_delete($post_id); -switch($this->request['type']) -{ - case 'delete'; - if ($post['post_id'] != $post['topic_first_post_id'] && $is_auth['auth_delete'] && ($is_auth['auth_mod'] || ($userdata['user_id'] == $post['poster_id'] && $post['topic_last_post_id'] == $post['post_id'] && $post['post_time'] + 3600*3 > TIMENOW))) - { - if (empty($this->request['confirmed'])) - { - $this->prompt_for_confirm($lang['CONFIRM_DELETE']); - } - post_delete($post_id); + // Update atom feed + update_atom('topic', (int)$this->request['topic_id']); - // Update atom feed - update_atom('topic', (int) $this->request['topic_id']); + $this->response['hide'] = true; + $this->response['post_id'] = $post_id; + } else { + $this->ajax_die(sprintf($lang['SORRY_AUTH_DELETE'], strip_tags($is_auth['auth_delete_type']))); + } + break; - $this->response['hide'] = true; - $this->response['post_id'] = $post_id; - } - else - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_DELETE'], strip_tags($is_auth['auth_delete_type']))); - } - break; + case 'reply': + if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) { + $this->ajax_die($lang['RULES_REPLY_CANNOT']); + } elseif (!$is_auth['auth_reply']) { + $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); + } - case 'reply'; - if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) - { - $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); - } - elseif(!$is_auth['auth_reply']) - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); - } + $quote_username = ($post['post_username'] != '') ? $post['post_username'] : get_username($post['poster_id']); + $message = "[quote=\"" . $quote_username . "\"][qpost=" . $post['post_id'] . "]" . $post['post_text'] . "[/quote]\r"; - $quote_username = ($post['post_username'] != '') ? $post['post_username'] : get_username($post['poster_id']); - $message = "[quote=\"". $quote_username ."\"][qpost=". $post['post_id'] ."]". $post['post_text'] ."[/quote]\r"; + // hide user passkey + $message = preg_replace('#(?<=[\?&;]' . config()->get('passkey_key') . '=)[a-zA-Z0-9]#', 'passkey', $message); + // hide sid + $message = preg_replace('#(?<=[\?&;]sid=)[a-zA-Z0-9]#', 'sid', $message); - // hide user passkey - $message = preg_replace('#(?<=\?uk=)[a-zA-Z0-9]{10}(?=&)#', 'passkey', $message); - // hide sid - $message = preg_replace('#(?<=[\?&;]sid=)[a-zA-Z0-9]{12}#', 'sid', $message); + $message = censor()->censorString($message); - if (!empty($orig_word)) - { - $message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : ''; - } + if ($post['post_id'] == $post['topic_first_post_id']) { + $message = "[quote]" . $post['topic_title'] . "[/quote]\r"; + } + if (mb_strlen($message, DEFAULT_CHARSET) > 1000) { + $this->response['redirect'] = make_url(POSTING_URL . '?mode=quote&' . POST_POST_URL . '=' . $post_id); + } - if ($post['post_id'] == $post['topic_first_post_id']) - { - $message = "[quote]". $post['topic_title'] ."[/quote]\r"; - } - if (mb_strlen($message, 'UTF-8') > 1000) - { - $this->response['redirect'] = make_url(POSTING_URL.'?mode=quote&p='. $post_id); - } + $this->response['quote'] = true; + $this->response['message'] = $message; + break; - $this->response['quote'] = true; - $this->response['message'] = $message; - break; + case 'view_message': + $message = (string)$this->request['message']; + if (!trim($message)) { + $this->ajax_die($lang['EMPTY_MESSAGE']); + } + $message = htmlCHR($message, false, ENT_NOQUOTES); - case 'view_message': - $message = (string) $this->request['message']; - if(!trim($message)) $this->ajax_die($lang['EMPTY_MESSAGE']); - $message = htmlCHR($message, false, ENT_NOQUOTES); + $this->response['message_html'] = bbcode2html($message); + $this->response['res_id'] = @$this->request['res_id']; + break; - $this->response['message_html'] = bbcode2html($message); - $this->response['res_id'] = @$this->request['res_id']; - break; + case 'edit': + case 'editor': + if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) { + $this->ajax_die($lang['POST_EDIT_CANNOT']); + } + if ($post['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) { + $this->ajax_die($lang['EDIT_OWN_POSTS']); + } + if ((mb_strlen($post['post_text'], DEFAULT_CHARSET) > 1000) || $post['post_attachment'] || ($post['topic_first_post_id'] == $post_id)) { + $this->response['redirect'] = make_url(POSTING_URL . '?mode=editpost&' . POST_POST_URL . '=' . $post_id); + } elseif ($this->request['type'] == 'editor') { + $text = (string)$this->request['text']; + $text = prepare_message($text); - case 'edit': - case 'editor': - if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) - { - $this->ajax_die($lang['POST_EDIT_CANNOT']); - } - if ($post['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['EDIT_OWN_POSTS']); - } - if ((mb_strlen($post['post_text'], 'UTF-8') > 1000) || $post['post_attachment'] || ($post['topic_first_post_id'] == $post_id)) - { - $this->response['redirect'] = make_url(POSTING_URL.'?mode=editpost&p='. $post_id); - } - elseif ($this->request['type'] == 'editor') - { - $text = (string) $this->request['text']; - $text = prepare_message($text); + if (mb_strlen($text) > 2) { + if ($text != $post['post_text']) { + if (config()->get('max_smilies')) { + $count_smilies = substr_count(bbcode2html($text), 'query("UPDATE " . BB_POSTS . " SET post_edit_time = '" . TIMENOW . "', post_edit_count = post_edit_count + 1 WHERE post_id = $post_id LIMIT 1"); + } + $s_text = str_replace('\n', "\n", $text); + $s_topic_title = str_replace('\n', "\n", $post['topic_title']); + add_search_words($post_id, stripslashes($s_text), stripslashes($s_topic_title)); + update_post_html([ + 'post_id' => $post_id, + 'post_text' => $text + ]); + } + } else { + $this->ajax_die($lang['EMPTY_MESSAGE']); + } - if (mb_strlen($text) > 2) - { - if ($text != $post['post_text']) - { - if ($bb_cfg['max_smilies']) - { - $count_smilies = substr_count(bbcode2html($text), 'query("UPDATE ". BB_POSTS ." SET post_edit_time = '". TIMENOW ."', post_edit_count = post_edit_count + 1 WHERE post_id = $post_id LIMIT 1"); - } - $s_text = str_replace('\n', "\n", $text); - $s_topic_title = str_replace('\n', "\n", $post['topic_title']); - add_search_words($post_id, stripslashes($s_text), stripslashes($s_topic_title)); - update_post_html(array( - 'post_id' => $post_id, - 'post_text' => $text, - )); - } - } - else $this->ajax_die($lang['EMPTY_MESSAGE']); + // Update atom feed + update_atom('topic', (int)$this->request['topic_id']); - // Update atom feed - update_atom('topic', (int) $this->request['topic_id']); + $this->response['html'] = bbcode2html($text); + } else { + $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); + if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + $this->ajax_die($lang['TOPIC_LOCKED']); + } elseif (!$is_auth['auth_edit']) { + $this->ajax_die(sprintf($lang['SORRY_AUTH_EDIT'], strip_tags($is_auth['auth_edit_type']))); + } - $this->response['html'] = bbcode2html($text); - } - else - { - $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); - if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['TOPIC_LOCKED']); - } - elseif (!$is_auth['auth_edit']) - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_EDIT'], strip_tags($is_auth['auth_edit_type']))); - } + $hidden_form = ''; + $hidden_form .= ''; + $hidden_form .= ''; - $hidden_form = ''; - $hidden_form .= ''; - $hidden_form .= ''; - - $this->response['text'] = ' -
    - '. $hidden_form .' + $this->response['text'] = ' + + ' . $hidden_form . '
    - - - -    - - -   - - -   -   + + + +    + + +   + + +   +  
    - +
    - - - -

    + + + +
    '; - } - $this->response['post_id'] = $post_id; - break; + } + $this->response['post_id'] = $post_id; + break; - case 'add': - if (!isset($this->request['topic_id'])) - { - $this->ajax_die('empty topic_id'); - } + case 'add': + if (!isset($this->request['topic_id'])) { + $this->ajax_die($lang['INVALID_TOPIC_ID']); + } - if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) - { - $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); - } - elseif (!$is_auth['auth_reply']) - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); - } - if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['TOPIC_LOCKED']); - } + if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) { + $this->ajax_die($lang['RULES_REPLY_CANNOT']); + } elseif (!$is_auth['auth_reply']) { + $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); + } + if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + $this->ajax_die($lang['TOPIC_LOCKED']); + } - $message = (string) $this->request['message']; - $message = prepare_message($message); + $message = (string)$this->request['message']; + $message = prepare_message($message); - // Flood control - $where_sql = (IS_GUEST) ? "p.poster_ip = '". USER_IP ."'" : "p.poster_id = {$userdata['user_id']}"; + // Flood control + $where_sql = IS_GUEST ? "p.poster_ip = '" . USER_IP . "'" : "p.poster_id = {$userdata['user_id']}"; - $sql = "SELECT MAX(p.post_time) AS last_post_time FROM ". BB_POSTS ." p WHERE $where_sql"; - if ($row = DB()->fetch_row($sql) AND $row['last_post_time']) - { - if ($userdata['user_level'] == USER) - { - if (TIMENOW - $row['last_post_time'] < $bb_cfg['flood_interval']) - { - $this->ajax_die($lang['FLOOD_ERROR']); - } - } - } + $sql = "SELECT MAX(p.post_time) AS last_post_time FROM " . BB_POSTS . " p WHERE $where_sql"; + if ($row = DB()->fetch_row($sql) and $row['last_post_time']) { + if ($userdata['user_level'] == USER) { + if ((TIMENOW - $row['last_post_time']) < config()->get('flood_interval')) { + $this->ajax_die($lang['FLOOD_ERROR']); + } + } + } - // Double Post Control - if (!empty($row['last_post_time']) && !IS_AM) - { - $sql = " + // Double Post Control + if (!empty($row['last_post_time']) && !IS_AM) { + $sql = " SELECT pt.post_text - FROM ". BB_POSTS ." p, ". BB_POSTS_TEXT ." pt + FROM " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt WHERE $where_sql - AND p.post_time = ". (int) $row['last_post_time'] ." + AND p.post_time = " . (int)$row['last_post_time'] . " AND pt.post_id = p.post_id LIMIT 1 "; - if ($row = DB()->fetch_row($sql)) - { - $last_msg = DB()->escape($row['post_text']); + if ($row = DB()->fetch_row($sql)) { + $last_msg = DB()->escape($row['post_text']); - if ($last_msg == $message) - { - $this->ajax_die($lang['DOUBLE_POST_ERROR']); - } - } - } + if ($last_msg == $message) { + $this->ajax_die($lang['DOUBLE_POST_ERROR']); + } + } + } - if ($bb_cfg['max_smilies']) - { - $count_smilies = substr_count(bbcode2html($message), 'sql_nextid(); - DB()->sql_query("INSERT INTO " . BB_POSTS_TEXT . " (post_id, post_text) VALUES ($post_id, '". DB()->escape($message) ."')"); + DB()->sql_query("INSERT INTO " . BB_POSTS . " (topic_id, forum_id, poster_id, post_time, poster_ip) VALUES ($topic_id, " . $post['forum_id'] . ", " . $userdata['user_id'] . ", '" . TIMENOW . "', '" . USER_IP . "')"); + $post_id = DB()->sql_nextid(); + DB()->sql_query("INSERT INTO " . BB_POSTS_TEXT . " (post_id, post_text) VALUES ($post_id, '" . DB()->escape($message) . "')"); - update_post_stats('reply', $post, $post['forum_id'], $topic_id, $post_id, $userdata['user_id']); + \TorrentPier\Legacy\Post::update_post_stats('reply', $post, $post['forum_id'], $topic_id, $post_id, $userdata['user_id']); - $s_message = str_replace('\n', "\n", $message); - $s_topic_title = str_replace('\n', "\n", $post['topic_title']); - add_search_words($post_id, stripslashes($s_message), stripslashes($s_topic_title)); - update_post_html(array( - 'post_id' => $post_id, - 'post_text' => $message, - )); + $s_message = str_replace('\n', "\n", $message); + $s_topic_title = str_replace('\n', "\n", $post['topic_title']); + add_search_words($post_id, stripslashes($s_message), stripslashes($s_topic_title)); + update_post_html([ + 'post_id' => $post_id, + 'post_text' => $message + ]); - if ($bb_cfg['topic_notify_enabled']) - { - $notify = !empty($this->request['notify']); - user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify); - } + if (config()->get('topic_notify_enabled')) { + $notify = !empty($this->request['notify']); + \TorrentPier\Legacy\Post::user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify); + } - // Update atom feed - update_atom('topic', (int) $this->request['topic_id']); + // Update atom feed + update_atom('topic', (int)$this->request['topic_id']); - $this->response['redirect'] = make_url(POST_URL . "$post_id#$post_id"); - break; + $this->response['redirect'] = make_url(POST_URL . "$post_id#$post_id"); + break; - default: - $this->ajax_die('empty type'); - break; -} \ No newline at end of file + default: + $this->ajax_die('empty type'); + break; +} diff --git a/library/ajax/sitemap.php b/library/ajax/sitemap.php index 45decf5f7..a201db707 100644 --- a/library/ajax/sitemap.php +++ b/library/ajax/sitemap.php @@ -1,55 +1,38 @@ request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} + +$map = new TorrentPier\Sitemap(); -$mode = (string) $this->request['mode']; -$map = new sitemap(); $html = ''; +switch ($mode) { + case 'create': + $map->createSitemap(); + if (is_file(SITEMAP_DIR . '/sitemap.xml')) { + $html .= $lang['SITEMAP_CREATED'] . ': ' . bb_date(TIMENOW, config()->get('post_date_format')) . ' ' . $lang['SITEMAP_AVAILABLE'] . ': ' . make_url('sitemap/sitemap.xml') . ''; + } else { + $html .= $lang['SITEMAP_NOT_CREATED']; + } + break; -switch ($mode) -{ - case 'create': - $map->create(); - if (@file_exists(SITEMAP_DIR. 'sitemap.xml')) - { - $html .= $lang['SITEMAP_CREATED'].': '.bb_date(TIMENOW, $bb_cfg['post_date_format']).' '.$lang['SITEMAP_AVAILABLE'].': '.make_url('sitemap.xml').''; - } else { - $html .= $lang['SITEMAP_NOT_CREATED']; - } - break; - - case 'search_update': - if (!@file_exists(SITEMAP_DIR. 'sitemap.xml')) $map->create(); - - $map_link = make_url(SITEMAP_DIR. 'sitemap.xml'); - - if (strpos($map->send_url("http://google.com/webmasters/sitemaps/ping?sitemap=", $map_link), "successfully added") !== false) { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Google: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Google: '.$lang['SITEMAP_ERROR'].' URL: http://google.com/webmasters/sitemaps/ping?sitemap='.$map_link.''; - } - - if (strpos($map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link), "OK") !== false) { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Yandex: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Yandex: '.$lang['SITEMAP_ERROR'].' URL: http://ping.blogs.yandex.ru/ping?sitemap='.$map_link.''; - } - - if ($map->send_url("http://www.bing.com/ping?sitemap=", $map_link)) { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Bing: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Bing: '.$lang['SITEMAP_ERROR'].' URL: http://www.bing.com/ping?sitemap='.$map_link.''; - } - - if (strpos($map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link), "Thanks for the ping") !== false) { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Weblogs: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
    '.$lang['SITEMAP_NOTIFY_SEARCH'].' Weblogs: '.$lang['SITEMAP_ERROR'].' URL: http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url='.$map_link.''; - } - break; + default: + $this->ajax_die("Invalid mode: $mode"); } $this->response['html'] = $html; -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/thanks.php b/library/ajax/thanks.php new file mode 100644 index 000000000..c4eb38689 --- /dev/null +++ b/library/ajax/thanks.php @@ -0,0 +1,73 @@ +get('tor_thank')) { + $this->ajax_die($lang['MODULE_OFF']); +} + +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} + +if (!$topic_id = (int)$this->request['topic_id']) { + $this->ajax_die($lang['INVALID_TOPIC_ID']); +} + +if (!$poster_id = (int)$this->request['poster_id']) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +} + +switch ($mode) { + case 'add': + if (IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } + + if ($poster_id == $userdata['user_id']) { + $this->ajax_die($lang['LIKE_OWN_POST']); + } + + if (DB()->fetch_row('SELECT topic_id FROM ' . BB_THX . " WHERE topic_id = $topic_id AND user_id = " . $userdata['user_id'])) { + $this->ajax_die($lang['LIKE_ALREADY']); + } + + $columns = 'topic_id, user_id, time'; + $values = "$topic_id, {$userdata['user_id']}, " . TIMENOW; + DB()->query('INSERT IGNORE INTO ' . BB_THX . " ($columns) VALUES ($values)"); + + // Limit voters per topic + $thanks_count = DB()->fetch_row('SELECT COUNT(*) as thx FROM ' . BB_THX . " WHERE topic_id = $topic_id")['thx']; + if ($thanks_count > (int)config()->get('tor_thank_limit_per_topic')) { + DB()->query('DELETE FROM ' . BB_THX . " WHERE topic_id = $topic_id ORDER BY time ASC LIMIT 1"); + } + break; + case 'get': + if (IS_GUEST && !config()->get('tor_thanks_list_guests')) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } + + $user_list = []; + $sql = DB()->fetch_rowset('SELECT u.username, u.user_rank, u.user_id, t.* FROM ' . BB_THX . ' t, ' . BB_USERS . " u WHERE t.topic_id = $topic_id AND t.user_id = u.user_id"); + foreach ($sql as $row) { + $user_list[] = '' . profile_url($row) . ' (' . bb_date($row['time']) . ')'; + } + + $this->response['html'] = implode(', ', $user_list) ?: $lang['NO_LIKES']; + break; + default: + $this->ajax_die('Invalid mode: ' . $mode); +} + +$this->response['mode'] = $mode; diff --git a/library/ajax/topic_tpl.php b/library/ajax/topic_tpl.php index fdc366349..24a04dab2 100644 --- a/library/ajax/topic_tpl.php +++ b/library/ajax/topic_tpl.php @@ -1,172 +1,184 @@ ajax_die('not auth'); +if (!IS_SUPER_ADMIN) { + $this->ajax_die($lang['ONLY_FOR_SUPER_ADMIN']); +} array_deep($this->request, 'trim'); -$mode = (string) $this->request['mode']; +$mode = (string)$this->request['mode']; $sql_error = false; // установка / начальная валидация значений -switch ($mode) -{ - case 'load': - case 'save': - if (!$tpl_id = (int) $this->request['tpl_id']) - { - $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); - } - if (!$tpl_data = DB()->fetch_row("SELECT * FROM ". BB_TOPIC_TPL ." WHERE tpl_id = $tpl_id LIMIT 1")) - { - $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); - } - break; +switch ($mode) { + case 'load': + case 'save': + case 'remove': + if (!$tpl_id = (int)$this->request['tpl_id']) { + $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); + } + if (!$tpl_data = DB()->fetch_row("SELECT * FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1")) { + $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); + } + break; } -switch ($mode) -{ - case 'save': - case 'new': - if (!$tpl_name = htmlCHR(str_compact($this->request['tpl_name']))) - { - $this->ajax_die('не заполнено название шаблона'); - } - $tpl_name = substr($tpl_name, 0, 60); +switch ($mode) { + case 'save': + case 'new': + if (!$tpl_name = htmlCHR(str_compact($this->request['tpl_name']))) { + $this->ajax_die('не заполнено название шаблона'); + } + $tpl_name = substr($tpl_name, 0, 60); - if (!$tpl_src_form = htmlCHR($this->request['tpl_src_form'])) - { - $this->ajax_die('не заполнен скрипт формы шаблона'); - } - if (!$tpl_src_title = htmlCHR($this->request['tpl_src_title'])) - { - $this->ajax_die('не заполнен формат названия темы'); - } - $tpl_src_title = str_compact($tpl_src_title); + if (!$tpl_src_form = htmlCHR($this->request['tpl_src_form'])) { + $this->ajax_die('не заполнен скрипт формы шаблона'); + } + if (!$tpl_src_title = htmlCHR($this->request['tpl_src_title'])) { + $this->ajax_die('не заполнен формат названия темы'); + } + $tpl_src_title = str_compact($tpl_src_title); - if (!$tpl_src_msg = htmlCHR($this->request['tpl_src_msg'])) - { - $this->ajax_die('не заполнен формат создания сообщения'); - } + if (!$tpl_src_msg = htmlCHR($this->request['tpl_src_msg'])) { + $this->ajax_die('не заполнен формат создания сообщения'); + } - $tpl_comment = htmlCHR($this->request['tpl_comment']); + $tpl_comment = htmlCHR($this->request['tpl_comment']); - preg_match('#\d+#', (string) $this->request['tpl_rules'], $m); - $tpl_rules_post_id = isset($m[0]) ? (int) $m[0] : 0; + preg_match('#\d+#', (string)$this->request['tpl_rules'], $m); + $tpl_rules_post_id = isset($m[0]) ? (int)$m[0] : 0; - $sql_args = array( - 'tpl_name' => (string) $tpl_name, - 'tpl_src_form' => (string) $tpl_src_form, - 'tpl_src_title' => (string) $tpl_src_title, - 'tpl_src_msg' => (string) $tpl_src_msg, - 'tpl_comment' => (string) $tpl_comment, - 'tpl_rules_post_id' => (int) $tpl_rules_post_id, - 'tpl_last_edit_tm' => (int) TIMENOW, - 'tpl_last_edit_by' => (int) $userdata['user_id'], - ); - break; + $sql_args = [ + 'tpl_name' => (string)$tpl_name, + 'tpl_src_form' => (string)$tpl_src_form, + 'tpl_src_title' => (string)$tpl_src_title, + 'tpl_src_msg' => (string)$tpl_src_msg, + 'tpl_comment' => (string)$tpl_comment, + 'tpl_rules_post_id' => (int)$tpl_rules_post_id, + 'tpl_last_edit_tm' => (int)TIMENOW, + 'tpl_last_edit_by' => (int)$userdata['user_id'] + ]; + break; } // выполнение -switch ($mode) -{ - // загрузка шаблона - case 'load': - $this->response['val']['tpl-name-save'] = $tpl_data['tpl_name']; - $this->response['val']['tpl-src-form'] = $tpl_data['tpl_src_form']; - $this->response['val']['tpl-src-title'] = $tpl_data['tpl_src_title']; - $this->response['val']['tpl-src-msg'] = $tpl_data['tpl_src_msg']; - $this->response['val']['tpl-comment-save'] = $tpl_data['tpl_comment']; - $this->response['val']['tpl-rules-save'] = $tpl_data['tpl_rules_post_id']; - array_deep($this->response['val'], 'html_ent_decode'); +switch ($mode) { + // загрузка шаблона + case 'load': + $this->response['val']['tpl-name-save'] = $tpl_data['tpl_name']; + $this->response['val']['tpl-src-form'] = $tpl_data['tpl_src_form']; + $this->response['val']['tpl-src-title'] = $tpl_data['tpl_src_title']; + $this->response['val']['tpl-src-msg'] = $tpl_data['tpl_src_msg']; + $this->response['val']['tpl-comment-save'] = $tpl_data['tpl_comment']; + $this->response['val']['tpl-rules-save'] = $tpl_data['tpl_rules_post_id']; + array_deep($this->response['val'], 'html_ent_decode'); - $this->response['val']['tpl-id-save'] = $tpl_id; - $this->response['val']['tpl-last-edit-tst'] = $tpl_data['tpl_last_edit_tm']; - $this->response['html']['tpl-name-old-save'] = $tpl_data['tpl_name']; - $this->response['html']['tpl-last-edit-time'] = bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'); - $this->response['html']['tpl-last-edit-by'] = get_username(intval($tpl_data['tpl_last_edit_by'])); + $this->response['val']['tpl-id-save'] = $tpl_id; + $this->response['val']['tpl-last-edit-tst'] = $tpl_data['tpl_last_edit_tm']; + $this->response['html']['tpl-name-old-save'] = $tpl_data['tpl_name']; + $this->response['html']['tpl-last-edit-time'] = bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'); + $this->response['html']['tpl-last-edit-by'] = profile_url(get_userdata((int)$tpl_data['tpl_last_edit_by'])); - $this->response['tpl_rules_href'] = POST_URL . $tpl_data['tpl_rules_post_id'] .'#'. $tpl_data['tpl_rules_post_id']; - break; + $this->response['tpl_rules_href'] = POST_URL . $tpl_data['tpl_rules_post_id'] . '#' . $tpl_data['tpl_rules_post_id']; + break; - // включение / отключение шаблона в форуме - case 'assign': - if (!$tpl_id = (int) $this->request['tpl_id']) - { - $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); - } - if (!$forum_id = (int) $this->request['forum_id']) - { - $this->ajax_die('empty forum_id'); - } - if (!forum_exists($forum_id)) - { - $this->ajax_die("нет такого форума [id: $forum_id]"); - } - // отключение - if ($tpl_id == -1) - { - $new_tpl_id = 0; - $this->response['msg'] = 'Шаблоны в этом форуме отключены'; - } - // включение - else - { - if (!$tpl_name = DB()->fetch_row("SELECT tpl_name FROM ". BB_TOPIC_TPL ." WHERE tpl_id = $tpl_id LIMIT 1", 'tpl_name')) - { - $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); - } - $new_tpl_id = $tpl_id; - $this->response['msg'] = "Включен шаблон $tpl_name"; - } - DB()->query("UPDATE ". BB_FORUMS ." SET forum_tpl_id = $new_tpl_id WHERE forum_id = $forum_id LIMIT 1"); - break; + // включение / отключение шаблона в форуме + case 'assign': + if (!$tpl_id = (int)$this->request['tpl_id']) { + $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); + } + if (!$forum_id = (int)$this->request['forum_id']) { + $this->ajax_die('empty forum_id'); + } + if (!forum_exists($forum_id)) { + $this->ajax_die("нет такого форума [id: $forum_id]"); + } + // отключение + if ($tpl_id == -1) { + $new_tpl_id = 0; + $this->response['msg'] = 'Шаблоны в этом форуме отключены'; + } // включение + else { + if (!$tpl_name = DB()->fetch_row("SELECT tpl_name FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1", 'tpl_name')) { + $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); + } + $new_tpl_id = $tpl_id; + $this->response['msg'] = "Включен шаблон $tpl_name"; + } + DB()->query("UPDATE " . BB_FORUMS . " SET forum_tpl_id = $new_tpl_id WHERE forum_id = $forum_id LIMIT 1"); + break; - // сохранение изменений - case 'save': - if ($tpl_data['tpl_last_edit_tm'] > $this->request['tpl_l_ed_tst'] && $tpl_data['tpl_last_edit_by'] != $userdata['user_id']) - { - $last_edit_by_username = get_username(intval($tpl_data['tpl_last_edit_by'])); - $msg = "Изменения не были сохранены!\n\n"; - $msg .= 'Шаблон был отредактирован: '. html_entity_decode($last_edit_by_username) .', '. delta_time($tpl_data['tpl_last_edit_tm']) ." назад\n\n"; - $this->ajax_die($msg); - } - $sql = "UPDATE ". BB_TOPIC_TPL ." SET ". DB()->build_array('UPDATE', $sql_args) ." WHERE tpl_id = $tpl_id LIMIT 1"; - if (!@DB()->query($sql)) - { - $sql_error = DB()->sql_error(); - } - $this->response['tpl_id'] = $tpl_id; - $this->response['tpl_name'] = $tpl_name; - $this->response['html']['tpl-last-edit-time'] = bb_date(TIMENOW, 'd-M-y H:i'); - $this->response['html']['tpl-last-edit-by'] = $userdata['username']; - break; + // сохранение изменений + case 'save': + if ($tpl_data['tpl_last_edit_tm'] > $this->request['tpl_l_ed_tst'] && $tpl_data['tpl_last_edit_by'] != $userdata['user_id']) { + $last_edit_by_username = get_username((int)$tpl_data['tpl_last_edit_by']); + $msg = "Изменения не были сохранены!\n\n"; + $msg .= 'Шаблон был отредактирован: ' . html_ent_decode($last_edit_by_username) . ', ' . bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'); + $this->ajax_die($msg); + } + $sql = "UPDATE " . BB_TOPIC_TPL . " SET " . DB()->build_array('UPDATE', $sql_args) . " WHERE tpl_id = $tpl_id LIMIT 1"; + if (!DB()->query($sql)) { + $sql_error = DB()->sql_error(); + } + $this->response['tpl_id'] = $tpl_id; + $this->response['tpl_name'] = $tpl_name; + $this->response['html']['tpl-last-edit-time'] = bb_date(TIMENOW, 'd-M-y H:i'); + $this->response['html']['tpl-last-edit-by'] = profile_url(get_userdata($userdata['username'], true)); + break; - // создание нового шаблона - case 'new': - $sql = "INSERT INTO ". BB_TOPIC_TPL . DB()->build_array('INSERT', $sql_args); - if (!@DB()->query($sql)) - { - $sql_error = DB()->sql_error(); - } - break; + // создание нового шаблона + case 'new': + $sql = "INSERT INTO " . BB_TOPIC_TPL . DB()->build_array('INSERT', $sql_args); + if (!DB()->query($sql)) { + $sql_error = DB()->sql_error(); + } + break; - // ошибочный $mode - default: - $this->ajax_die("invalid mode: $mode"); + // удаление шаблона + case 'remove': + if (!$forum_id = (int)$this->request['forum_id']) { + $this->ajax_die('empty forum_id'); + } + if (!forum_exists($forum_id)) { + $this->ajax_die("нет такого форума [id: $forum_id]"); + } + $sql = "DELETE FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1"; + if (!DB()->query($sql)) { + $sql_error = DB()->sql_error(); + } + $get_forum_tpl_id = DB()->fetch_row("SELECT forum_tpl_id FROM " . BB_FORUMS . " WHERE forum_id = " . $forum_id . " LIMIT 1"); + if ($tpl_id == $get_forum_tpl_id['forum_tpl_id']) { + DB()->query("UPDATE " . BB_FORUMS . " SET forum_tpl_id = 0 WHERE forum_id = $forum_id LIMIT 1"); + } + $this->response['msg'] = "Шаблон {$tpl_data['tpl_name']} успешно удалён"; + break; + + // ошибочный $mode + default: + $this->ajax_die("invalid mode: $mode"); } // возможный дубль названия шаблона -if ($sql_error) -{ - if ($sql_error['code'] == 1062) // Duplicate entry - { - $this->ajax_die('Шаблон с таким названием уже существует, выберите другое название'); - } - $this->ajax_die("db error {$sql_error['code']}: {$sql_error['message']}"); +if ($sql_error) { + if ($sql_error['code'] == 1062) { + // Duplicate entry + + $this->ajax_die('Шаблон с таким названием уже существует, выберите другое название'); + } + $this->ajax_die("db error {$sql_error['code']}: {$sql_error['message']}"); } // выход -$this->response['mode'] = $mode; -$this->response['timestamp'] = TIMENOW; \ No newline at end of file +$this->response['mode'] = $mode; +$this->response['timestamp'] = TIMENOW; diff --git a/library/ajax/user_register.php b/library/ajax/user_register.php index aa0a3d009..ef03c683d 100644 --- a/library/ajax/user_register.php +++ b/library/ajax/user_register.php @@ -1,76 +1,60 @@ request['mode']; +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); +} $html = ''; -switch($mode) -{ - case 'check_name': - $username = clean_username($this->request['username']); +switch ($mode) { + case 'check_name': + $username = clean_username($this->request['username']); - if (empty($username)) - { - $html = ' '. $lang['CHOOSE_A_NAME'] .''; - } - elseif($err = validate_username($username)) - { - $html = ' '. $err .''; - } - break; + if ($err = \TorrentPier\Validate::username($username)) { + $html = ' ' . $err . ''; + } + break; - case 'check_email': - $email = (string) $this->request['email']; + case 'check_email': + $email = (string)$this->request['email']; - if (empty($email)) - { - $html = ' '. $lang['CHOOSE_E_MAIL'] .''; - } - elseif($err = validate_email($email)) - { - $html = ' '. $err .''; - } - break; + if ($err = \TorrentPier\Validate::email($email)) { + $html = ' ' . $err . ''; + } + break; - case 'check_pass': - $pass = (string) $this->request['pass']; - $pass_confirm = (string) $this->request['pass_confirm']; - if (empty($pass) || empty($pass_confirm)) - { - $html = ' '. $lang['CHOOSE_PASS'] .''; - } - else - { - if ($pass != $pass_confirm) - { - $html = ' '. $lang['CHOOSE_PASS_ERR'] .''; - } - else - { - if (mb_strlen($pass, 'UTF-8') > 20) - { - $html = ' '. sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20) .''; - } - elseif (mb_strlen($pass, 'UTF-8') < 5) - { - $html = ' '. sprintf($lang['CHOOSE_PASS_ERR_MIN'], 5) .''; - } - else - { - $text = (IS_GUEST) ? $lang['CHOOSE_PASS_REG_OK'] : $lang['CHOOSE_PASS_OK']; - $html = ' '. $text .''; - } - } - } - break; + case 'check_pass': + $pass = (string)$this->request['pass']; + $pass_confirm = (string)$this->request['pass_confirm']; - case 'refresh_captcha'; - $html = CAPTCHA()->get_html(); - break; + if ($err = \TorrentPier\Validate::password($pass, $pass_confirm)) { + $html = ' ' . $err . ''; + } else { + $text = IS_GUEST ? $lang['CHOOSE_PASS_REG_OK'] : $lang['CHOOSE_PASS_OK']; + $html = ' ' . $text . ''; + } + break; + + case 'check_country': + $country = (string)$this->request['country']; + $html = render_flag($country); + break; + + default: + $this->ajax_die('Invalid mode: ' . $mode); } $this->response['html'] = $html; -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/view_post.php b/library/ajax/view_post.php index 2f0415b7a..e5d3e8462 100644 --- a/library/ajax/view_post.php +++ b/library/ajax/view_post.php @@ -1,53 +1,62 @@ request['post_id']; -$topic_id = (int) @$this->request['topic_id']; +$post_id = isset($this->request['post_id']) ? (int)$this->request['post_id'] : null; +$topic_id = isset($this->request['topic_id']) ? (int)$this->request['topic_id'] : null; +$return_text = config()->get('show_post_bbcode_button.enabled') && isset($this->request['return_text']) && (bool)$this->request['return_text']; -if (!$post_id) -{ - $post_id = DB()->fetch_row("SELECT topic_first_post_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id", 'topic_first_post_id'); +if (is_null($post_id)) { + $post_id = DB()->fetch_row("SELECT topic_first_post_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id", 'topic_first_post_id'); } +$post_text_sql = $return_text ? "pt.post_text," : "IF(h.post_html IS NULL, pt.post_text, NULL) AS post_text,"; + $sql = " SELECT p.*, - h.post_html, IF(h.post_html IS NULL, pt.post_text, NULL) AS post_text, + h.post_html, $post_text_sql f.auth_read - FROM ". BB_POSTS ." p - INNER JOIN ". BB_POSTS_TEXT ." pt ON(pt.post_id = p.post_id) - LEFT JOIN ". BB_POSTS_HTML ." h ON(h.post_id = pt.post_id) - INNER JOIN ". BB_FORUMS ." f ON(f.forum_id = p.forum_id) + FROM " . BB_POSTS . " p + INNER JOIN " . BB_POSTS_TEXT . " pt ON(pt.post_id = p.post_id) + LEFT JOIN " . BB_POSTS_HTML . " h ON(h.post_id = pt.post_id) + INNER JOIN " . BB_FORUMS . " f ON(f.forum_id = p.forum_id) WHERE p.post_id = $post_id LIMIT 1 "; -if (!$post_data = DB()->fetch_row($sql)) -{ - $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); +if (!$post_data = DB()->fetch_row($sql)) { + $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); } // Auth check -if ($post_data['auth_read'] == AUTH_REG) -{ - if (IS_GUEST) - { - $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); - } -} -elseif ($post_data['auth_read'] != AUTH_ALL) -{ - $is_auth = auth(AUTH_READ, $post_data['forum_id'], $user->data, $post_data); - if (!$is_auth['auth_read']) - { - $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); - } +if ($post_data['auth_read'] == AUTH_REG) { + if (IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } +} elseif ($post_data['auth_read'] != AUTH_ALL) { + $is_auth = auth(AUTH_READ, $post_data['forum_id'], $user->data, $post_data); + if (!$is_auth['auth_read']) { + $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); + } } -$this->response['post_id'] = $post_id; -$this->response['topic_id'] = $topic_id; -$this->response['post_html'] = get_parsed_post($post_data); \ No newline at end of file +$this->response['post_id'] = $post_id; +$this->response['topic_id'] = $topic_id; +if ($return_text) { + $this->response['post_text'] = $post_data['post_text']; +} else { + $this->response['post_html'] = get_parsed_post($post_data); +} diff --git a/library/ajax/view_torrent.php b/library/ajax/view_torrent.php index af2327b8e..942a32b11 100644 --- a/library/ajax/view_torrent.php +++ b/library/ajax/view_torrent.php @@ -1,186 +1,43 @@ request['attach_id'])) -{ - $this->ajax_die($lang['EMPTY_ATTACH_ID']); +if (!isset($this->request['attach_id'])) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); } -$attach_id = (int) $this->request['attach_id']; +$attach_id = (int)$this->request['attach_id']; -global $bnc_error; -$bnc_error = 0; - -$torrent = DB()->fetch_row("SELECT at.attach_id, at.physical_filename FROM ". BB_ATTACHMENTS_DESC ." at WHERE at.attach_id = $attach_id LIMIT 1"); -if (!$torrent) $this->ajax_die($lang['EMPTY_ATTACH_ID']); -$filename = get_attachments_dir() .'/'. $torrent['physical_filename']; - -if (($file_contents = @file_get_contents($filename)) === false) -{ - if (IS_AM) - { - $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] ."\n\n". htmlCHR($filename)); - } - else - { - $this->ajax_die($lang['ERROR_NO_ATTACHMENT']); - } +$torrent = DB()->fetch_row("SELECT attach_id, physical_filename FROM " . BB_ATTACHMENTS_DESC . " WHERE attach_id = $attach_id LIMIT 1"); +if (!$torrent) { + $this->ajax_die($lang['ERROR_BUILD']); } -// Построение списка -$tor_filelist = build_tor_filelist($file_contents); - -function build_tor_filelist ($file_contents) -{ - global $lang; - - if (!$tor = bdecode($file_contents)) - { - return $lang['TORFILE_INVALID']; - } - - $torrent = new torrent($tor); - - return $torrent->get_filelist(); +$file_contents = null; +$filename = get_attachments_dir() . '/' . $torrent['physical_filename']; +if (!is_file($filename) || !$file_contents = file_get_contents($filename)) { + $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] . "\n\n" . htmlCHR($filename)); } -class torrent -{ - var $tor_decoded = array(); - var $files_ary = array('/' => ''); - var $multiple = null; - var $root_dir = ''; - var $files_html = ''; - - function torrent ($decoded_file_contents) - { - $this->tor_decoded = $decoded_file_contents; - } - - function get_filelist () - { - $this->build_filelist_array(); - - if ($this->multiple) - { - if ($this->files_ary['/'] !== '') - { - $this->files_ary = array_merge($this->files_ary, $this->files_ary['/']); - unset($this->files_ary['/']); - } - $filelist = $this->build_filelist_html(); - return "
    {$this->root_dir}
    $filelist"; - } - else - { - return join('', $this->files_ary['/']); - } - } - - function build_filelist_array () - { - $info = $this->tor_decoded['info']; - - if (isset($info['name.utf-8'])) - { - $info['name'] =& $info['name.utf-8']; - } - - if (isset($info['files']) && is_array($info['files'])) - { - $this->root_dir = isset($info['name']) ? '../'. clean_tor_dirname($info['name']) : '...'; - $this->multiple = true; - - foreach ($info['files'] as $f) - { - if (isset($f['path.utf-8'])) - { - $f['path'] =& $f['path.utf-8']; - } - if (!isset($f['path']) || !is_array($f['path'])) - { - continue; - } - array_deep($f['path'], 'clean_tor_dirname'); - - $length = isset($f['length']) ? (float) $f['length'] : 0; - $subdir_count = count($f['path']) - 1; - - if ($subdir_count > 0) - { - $name = array_pop($f['path']); - $cur_files_ary =& $this->files_ary; - - for ($i=0,$j=1; $i < $subdir_count; $i++,$j++) - { - $subdir = $f['path'][$i]; - - if (!isset($cur_files_ary[$subdir])) - { - $cur_files_ary[$subdir] = array(); - } - $cur_files_ary =& $cur_files_ary[$subdir]; - - if ($j == $subdir_count) - { - if (is_string($cur_files_ary)) - { - $GLOBALS['bnc_error'] = 1; - break(1); - } - $cur_files_ary[] = $this->build_file_item($name, $length); - } - } - @natsort($cur_files_ary); - } - else - { - $name = $f['path'][0]; - $this->files_ary['/'][] = $this->build_file_item($name, $length); - natsort($this->files_ary['/']); - } - } - } - else - { - $this->multiple = false; - $name = isset($info['name']) ? clean_tor_dirname($info['name']) : ''; - $length = isset($info['length']) ? (float) $info['length'] : 0; - - $this->files_ary['/'][] = $this->build_file_item($name, $length); - natsort($this->files_ary['/']); - } - } - - function build_file_item ($name, $length) - { - global $bb_cfg, $images, $lang; - - $magnet_name = $magnet_ext = ''; - - if ($bb_cfg['magnet_links_enabled']) - { - $magnet_name = ''; - $magnet_ext = ''; - } - - return "$name $length $magnet_name $magnet_ext"; - } - - function build_filelist_html () - { - global $html; - return $html->array2html($this->files_ary); - } +try { + $tor = \Arokettu\Bencode\Bencode::decode($file_contents, dictType: \Arokettu\Bencode\Bencode\Collection::ARRAY); +} catch (\Exception $e) { + $this->response['html'] = htmlCHR("{$lang['TORFILE_INVALID']}: {$e->getMessage()}"); + return; } -function clean_tor_dirname ($dirname) -{ - return str_replace(array('[', ']', '<', '>', "'"), array('[', ']', '<', '>', '''), $dirname); -} +$torrent = new TorrentPier\Legacy\TorrentFileList($tor); -if ($bnc_error) $tor_filelist = ''.$lang['ERROR_BUILD'].'

    '.$tor_filelist; +$tor_filelist = $torrent->get_filelist(); -$this->response['html'] = $tor_filelist; \ No newline at end of file +$this->response['html'] = $tor_filelist; diff --git a/library/attach_mod/.htaccess b/library/attach_mod/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/library/attach_mod/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/library/attach_mod/attachment_mod.php b/library/attach_mod/attachment_mod.php index c6f3eac02..16fa06a8b 100644 --- a/library/attach_mod/attachment_mod.php +++ b/library/attach_mod/attachment_mod.php @@ -1,82 +1,77 @@ get('default_lang') . '/' . $language_file . '.php'; + if (file_exists($file)) { + return config()->get('default_lang'); + } - if (!file_exists(LANG_ROOT_DIR ."$language/$language_file.php")) - { - bb_die('Attachment mod language file does not exist: language/' . $language . '/' . $language_file . '.php'); - } - else - { - return $language; - } - } - else - { - return $language; - } + $file = LANG_ROOT_DIR . '/' . $attach_config['board_lang'] . '/' . $language_file . '.php'; + if (file_exists($file)) { + return $attach_config['board_lang']; + } + + bb_die('Attachment mod language file does not exist: language/' . $attach_config['board_lang'] . '/' . $language_file . '.php'); } /** -* Get attachment mod configuration -*/ + * Get attachment mod configuration + */ function get_config() { - global $bb_cfg; + $attach_config = []; - $attach_config = array(); + $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; - $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information'); + } - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachment information'); - } + while ($row = DB()->sql_fetchrow($result)) { + $attach_config[$row['config_name']] = trim($row['config_value']); + } - while ($row = DB()->sql_fetchrow($result)) - { - $attach_config[$row['config_name']] = trim($row['config_value']); - } + // We assign the original default board language here, because it gets overwritten later with the users default language + $attach_config['board_lang'] = trim(config()->get('default_lang')); - // We assign the original default board language here, because it gets overwritten later with the users default language - $attach_config['board_lang'] = trim($bb_cfg['default_lang']); - - return $attach_config; + return $attach_config; } // Get Attachment Config -$attach_config = array(); +$attach_config = []; -if (!$attach_config = CACHE('bb_cache')->get('attach_config')) -{ - $attach_config = get_config(); - CACHE('bb_cache')->set('attach_config', $attach_config, 86400); +if (!$attach_config = CACHE('bb_cache')->get('attach_config')) { + $attach_config = get_config(); + CACHE('bb_cache')->set('attach_config', $attach_config, 86400); } -include(ATTACH_DIR .'displaying.php'); -include(ATTACH_DIR .'posting_attachments.php'); +include ATTACH_DIR . '/displaying.php'; +include ATTACH_DIR . '/posting_attachments.php'; -$upload_dir = $attach_config['upload_dir']; \ No newline at end of file +$upload_dir = $attach_config['upload_dir']; diff --git a/library/attach_mod/displaying.php b/library/attach_mod/displaying.php index d1c6e3e6e..9f6ee8394 100644 --- a/library/attach_mod/displaying.php +++ b/library/attach_mod/displaying.php @@ -1,346 +1,319 @@ update('attach_extensions'); //get_extension_informations() - $extension_informations = get_extension_informations(); - } - $allowed_extensions = array(); + if (!$extension_informations = get_extension_informations()) { + $GLOBALS['datastore']->update('attach_extensions'); + $extension_informations = get_extension_informations(); + } - for ($i = 0, $size = sizeof($extension_informations); $i < $size; $i++) - { - $extension = strtolower(trim($extension_informations[$i]['extension'])); - $allowed_extensions[] = $extension; - $display_categories[$extension] = intval($extension_informations[$i]['cat_id']); - $download_modes[$extension] = intval($extension_informations[$i]['download_mode']); - $upload_icons[$extension] = trim($extension_informations[$i]['upload_icon']); - } + $allowed_extensions = []; + for ($i = 0, $size = count($extension_informations); $i < $size; $i++) { + $extension = strtolower(trim($extension_informations[$i]['extension'])); + // Get allowed extensions + if ((int)$extension_informations[$i]['allow_group'] === 1) { + $allowed_extensions[] = $extension; + } + $display_categories[$extension] = (int)$extension_informations[$i]['cat_id']; + $download_modes[$extension] = (int)$extension_informations[$i]['download_mode']; + $upload_icons[$extension] = trim($extension_informations[$i]['upload_icon']); + } } /** -* Writing Data into plain Template Vars -*/ + * Writing Data into plain Template Vars + */ function init_display_template($template_var, $replacement, $filename = 'viewtopic_attach.tpl') { - global $template; + global $template; - // This function is adapted from the old template class - // I wish i had the functions from the 3.x one. :D (This class rocks, can't await to use it in Mods) + // This function is adapted from the old template class + // I wish i had the functions from the 3.x one. :D (This class rocks, can't await to use it in Mods) - // Handle Attachment Informations - if (!isset($template->uncompiled_code[$template_var]) && empty($template->uncompiled_code[$template_var])) - { - // If we don't have a file assigned to this handle, die. - if (!isset($template->files[$template_var])) - { - die("Template->loadfile(): No file specified for handle $template_var"); - } + // Handle Attachment Informations + if (!isset($template->uncompiled_code[$template_var]) && empty($template->uncompiled_code[$template_var])) { + // If we don't have a file assigned to this handle, die. + if (!isset($template->files[$template_var])) { + die("Template->loadfile(): No file specified for handle $template_var"); + } - $filename_2 = $template->files[$template_var]; + $filename_2 = $template->files[$template_var]; - $str = implode('', @file($filename_2)); - if (empty($str)) - { - die("Template->loadfile(): File $filename_2 for handle $template_var is empty"); - } + $str = file_get_contents($filename_2); + if (empty($str)) { + die("Template->loadfile(): File $filename_2 for handle $template_var is empty"); + } - $template->uncompiled_code[$template_var] = $str; - } + $template->uncompiled_code[$template_var] = $str; + } - $complete_filename = $filename; - if (substr($complete_filename, 0, 1) != '/') - { - $complete_filename = $template->root . '/' . $complete_filename; - } + $complete_filename = $filename; + if ($complete_filename[0] != '/') { + $complete_filename = $template->root . '/' . $complete_filename; + } - if (!file_exists($complete_filename)) - { - die("Template->make_filename(): Error - file $complete_filename does not exist"); - } + if (!file_exists($complete_filename)) { + die("Template->make_filename(): Error - file $complete_filename does not exist"); + } - $content = implode('', file($complete_filename)); - if (empty($content)) - { - die('Template->loadfile(): File ' . $complete_filename . ' is empty'); - } + $content = file_get_contents($complete_filename); + if (empty($content)) { + die('Template->loadfile(): File ' . $complete_filename . ' is empty'); + } - // replace $replacement with uncompiled code in $filename - $template->uncompiled_code[$template_var] = str_replace($replacement, $content, $template->uncompiled_code[$template_var]); + // replace $replacement with uncompiled code in $filename + $template->uncompiled_code[$template_var] = str_replace($replacement, $content, $template->uncompiled_code[$template_var]); } /** -* Display Attachments in Posts -*/ + * Display Attachments in Posts + */ function display_post_attachments($post_id, $switch_attachment) { - global $attach_config, $is_auth; + global $attach_config, $is_auth; - if (intval($switch_attachment) == 0 || intval($attach_config['disable_mod'])) - { - return; - } + if ((int)$switch_attachment == 0 || (int)$attach_config['disable_mod']) { + return; + } - if ($is_auth['auth_download'] && $is_auth['auth_view']) - { - display_attachments($post_id); - } + if ($is_auth['auth_download'] && $is_auth['auth_view']) { + display_attachments($post_id); + } } /** -* Initializes some templating variables for displaying Attachments in Posts -*/ + * Initializes some templating variables for displaying Attachments in Posts + */ function init_display_post_attachments($switch_attachment) { - global $attach_config, $is_auth, $template, $lang, $postrow, $total_posts, $attachments, $forum_row, $t_data; + global $attach_config, $is_auth, $template, $lang, $postrow, $total_posts, $attachments, $forum_row, $t_data; - if (empty($t_data) && !empty($forum_row)) - { - $switch_attachment = $forum_row['topic_attachment']; - } + if (empty($t_data) && !empty($forum_row)) { + $switch_attachment = $forum_row['topic_attachment']; + } - if (intval($switch_attachment) == 0 || intval($attach_config['disable_mod']) || (!($is_auth['auth_download'] && $is_auth['auth_view']))) - { - init_display_template('body', '{postrow.ATTACHMENTS}', 'viewtopic_attach_guest.tpl'); - return; - } + if ((int)$switch_attachment == 0 || (int)$attach_config['disable_mod'] || (!($is_auth['auth_download'] && $is_auth['auth_view']))) { + init_display_template('body', '{postrow.ATTACHMENTS}', 'viewtopic_attach_guest.tpl'); + return; + } - $post_id_array = array(); + $post_id_array = []; - for ($i = 0; $i < $total_posts; $i++) - { - if ($postrow[$i]['post_attachment'] == 1) - { - $post_id_array[] = (int) $postrow[$i]['post_id']; - } - } + for ($i = 0; $i < $total_posts; $i++) { + if ($postrow[$i]['post_attachment'] == 1) { + $post_id_array[] = (int)$postrow[$i]['post_id']; + } + } - if (sizeof($post_id_array) == 0) - { - return; - } + if (count($post_id_array) == 0) { + return; + } - $rows = get_attachments_from_post($post_id_array); - $num_rows = sizeof($rows); + $rows = get_attachments_from_post($post_id_array); + $num_rows = count($rows); - if ($num_rows == 0) - { - return; - } + if ($num_rows == 0) { + return; + } - @reset($attachments); + @reset($attachments); - for ($i = 0; $i < $num_rows; $i++) - { - $attachments['_' . $rows[$i]['post_id']][] = $rows[$i]; - //bt - if ($rows[$i]['tracker_status']) - { - if (defined('TORRENT_POST')) - { - bb_die('Multiple registered torrents in one topic

    first torrent found in post_id = '. TORRENT_POST .'
    current post_id = '. $rows[$i]['post_id'] .'

    attachments info:
    '. print_r($rows, TRUE) .'
    '); - } - define('TORRENT_POST', $rows[$i]['post_id']); - } - //bt end - } + for ($i = 0; $i < $num_rows; $i++) { + $attachments['_' . $rows[$i]['post_id']][] = $rows[$i]; + //bt + if ($rows[$i]['tracker_status']) { + if (defined('TORRENT_POST')) { + bb_die('Multiple registered torrents in one topic

    first torrent found in post_id = ' . TORRENT_POST . '
    current post_id = ' . $rows[$i]['post_id'] . '

    attachments info:
    ' . print_r($rows, true) . '
    '); + } + define('TORRENT_POST', $rows[$i]['post_id']); + } + //bt end + } - init_display_template('body', '{postrow.ATTACHMENTS}'); + init_display_template('body', '{postrow.ATTACHMENTS}'); - init_complete_extensions_data(); + init_complete_extensions_data(); } /** -* END ATTACHMENT DISPLAY IN POSTS -*/ + * END ATTACHMENT DISPLAY IN POSTS + */ /** -* Assign Variables and Definitions based on the fetched Attachments - internal -* used by all displaying functions, the Data was collected before, it's only dependend on the template used. :) -* before this function is usable, init_display_attachments have to be called for specific pages (pm, posting, review etc...) -*/ + * Assign Variables and Definitions based on the fetched Attachments - internal + * used by all displaying functions, the Data was collected before, it's only dependend on the template used. :) + * before this function is usable, init_display_attachments have to be called for specific pages (pm, posting, review etc...) + */ function display_attachments($post_id) { - global $template, $upload_dir, $userdata, $allowed_extensions, $display_categories, $download_modes, $lang, $attachments, $upload_icons, $attach_config; + global $template, $upload_dir, $userdata, $allowed_extensions, $display_categories, $download_modes, $lang, $attachments, $upload_icons, $attach_config; - $num_attachments = @sizeof($attachments['_' . $post_id]); + $num_attachments = @count($attachments['_' . $post_id]); - if ($num_attachments == 0) - { - return; - } + if ($num_attachments == 0) { + return; + } - $template->assign_block_vars('postrow.attach', array()); + $template->assign_block_vars('postrow.attach', []); - for ($i = 0; $i < $num_attachments; $i++) - { - // Some basic things... - $filename = $upload_dir . '/' . basename($attachments['_' . $post_id][$i]['physical_filename']); - $thumbnail_filename = $upload_dir . '/' . THUMB_DIR . '/t_' . basename($attachments['_' . $post_id][$i]['physical_filename']); + for ($i = 0; $i < $num_attachments; $i++) { + $filename = $upload_dir . '/' . basename($attachments['_' . $post_id][$i]['physical_filename']); - $upload_image = ''; + $upload_image = ''; + if ($attach_config['upload_img'] && empty($upload_icons[$attachments['_' . $post_id][$i]['extension']])) { + $upload_image = ''; + } elseif (trim($upload_icons[$attachments['_' . $post_id][$i]['extension']]) != '') { + $upload_image = ''; + } - if ($attach_config['upload_img'] && empty($upload_icons[$attachments['_' . $post_id][$i]['extension']])) - { - $upload_image = ''; - } - else if (trim($upload_icons[$attachments['_' . $post_id][$i]['extension']]) != '') - { - $upload_image = ''; - } + $filesize = humn_size($attachments['_' . $post_id][$i]['filesize']); - $filesize = humn_size($attachments['_' . $post_id][$i]['filesize']); + $display_name = htmlspecialchars($attachments['_' . $post_id][$i]['real_filename']); + $comment = htmlspecialchars($attachments['_' . $post_id][$i]['comment']); + $comment = str_replace("\n", '
    ', $comment); - $display_name = htmlspecialchars($attachments['_' . $post_id][$i]['real_filename']); - $comment = htmlspecialchars($attachments['_' . $post_id][$i]['comment']); - $comment = str_replace("\n", '
    ', $comment); + $denied = false; - $denied = false; + // Admin is allowed to view forbidden Attachments, but the error-message is displayed too to inform the Admin + if (!in_array($attachments['_' . $post_id][$i]['extension'], $allowed_extensions)) { + $denied = true; - // Admin is allowed to view forbidden Attachments, but the error-message is displayed too to inform the Admin - if (!in_array($attachments['_' . $post_id][$i]['extension'], $allowed_extensions)) - { - $denied = true; + $template->assign_block_vars('postrow.attach.denyrow', ['L_DENIED' => sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachments['_' . $post_id][$i]['extension'])]); + } - $template->assign_block_vars('postrow.attach.denyrow', array( - 'L_DENIED' => sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachments['_' . $post_id][$i]['extension'])) - ); - } + if (!$denied || IS_ADMIN) { + // define category + $image = false; + $thumbnail = false; + $link = false; - if (!$denied || IS_ADMIN) - { - // define category - $image = FALSE; - $thumbnail = FALSE; - $link = FALSE; + // Shows the images in topic + if (@(int)$display_categories[$attachments['_' . $post_id][$i]['extension']] == IMAGE_CAT && (int)$attach_config['img_display_inlined']) { + if ((int)$attach_config['img_link_width'] != 0 || (int)$attach_config['img_link_height'] != 0) { + // Get image sizes + [$width, $height] = getimagesize($filename); - if (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT && intval($attach_config['img_display_inlined'])) - { - if (intval($attach_config['img_link_width']) != 0 || intval($attach_config['img_link_height']) != 0) - { - list($width, $height) = image_getdimension($filename); + // Check if image sizes is allowed + if ($width == 0 && $height == 0) { + $image = true; + } else { + if ($width <= (int)$attach_config['img_link_width'] && $height <= (int)$attach_config['img_link_height']) { + $image = true; + } + } + } else { + $image = true; + } + } - if ($width == 0 && $height == 0) - { - $image = TRUE; - } - else - { - if ($width <= intval($attach_config['img_link_width']) && $height <= intval($attach_config['img_link_height'])) - { - $image = TRUE; - } - } - } - else - { - $image = TRUE; - } - } + // Checks if image is thumbnail + if (@(int)$display_categories[$attachments['_' . $post_id][$i]['extension']] == IMAGE_CAT && $attachments['_' . $post_id][$i]['thumbnail'] == 1) { + $thumbnail = true; + $image = false; + } - if (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT && $attachments['_' . $post_id][$i]['thumbnail'] == 1) - { - $thumbnail = TRUE; - $image = FALSE; - } + // Checks whether the image should be displayed as a link + if (!$image && !$thumbnail) { + $link = true; + } - if (!$image && !$thumbnail) - { - $link = TRUE; - } + if ($image) { + // Images + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $img_source = BB_ROOT . DL_URL . $attachments['_' . $post_id][$i]['attach_id']; + $download_link = true; + } else { + $img_source = $filename; + $download_link = false; + } - if ($image) - { - // Images - if ($attach_config['upload_dir'][0] == '/' || ( $attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $img_source = BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id']; - $download_link = TRUE; - } - else - { - $img_source = $filename; - $download_link = FALSE; - } + $template->assign_block_vars('postrow.attach.cat_images', [ + 'DOWNLOAD_NAME' => $display_name, + 'S_UPLOAD_IMAGE' => $upload_image, + 'IMG_SRC' => $img_source, + 'FILESIZE' => $filesize, + 'COMMENT' => $comment + ]); - $template->assign_block_vars('postrow.attach.cat_images', array( - 'DOWNLOAD_NAME' => $display_name, - 'S_UPLOAD_IMAGE' => $upload_image, - 'IMG_SRC' => $img_source, - 'FILESIZE' => $filesize, - 'COMMENT' => $comment, - )); - - // Directly Viewed Image ... update the download count - if (!$download_link) - { - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' + // Directly Viewed Image ... update the download count + if (!$download_link) { + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET download_count = download_count + 1 - WHERE attach_id = ' . (int) $attachments['_' . $post_id][$i]['attach_id']; + WHERE attach_id = ' . (int)$attachments['_' . $post_id][$i]['attach_id']; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not update attachment download count'); - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not update attachment download count'); + } + } + } - if ($thumbnail) - { - // Images, but display Thumbnail - if ($attach_config['upload_dir'][0] == '/' || ( $attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $thumb_source = BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'] . '&thumb=1'; - } - else - { - $thumb_source = $thumbnail_filename; - } + if ($thumbnail) { + // Images, but display Thumbnail + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $thumb_source = BB_ROOT . DL_URL . $attachments['_' . $post_id][$i]['attach_id'] . '&thumb=1'; + } else { + // Get the thumbnail image + $thumbnail_filename = $upload_dir . '/' . THUMB_DIR . '/t_' . basename($attachments['_' . $post_id][$i]['physical_filename']); - $template->assign_block_vars('postrow.attach.cat_thumb_images', array( - 'DOWNLOAD_NAME' => $display_name, - 'S_UPLOAD_IMAGE' => $upload_image, - 'IMG_SRC' => BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'], - 'IMG_THUMB_SRC' => $thumb_source, - 'FILESIZE' => $filesize, - 'COMMENT' => $comment, - )); - } + // Checks the thumbnail existence + if (!is_file($thumbnail_filename)) { + continue; + } - // bt - if ($link && ($attachments['_'. $post_id][$i]['extension'] === TORRENT_EXT)) - { - include(ATTACH_DIR .'displaying_torrent.php'); - } - else if ($link) - { - $target_blank = ( (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT) ) ? 'target="_blank"' : ''; + $thumb_source = $thumbnail_filename; + } - // display attachment - $template->assign_block_vars('postrow.attach.attachrow', array( - 'U_DOWNLOAD_LINK' => BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'], - 'S_UPLOAD_IMAGE' => $upload_image, - 'DOWNLOAD_NAME' => $display_name, - 'FILESIZE' => $filesize, - 'COMMENT' => $comment, - 'TARGET_BLANK' => $target_blank, - 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $attachments['_' . $post_id][$i]['download_count']), - )); - } - } - } -} \ No newline at end of file + $template->assign_block_vars('postrow.attach.cat_thumb_images', [ + 'DOWNLOAD_NAME' => $display_name, + 'S_UPLOAD_IMAGE' => $upload_image, + 'IMG_SRC' => BB_ROOT . DL_URL . $attachments['_' . $post_id][$i]['attach_id'], + 'IMG_THUMB_SRC' => $thumb_source, + 'FILESIZE' => $filesize, + 'COMMENT' => $comment, + 'DOWNLOAD_COUNT' => declension((int)$attachments['_' . $post_id][$i]['download_count'], 'times'), + ]); + } + + // bt + if ($link && ($attachments['_' . $post_id][$i]['extension'] === TORRENT_EXT)) { + include ATTACH_DIR . '/displaying_torrent.php'; + } elseif ($link) { + $target_blank = ((@(int)$display_categories[$attachments['_' . $post_id][$i]['extension']] == IMAGE_CAT)) ? 'target="_blank"' : ''; + + // display attachment + $template->assign_block_vars('postrow.attach.attachrow', [ + 'U_DOWNLOAD_LINK' => BB_ROOT . DL_URL . $attachments['_' . $post_id][$i]['attach_id'], + 'S_UPLOAD_IMAGE' => $upload_image, + 'DOWNLOAD_NAME' => $display_name, + 'FILESIZE' => $filesize, + 'COMMENT' => $comment, + 'TARGET_BLANK' => $target_blank, + 'IS_IMAGE' => (bool)$target_blank, + 'DOWNLOAD_COUNT' => declension((int)$attachments['_' . $post_id][$i]['download_count'], 'times') + ]); + } + } + } +} diff --git a/library/attach_mod/displaying_torrent.php b/library/attach_mod/displaying_torrent.php index 4373939a7..18c6a5bbf 100644 --- a/library/attach_mod/displaying_torrent.php +++ b/library/attach_mod/displaying_torrent.php @@ -1,71 +1,74 @@ '; +$peers_div_style_normal = 'padding: 3px;'; +$peers_div_style_overflow = "padding: 6px; height: $peers_overflow_div_height; overflow: auto; border: 1px inset;"; +$s_last_seed_date_format = 'Y-m-d'; +$upload_image = '' . $lang['DL_TORRENT'] . ''; -$peers_cnt = $seed_count = 0; +$peers_cnt = $seed_count = $leech_count = 0; $seeders = $leechers = ''; -$tor_info = array(); +$tor_info = []; -$template->assign_vars(array( - 'SEED_COUNT' => false, - 'LEECH_COUNT' => false, - 'TOR_SPEED_UP' => false, - 'TOR_SPEED_DOWN' => false, - 'SHOW_RATIO_WARN' => false, -)); +$template->assign_vars([ + 'SEED_COUNT' => false, + 'LEECH_COUNT' => false, + 'TOR_SPEED_UP' => false, + 'TOR_SPEED_DOWN' => false, + 'SHOW_RATIO_WARN' => false +]); // Define show peers mode (count only || user names with complete % || full details) -$cfg_sp_mode = $bb_cfg['bt_show_peers_mode']; -$get_sp_mode = (isset($_GET['spmode'])) ? $_GET['spmode'] : ''; +$cfg_sp_mode = config()->get('bt_show_peers_mode'); +$get_sp_mode = $_GET['spmode'] ?? ''; $s_mode = 'count'; -if ($cfg_sp_mode == SHOW_PEERS_NAMES) -{ - $s_mode = 'names'; -} -else if ($cfg_sp_mode == SHOW_PEERS_FULL) -{ - $s_mode = 'full'; +if ($cfg_sp_mode == SHOW_PEERS_NAMES) { + $s_mode = 'names'; +} elseif ($cfg_sp_mode == SHOW_PEERS_FULL) { + $s_mode = 'full'; } -if ($bb_cfg['bt_allow_spmode_change']) -{ - if ($get_sp_mode == 'names') - { - $s_mode = 'names'; - } - else if ($get_sp_mode == 'full') - { - $s_mode = 'full'; - } +if (config()->get('bt_allow_spmode_change')) { + if ($get_sp_mode == 'names') { + $s_mode = 'names'; + } elseif ($get_sp_mode == 'full') { + $s_mode = 'full'; + } } -$bt_topic_id = $t_data['topic_id']; -$bt_user_id = $userdata['user_id']; -$attach_id = $attachments['_'. $post_id][$i]['attach_id']; -$tracker_status = $attachments['_'. $post_id][$i]['tracker_status']; -$download_count = $attachments['_'. $post_id][$i]['download_count']; -$tor_file_size = humn_size($attachments['_'. $post_id][$i]['filesize']); -$tor_file_time = bb_date($attachments['_'. $post_id][$i]['filetime']); +$bt_topic_id = $t_data['topic_id']; +$bt_user_id = $userdata['user_id']; +$attach_id = $attachments['_' . $post_id][$i]['attach_id']; +$tracker_status = $attachments['_' . $post_id][$i]['tracker_status']; +$download_count = declension((int)$attachments['_' . $post_id][$i]['download_count'], 'times'); +$tor_file_size = humn_size($attachments['_' . $post_id][$i]['filesize']); +$tor_file_time = bb_date($attachments['_' . $post_id][$i]['filetime']); -$tor_reged = (bool) $tracker_status; -$show_peers = (bool) $bb_cfg['bt_show_peers']; +$tor_reged = (bool)$tracker_status; +$show_peers = (bool)config()->get('bt_show_peers'); $locked = ($t_data['forum_status'] == FORUM_LOCKED || $t_data['topic_status'] == TOPIC_LOCKED); $tor_auth = ($bt_user_id != GUEST_UID && (($bt_user_id == $poster_id && !$locked) || $is_auth['auth_mod'])); @@ -73,532 +76,511 @@ $tor_auth = ($bt_user_id != GUEST_UID && (($bt_user_id == $poster_id && !$locked $tor_auth_reg = ($tor_auth && $t_data['allow_reg_tracker'] && $post_id == $t_data['topic_first_post_id']); $tor_auth_del = ($tor_auth && $tor_reged); -$tracker_link = ($tor_reged) ? $lang['BT_REG_YES'] : $lang['BT_REG_NO']; +$tracker_link = ($tor_reged) ? $lang['BT_REG_YES'] : $lang['BT_REG_NO']; -$download_link = DOWNLOAD_URL . $attach_id; -$description = ($comment) ? $comment : preg_replace("#.torrent$#i", '', $display_name); +$download_link = DL_URL . $attach_id; +$description = ($comment) ?: preg_replace("#" . "." . TORRENT_EXT . "$#i", '', $display_name); -if ($tor_auth_reg || $tor_auth_del) -{ - $reg_tor_url = ''. $lang['BT_REG_ON_TRACKER'] .''; - $unreg_tor_url = ''. $lang['BT_UNREG_FROM_TRACKER'] .''; +if ($tor_auth_reg || $tor_auth_del) { + $reg_tor_url = '' . $lang['BT_REG_ON_TRACKER'] . ''; + $unreg_tor_url = '' . $lang['BT_UNREG_FROM_TRACKER'] . ''; - $tracker_link = ($tor_reged) ? $unreg_tor_url : $reg_tor_url; + $tracker_link = ($tor_reged) ? $unreg_tor_url : $reg_tor_url; } -if ($bb_cfg['torrent_name_style']) -{ - $display_name = '['.$bb_cfg['server_name'].'].t' . $bt_topic_id . '.torrent'; +if (config()->get('tracker.use_old_torrent_name_format')) { + $display_name = '[' . config()->get('server_name') . '].t' . $bt_topic_id . '.' . TORRENT_EXT; +} else { + $display_name = $t_data['topic_title'] . ' [' . config()->get('server_name') . '-' . $bt_topic_id . ']' . '.' . TORRENT_EXT; } -if (!$tor_reged) -{ - $template->assign_block_vars('postrow.attach.tor_not_reged', array( - 'DOWNLOAD_NAME' => $display_name, - 'TRACKER_LINK' => $tracker_link, - 'ATTACH_ID' => $attach_id, +if (!$tor_reged) { + $template->assign_block_vars('postrow.attach.tor_not_reged', [ + 'DOWNLOAD_NAME' => $display_name, + 'TRACKER_LINK' => $tracker_link, + 'ATTACH_ID' => $attach_id, - 'S_UPLOAD_IMAGE' => $upload_image, - 'U_DOWNLOAD_LINK' => $download_link, - 'FILESIZE' => $tor_file_size, + 'S_UPLOAD_IMAGE' => $upload_image, + 'U_DOWNLOAD_LINK' => $download_link, + 'FILESIZE' => $tor_file_size, - 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $download_count), - 'POSTED_TIME' => $tor_file_time, - )); + 'DOWNLOAD_COUNT' => $download_count, + 'POSTED_TIME' => $tor_file_time, + ]); - if ($comment) - { - $template->assign_block_vars('postrow.attach.tor_not_reged.comment', array('COMMENT' => $comment)); - } -} -else -{ - $sql = "SELECT bt.*, u.user_id, u.username, u.user_rank - FROM ". BB_BT_TORRENTS ." bt - LEFT JOIN ". BB_USERS ." u ON(bt.checked_user_id = u.user_id) + if ($comment) { + $template->assign_block_vars('postrow.attach.tor_not_reged.comment', ['COMMENT' => $comment]); + } +} else { + $sql = "SELECT bt.*, u.user_id, u.username, u.user_rank + FROM " . BB_BT_TORRENTS . " bt + LEFT JOIN " . BB_USERS . " u ON(bt.checked_user_id = u.user_id) WHERE bt.attach_id = $attach_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain torrent information'); - } - $tor_info = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain torrent information'); + } + $tor_info = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); } -if ($tor_reged && !$tor_info) -{ - DB()->query("UPDATE ". BB_ATTACHMENTS_DESC ." SET tracker_status = 0 WHERE attach_id = $attach_id"); +if ($tor_reged && !$tor_info) { + DB()->query("UPDATE " . BB_ATTACHMENTS_DESC . " SET tracker_status = 0 WHERE attach_id = $attach_id"); - bb_die('Torrent status fixed'); + bb_die('Torrent status fixed'); } -if ($tor_auth) -{ - $template->assign_vars(array( - 'TOR_CONTROLS' => true, - 'TOR_ATTACH_ID' => $attach_id, - )); +if ($tor_auth) { + $template->assign_vars([ + 'TOR_CONTROLS' => true, + 'TOR_ATTACH_ID' => $attach_id + ]); - if ($t_data['self_moderated'] || $is_auth['auth_mod']) - { - $template->assign_vars(array('AUTH_MOVE' => true)); - } + if ($t_data['self_moderated'] || $is_auth['auth_mod']) { + $template->assign_vars(['AUTH_MOVE' => true]); + } } -if ($tor_reged && $tor_info) -{ - $tor_size = ($tor_info['size']) ? $tor_info['size'] : 0; - $tor_id = $tor_info['topic_id']; - $tor_type = $tor_info['tor_type']; +if ($tor_reged && $tor_info) { + $tor_size = ($tor_info['size']) ?: 0; + $tor_completed_count = declension((int)$tor_info['complete_count'], 'times'); + $tor_id = $tor_info['topic_id']; + $tor_type = $tor_info['tor_type']; - // Magnet link - $passkey = DB()->fetch_row("SELECT auth_key FROM ". BB_BT_USERS ." WHERE user_id = ". (int) $bt_user_id ." LIMIT 1"); - $tor_magnet = create_magnet($tor_info['info_hash'], $passkey['auth_key'], $userdata['session_logged_in']); + // Magnet link + $user_passkey = \TorrentPier\Legacy\Torrent::getPasskey($bt_user_id); + $tor_magnet = create_magnet($tor_info['info_hash'], $tor_info['info_hash_v2'], $user_passkey, html_ent_decode($t_data['topic_title']), $tor_size); - // ratio limits - $min_ratio_dl = $bb_cfg['bt_min_ratio_allow_dl_tor']; - $min_ratio_warn = $bb_cfg['bt_min_ratio_warning']; - $dl_allowed = true; - $user_ratio = 0; + // ratio limits + $min_ratio_dl = config()->get('bt_min_ratio_allow_dl_tor'); + $min_ratio_warn = config()->get('bt_min_ratio_warning'); + $dl_allowed = true; + $user_ratio = 0; - if (($min_ratio_dl || $min_ratio_warn) && $bt_user_id != $poster_id) - { - $sql = "SELECT u.*, dl.user_status - FROM ". BB_BT_USERS ." u - LEFT JOIN ". BB_BT_DLSTATUS ." dl ON dl.user_id = $bt_user_id AND dl.topic_id = $bt_topic_id + if (($min_ratio_dl || $min_ratio_warn) && ($bt_user_id != $poster_id && $bt_user_id != GUEST_UID)) { + $sql = "SELECT u.*, dl.user_status + FROM " . BB_BT_USERS . " u + LEFT JOIN " . BB_BT_DLSTATUS . " dl ON dl.user_id = $bt_user_id AND dl.topic_id = $bt_topic_id WHERE u.user_id = $bt_user_id LIMIT 1"; - } - else - { - $sql = "SELECT user_status - FROM ". BB_BT_DLSTATUS ." + } else { + $sql = "SELECT user_status + FROM " . BB_BT_DLSTATUS . " WHERE user_id = $bt_user_id AND topic_id = $bt_topic_id LIMIT 1"; - } + } - $bt_userdata = DB()->fetch_row($sql); + $bt_userdata = DB()->fetch_row($sql); + $user_status = $bt_userdata['user_status'] ?? null; - $user_status = isset($bt_userdata['user_status']) ? $bt_userdata['user_status'] : null; + if (($min_ratio_dl || $min_ratio_warn) && (isset($user_status) && $user_status != DL_STATUS_COMPLETE) && ($bt_user_id != $poster_id && $bt_user_id != GUEST_UID) && $tor_type != TOR_TYPE_GOLD) { + if (($user_ratio = get_bt_ratio($bt_userdata)) !== null) { + $dl_allowed = ($user_ratio > $min_ratio_dl); + } - if (($min_ratio_dl || $min_ratio_warn) && $user_status != DL_STATUS_COMPLETE && $bt_user_id != $poster_id && $tor_type != TOR_TYPE_GOLD) - { - if (($user_ratio = get_bt_ratio($bt_userdata)) !== null) - { - $dl_allowed = ($user_ratio > $min_ratio_dl); - } + if ((isset($user_ratio, $min_ratio_warn) && $user_ratio < $min_ratio_warn && TR_RATING_LIMITS) || ($bt_userdata['u_down_total'] < MIN_DL_FOR_RATIO)) { + $template->assign_vars([ + 'SHOW_RATIO_WARN' => true, + 'RATIO_WARN_MSG' => sprintf($lang['BT_RATIO_WARNING_MSG'], $min_ratio_dl, config()->get('ratio_url_help')), + ]); + } + } - if ((isset($user_ratio) && isset($min_ratio_warn) && $user_ratio < $min_ratio_warn && TR_RATING_LIMITS) || ($bt_userdata['u_down_total'] < MIN_DL_FOR_RATIO)) - { - $template->assign_vars(array( - 'SHOW_RATIO_WARN' => true, - 'RATIO_WARN_MSG' => sprintf($lang['BT_RATIO_WARNING_MSG'], $min_ratio_dl, $bb_cfg['ratio_url_help']), - )); - } - } + if (!$dl_allowed) { + $template->assign_block_vars('postrow.attach.tor_reged', []); + $template->assign_vars([ + 'TOR_BLOCKED' => true, + 'TOR_BLOCKED_MSG' => sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu=$bt_user_id&dlc=1"), + ]); + } else { + $template->assign_block_vars('postrow.attach.tor_reged', [ + 'DOWNLOAD_NAME' => $display_name, + 'TRACKER_LINK' => $tracker_link, + 'ATTACH_ID' => $attach_id, + 'TOR_SILVER_GOLD' => $tor_type, + 'TOR_TYPE' => is_gold($tor_type), - if (!$dl_allowed) - { - $template->assign_block_vars('postrow.attach.tor_reged', array()); - $template->assign_vars(array( - 'TOR_BLOCKED' => true, - 'TOR_BLOCKED_MSG' => sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu=$bt_user_id&dlc=1"), - )); - } - else - { - $template->assign_block_vars('postrow.attach.tor_reged', array( - 'DOWNLOAD_NAME' => $display_name, - 'TRACKER_LINK' => $tracker_link, - 'ATTACH_ID' => $attach_id, - 'TOR_SILVER_GOLD' => $tor_type, + // torrent status mod + 'TOR_FROZEN' => !IS_AM ? (isset(config()->get('tor_frozen')[$tor_info['tor_status']]) && !(isset(config()->get('tor_frozen_author_download')[$tor_info['tor_status']]) && $userdata['user_id'] == $tor_info['poster_id'])) ? true : '' : '', + 'TOR_STATUS_TEXT' => $lang['TOR_STATUS_NAME'][$tor_info['tor_status']], + 'TOR_STATUS_ICON' => config()->get('tor_icons')[$tor_info['tor_status']], + 'TOR_STATUS_BY' => ($tor_info['checked_user_id'] && ($is_auth['auth_mod'] || $tor_status_by_for_all)) ? (' · ' . profile_url($tor_info) . ' · ' . delta_time($tor_info['checked_time']) . $lang['TOR_BACK'] . '') : '', + 'TOR_STATUS_SELECT' => build_select('sel_status', array_flip($lang['TOR_STATUS_NAME']), TOR_APPROVED), + 'TOR_STATUS_REPLY' => config()->get('tor_comment') && !IS_GUEST && in_array($tor_info['tor_status'], config()->get('tor_reply')) && $userdata['user_id'] == $tor_info['poster_id'] && $t_data['topic_status'] != TOPIC_LOCKED, + //end torrent status mod - // torrent status mod - 'TOR_FROZEN' => (!IS_AM) ? (isset($bb_cfg['tor_frozen'][$tor_info['tor_status']]) && !(isset($bb_cfg['tor_frozen_author_download'][$tor_info['tor_status']]) && $userdata['user_id'] == $tor_info['poster_id'])) ? true : '' : '', - 'TOR_STATUS_TEXT' => $lang['TOR_STATUS_NAME'][$tor_info['tor_status']], - 'TOR_STATUS_ICON' => $bb_cfg['tor_icons'][$tor_info['tor_status']], - 'TOR_STATUS_BY' => ($tor_info['checked_user_id'] && $is_auth['auth_mod']) ? (' · '. profile_url($tor_info) .' · '. delta_time($tor_info['checked_time']) . $lang['TOR_BACK'] .'') : '', - 'TOR_STATUS_SELECT' => build_select('sel_status', array_flip($lang['TOR_STATUS_NAME']), TOR_APPROVED), - 'TOR_STATUS_REPLY' => $bb_cfg['tor_comment'] && !IS_GUEST && in_array($tor_info['tor_status'], $bb_cfg['tor_reply']) && $userdata['user_id'] == $tor_info['poster_id'] && $t_data['topic_status'] != TOPIC_LOCKED, - //end torrent status mod + 'S_UPLOAD_IMAGE' => $upload_image, + 'U_DOWNLOAD_LINK' => $download_link, + 'DL_LINK_CLASS' => isset($bt_userdata['user_status']) ? $dl_link_css[$bt_userdata['user_status']] : 'genmed', + 'DL_TITLE_CLASS' => isset($bt_userdata['user_status']) ? $dl_status_css[$bt_userdata['user_status']] : 'gen', + 'FILESIZE' => $tor_file_size, + 'MAGNET' => $tor_magnet, + 'HASH' => !empty($tor_info['info_hash']) ? strtoupper(bin2hex($tor_info['info_hash'])) : false, + 'HASH_V2' => !empty($tor_info['info_hash_v2']) ? strtoupper(bin2hex($tor_info['info_hash_v2'])) : false, + 'FILELIST_ICON' => $images['icon_tor_filelist'], + 'REGED_TIME' => bb_date($tor_info['reg_time']), + 'REGED_DELTA' => delta_time($tor_info['reg_time']), + 'TORRENT_SIZE' => humn_size($tor_size, 2), + 'DOWNLOAD_COUNT' => $download_count, + 'COMPLETED' => $tor_completed_count, + ]); - 'S_UPLOAD_IMAGE' => $upload_image, - 'U_DOWNLOAD_LINK' => $download_link, - 'DL_LINK_CLASS' => (isset($bt_userdata['user_status'])) ? $dl_link_css[$bt_userdata['user_status']] : 'genmed', - 'DL_TITLE_CLASS' => (isset($bt_userdata['user_status'])) ? $dl_status_css[$bt_userdata['user_status']] : 'gen', - 'FILESIZE' => $tor_file_size, - 'MAGNET' => $tor_magnet, - 'HASH' => strtoupper(bin2hex($tor_info['info_hash'])), - 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $download_count), - 'REGED_TIME' => bb_date($tor_info['reg_time']), - 'REGED_DELTA' => delta_time($tor_info['reg_time']), - 'TORRENT_SIZE' => humn_size($tor_size), - 'COMPLETED' => sprintf($lang['DOWNLOAD_NUMBER'], $tor_info['complete_count']), - )); + // TorrServer integration + if (config()->get('torr_server.enabled') && (!IS_GUEST || !config()->get('torr_server.disable_for_guest')) && (new \TorrentPier\TorrServerAPI())->getM3UPath($attach_id)) { + $template->assign_block_vars('postrow.attach.tor_reged.tor_server', [ + 'TORR_SERVER_M3U_LINK' => PLAYBACK_M3U_URL . $bt_topic_id, + 'TORR_SERVER_M3U_ICON' => $images['icon_tor_m3u_icon'], + ]); + } - if ($comment) - { - $template->assign_block_vars('postrow.attach.tor_reged.comment', array('COMMENT' => $comment)); - } - } + if ($comment) { + $template->assign_block_vars('postrow.attach.tor_reged.comment', ['COMMENT' => $comment]); + } + } - if ($bb_cfg['show_tor_info_in_dl_list']) - { - $template->assign_vars(array( - 'SHOW_DL_LIST' => true, - 'SHOW_DL_LIST_TOR_INFO' => true, + if (config()->get('show_tor_info_in_dl_list')) { + $template->assign_vars([ + 'SHOW_DL_LIST' => true, + 'SHOW_DL_LIST_TOR_INFO' => true, - 'TOR_SIZE' => humn_size($tor_size), - 'TOR_LONGEVITY' => delta_time($tor_info['reg_time']), - 'TOR_COMPLETED' => declension($tor_info['complete_count'], 'times'), - )); - } + 'TOR_SIZE' => humn_size($tor_size, 2), + 'TOR_LONGEVITY' => delta_time($tor_info['reg_time']), + 'TOR_DOWNLOAD_COUNT' => $download_count, + 'TOR_COMPLETED' => $tor_completed_count, + ]); + } - // Show peers - if ($show_peers) - { - // Sorting order in full mode - if ($s_mode == 'full') - { - $full_mode_order = 'tr.remain'; - $full_mode_sort_dir = 'ASC'; + // Show peers + if ($show_peers) { + // Sorting order in full mode + if ($s_mode == 'full') { + $full_mode_order = 'tr.remain'; + $full_mode_sort_dir = 'ASC'; - if (isset($_REQUEST['psortasc'])) - { - $full_mode_sort_dir = 'ASC'; - } - else if (isset($_REQUEST['psortdesc'])) - { - $full_mode_sort_dir = 'DESC'; - } + if (isset($_REQUEST['psortdesc'])) { + $full_mode_sort_dir = 'DESC'; + } - if (isset($_REQUEST['porder'])) - { - $peer_orders = array( - 'name' => 'u.username', - 'ip' => 'tr.ip', - 'port' => 'tr.port', - 'compl' => 'tr.remain', - 'cup' => 'tr.uploaded', - 'cdown' => 'tr.downloaded', - 'sup' => 'tr.speed_up', - 'sdown' => 'tr.speed_down', - 'time' => 'tr.update_time', - ); + if (isset($_REQUEST['porder'])) { + $peer_orders = [ + 'name' => 'u.username', + 'ip' => 'tr.ip', + 'port' => 'tr.port', + 'compl' => 'tr.remain', + 'cup' => 'tr.uploaded', + 'cdown' => 'tr.downloaded', + 'sup' => 'tr.speed_up', + 'sdown' => 'tr.speed_down', + 'time' => 'tr.update_time', + 'peer_id' => 'tr.peer_id', + ]; - foreach ($peer_orders as $get_key => $order_by_value) - { - if ($_REQUEST['porder'] == $get_key) - { - $full_mode_order = $order_by_value; - break; - } - } - } - } - // SQL for each mode - if ($s_mode == 'count') - { - $sql = "SELECT seeders, leechers, speed_up, speed_down - FROM ". BB_BT_TRACKER_SNAP ." + foreach ($peer_orders as $get_key => $order_by_value) { + if ($_REQUEST['porder'] == $get_key) { + $full_mode_order = $order_by_value; + break; + } + } + } + } + // SQL for each mode + if ($s_mode == 'count') { + $sql = "SELECT seeders, leechers, speed_up, speed_down + FROM " . BB_BT_TRACKER_SNAP . " WHERE topic_id = $tor_id LIMIT 1"; - } - else if ($s_mode == 'names') - { - $sql = "SELECT tr.user_id, tr.ip, tr.port, tr.remain, tr.seeder, u.username, u.user_rank - FROM ". BB_BT_TRACKER ." tr, ". BB_USERS ." u + } elseif ($s_mode == 'names') { + $sql = "SELECT tr.user_id, tr.ip, tr.ipv6, tr.port, tr.remain, tr.seeder, u.username, u.user_rank + FROM " . BB_BT_TRACKER . " tr, " . BB_USERS . " u WHERE tr.topic_id = $tor_id AND u.user_id = tr.user_id - GROUP BY tr.ip, tr.user_id, tr.port, tr.seeder ORDER BY u.username LIMIT $show_peers_limit"; - } - else - { - $sql = "SELECT - tr.user_id, tr.ip, tr.port, tr.uploaded, tr.downloaded, tr.remain, + } else { + $sql = "SELECT + tr.user_id, tr.ip, tr.ipv6, tr.port, tr.peer_id, tr.uploaded, tr.downloaded, tr.remain, tr.seeder, tr.releaser, tr.speed_up, tr.speed_down, tr.update_time, - tr.complete_percent, u.username, u.user_rank - FROM ". BB_BT_TRACKER ." tr - LEFT JOIN ". BB_USERS ." u ON u.user_id = tr.user_id + tr.complete_percent, u.username, u.user_rank, u.user_opt + FROM " . BB_BT_TRACKER . " tr + LEFT JOIN " . BB_USERS . " u ON u.user_id = tr.user_id WHERE tr.topic_id = $tor_id - GROUP BY tr.ip, tr.user_id, tr.port, tr.seeder ORDER BY $full_mode_order $full_mode_sort_dir LIMIT $show_peers_limit"; - } + } - // Build peers table - if ($peers = DB()->fetch_rowset($sql)) - { - $peers_cnt = count($peers); + // Build peers table + if ($peers = DB()->fetch_rowset($sql)) { + $peers_cnt = count($peers); - $cnt = $tr = $sp_up = $sp_down = $sp_up_tot = $sp_down_tot = array(); - $cnt['s'] = $tr['s'] = $sp_up['s'] = $sp_down['s'] = $sp_up_tot['s'] = $sp_down_tot['s'] = 0; - $cnt['l'] = $tr['l'] = $sp_up['l'] = $sp_down['l'] = $sp_up_tot['l'] = $sp_down_tot['l'] = 0; + $cnt = $tr = $sp_up = $sp_down = $sp_up_tot = $sp_down_tot = []; + $cnt['s'] = $tr['s'] = $sp_up['s'] = $sp_down['s'] = $sp_up_tot['s'] = $sp_down_tot['s'] = 0; + $cnt['l'] = $tr['l'] = $sp_up['l'] = $sp_down['l'] = $sp_up_tot['l'] = $sp_down_tot['l'] = 0; - $max_up = $max_down = $max_sp_up = $max_sp_down = array(); - $max_up['s'] = $max_down['s'] = $max_sp_up['s'] = $max_sp_down['s'] = 0; - $max_up['l'] = $max_down['l'] = $max_sp_up['l'] = $max_sp_down['l'] = 0; - $max_up_id['s'] = $max_down_id['s'] = $max_sp_up_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); - $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); + $max_up = $max_down = $max_sp_up = $max_sp_down = []; + $max_up['s'] = $max_down['s'] = $max_sp_up['s'] = $max_sp_down['s'] = 0; + $max_up['l'] = $max_down['l'] = $max_sp_up['l'] = $max_sp_down['l'] = 0; + $max_up_id['s'] = $max_down_id['s'] = $max_sp_up_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); + $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); - if ($s_mode == 'full') - { - foreach ($peers as $pid => $peer) - { - $x = ($peer['seeder']) ? 's' : 'l'; - $cnt[$x]++; - $sp_up_tot[$x] += $peer['speed_up']; - $sp_down_tot[$x] += $peer['speed_down']; + if ($s_mode == 'full') { + foreach ($peers as $pid => $peer) { + $x = ($peer['seeder']) ? 's' : 'l'; + $cnt[$x]++; + $sp_up_tot[$x] += $peer['speed_up']; + $sp_down_tot[$x] += $peer['speed_down']; - $guest = ($peer['user_id'] == GUEST_UID || is_null($peer['username'])); - $p_max_up = $peer['uploaded']; - $p_max_down = $peer['downloaded']; + $guest = ($peer['user_id'] == GUEST_UID || null === $peer['username']); + $p_max_up = $peer['uploaded']; + $p_max_down = $peer['downloaded']; - if ($p_max_up > $max_up[$x]) - { - $max_up[$x] = $p_max_up; - $max_up_id[$x] = $pid; - } - if ($peer['speed_up'] > $max_sp_up[$x]) - { - $max_sp_up[$x] = $peer['speed_up']; - $max_sp_up_id[$x] = $pid; - } - if ($p_max_down > $max_down[$x]) - { - $max_down[$x] = $p_max_down; - $max_down_id[$x] = $pid; - } - if ($peer['speed_down'] > $max_sp_down[$x]) - { - $max_sp_down[$x] = $peer['speed_down']; - $max_sp_down_id[$x] = $pid; - } - } - $max_down_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); + if ($p_max_up > $max_up[$x]) { + $max_up[$x] = $p_max_up; + $max_up_id[$x] = $pid; + } + if ($peer['speed_up'] > $max_sp_up[$x]) { + $max_sp_up[$x] = $peer['speed_up']; + $max_sp_up_id[$x] = $pid; + } + if ($p_max_down > $max_down[$x]) { + $max_down[$x] = $p_max_down; + $max_down_id[$x] = $pid; + } + if ($peer['speed_down'] > $max_sp_down[$x]) { + $max_sp_down[$x] = $peer['speed_down']; + $max_sp_down_id[$x] = $pid; + } + } + $max_down_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); - if ($cnt['s'] == 1) - { - $max_up_id['s'] = $max_sp_up_id['s'] = ($peers_cnt + 1); - } - if ($cnt['l'] == 1) - { - $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); - } - } + if ($cnt['s'] == 1) { + $max_up_id['s'] = $max_sp_up_id['s'] = ($peers_cnt + 1); + } + if ($cnt['l'] == 1) { + $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); + } + } - if ($s_mode == 'count') - { - $tmp = array(); - $tmp[0]['seeder'] = $tmp[0]['username'] = $tmp[1]['username'] = 0; - $tmp[1]['seeder'] = 1; - $tmp[0]['username'] = (int) @$peers[0]['leechers']; - $tmp[1]['username'] = (int) @$peers[0]['seeders']; - $tor_speed_up = (int) @$peers[0]['speed_up']; - $tor_speed_down = (int) @$peers[0]['speed_down']; - $peers = $tmp; + if ($s_mode == 'count') { + $tmp = []; + $tmp[0]['seeder'] = $tmp[0]['username'] = $tmp[1]['username'] = 0; + $tmp[1]['seeder'] = 1; + $tmp[0]['username'] = (int)@$peers[0]['leechers']; + $tmp[1]['username'] = (int)@$peers[0]['seeders']; + $tor_speed_up = (int)@$peers[0]['speed_up']; + $tor_speed_down = (int)@$peers[0]['speed_down']; + $peers = $tmp; - $template->assign_vars(array( - 'TOR_SPEED_UP' => ($tor_speed_up) ? humn_size($tor_speed_up, 0, 'KB') .'/s' : '0 KB/s', - 'TOR_SPEED_DOWN' => ($tor_speed_down) ? humn_size($tor_speed_down, 0, 'KB') .'/s' : '0 KB/s', - )); - } + $template->assign_vars([ + 'TOR_SPEED_UP' => ($tor_speed_up) ? humn_size($tor_speed_up, min: 'KB') . '/s' : '0 KB/s', + 'TOR_SPEED_DOWN' => ($tor_speed_down) ? humn_size($tor_speed_down, min: 'KB') . '/s' : '0 KB/s' + ]); + } - foreach ($peers as $pid => $peer) - { - $u_prof_href = ($s_mode == 'count') ? '#' : "profile.php?mode=viewprofile&u=". $peer['user_id'] ."#torrent"; + foreach ($peers as $pid => $peer) { + $u_prof_href = ($s_mode == 'count') ? '#' : PROFILE_URL . $peer['user_id'] . "#torrent"; - // Full details mode - if ($s_mode == 'full') - { - $ip = bt_show_ip($peer['ip']); - $port = bt_show_port($peer['port']); + // Full details mode + if ($s_mode == 'full') { + if (!empty($peer['ip']) && !empty($peer['ipv6'])) { + if ($ip = bt_show_ip($peer['ipv6'])) { + $ip .= ' (' . bt_show_ip($peer['ip']) . ')'; + } + } else { + $ip = bt_show_ip(!empty($peer['ipv6']) ? $peer['ipv6'] : $peer['ip']); + } + $port = bt_show_port($peer['port']); - // peer max/current up/down - $p_max_up = $peer['uploaded']; - $p_max_down = $peer['downloaded']; - $p_cur_up = $peer['uploaded']; - $p_cur_down = $peer['downloaded']; + // peer max/current up/down + $p_max_up = $peer['uploaded']; + $p_max_down = $peer['downloaded']; + $p_cur_up = $peer['uploaded']; + $p_cur_down = $peer['downloaded']; - if ($peer['seeder']) - { - $x = 's'; - $x_row = 'srow'; - $x_full = 'sfull'; + if ($peer['seeder']) { + $x = 's'; + $x_row = 'srow'; + $x_full = 'sfull'; - if (!defined('SEEDER_EXIST')) - { - define('SEEDER_EXIST', true); - $seed_order_action = "viewtopic.php?". POST_TOPIC_URL ."=$bt_topic_id&spmode=full#seeders"; + if (!defined('SEEDER_EXIST')) { + define('SEEDER_EXIST', true); + $seed_order_action = TOPIC_URL . "$bt_topic_id&spmode=full#seeders"; - $template->assign_block_vars("$x_full", array( - 'SEED_ORD_ACT' => $seed_order_action, - 'SEEDERS_UP_TOT' => humn_size($sp_up_tot[$x], 0, 'KB') .'/s' - )); + $template->assign_block_vars((string)$x_full, [ + 'SEED_ORD_ACT' => $seed_order_action, + 'SEEDERS_UP_TOT' => humn_size($sp_up_tot[$x], min: 'KB') . '/s' + ]); - if ($ip) - { - $template->assign_block_vars("$x_full.iphead", array()); - } - if ($port !== false) - { - $template->assign_block_vars("$x_full.porthead", array()); - } - } - $compl_perc = ($tor_size) ? round(($p_max_up / $tor_size), 1) : 0; - } - else - { - $x = 'l'; - $x_row = 'lrow'; - $x_full = 'lfull'; + if ($ip) { + $template->assign_block_vars("$x_full.iphead", []); + } + if ($port !== false) { + $template->assign_block_vars("$x_full.porthead", []); + } + } + $compl_perc = ($tor_size) ? round(($p_max_up / $tor_size), 1) : 0; + } else { + $x = 'l'; + $x_row = 'lrow'; + $x_full = 'lfull'; - if (!defined('LEECHER_EXIST')) - { - define('LEECHER_EXIST', true); - $leech_order_action = "viewtopic.php?". POST_TOPIC_URL ."=$bt_topic_id&spmode=full#leechers"; + if (!defined('LEECHER_EXIST')) { + define('LEECHER_EXIST', true); + $leech_order_action = TOPIC_URL . "$bt_topic_id&spmode=full#leechers"; - $template->assign_block_vars("$x_full", array( - 'LEECH_ORD_ACT' => $leech_order_action, - 'LEECHERS_UP_TOT' => humn_size($sp_up_tot[$x], 0, 'KB') .'/s', - 'LEECHERS_DOWN_TOT' => humn_size($sp_down_tot[$x], 0, 'KB') .'/s' - )); + $template->assign_block_vars((string)$x_full, [ + 'LEECH_ORD_ACT' => $leech_order_action, + 'LEECHERS_UP_TOT' => humn_size($sp_up_tot[$x], min: 'KB') . '/s', + 'LEECHERS_DOWN_TOT' => humn_size($sp_down_tot[$x], min: 'KB') . '/s' + ]); - if ($ip) - { - $template->assign_block_vars("$x_full.iphead", array()); - } - if ($port !== false) - { - $template->assign_block_vars("$x_full.porthead", array()); - } - } - $compl_size = ($peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; - $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; - } + if ($ip) { + $template->assign_block_vars("$x_full.iphead", []); + } + if ($port !== false) { + $template->assign_block_vars("$x_full.porthead", []); + } + } + $compl_size = ($peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; + $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; + } - $rel_sign = (!$guest && $peer['releaser']) ? ' ®' : ''; - $name = profile_url($peer). $rel_sign; - $up_tot = ($p_max_up) ? humn_size($p_max_up) : '-'; - $down_tot = ($p_max_down) ? humn_size($p_max_down) : '-'; - $up_ratio = ($p_max_down) ? round(($p_max_up / $p_max_down), 2) : ''; - $sp_up = ($peer['speed_up']) ? humn_size($peer['speed_up'], 0, 'KB') .'/s' : '-'; - $sp_down = ($peer['speed_down']) ? humn_size($peer['speed_down'], 0, 'KB') .'/s' : '-'; + $up_tot = ($p_max_up) ? humn_size($p_max_up) : '-'; + $down_tot = ($p_max_down) ? humn_size($p_max_down) : '-'; + $up_ratio = ($p_max_down) ? round(($p_max_up / $p_max_down), 2) : ''; + $sp_up = ($peer['speed_up']) ? humn_size($peer['speed_up'], min: 'KB') . '/s' : '-'; + $sp_down = ($peer['speed_down']) ? humn_size($peer['speed_down'], min: 'KB') . '/s' : '-'; - $bgr_class = (!($tr[$x] % 2)) ? $bgr_class_1 : $bgr_class_2; - $row_bgr = ($change_peers_bgr_over) ? " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\"" : ''; - $tr[$x]++; + $bgr_class = (!($tr[$x] % 2)) ? $bgr_class_1 : $bgr_class_2; + $row_bgr = ($change_peers_bgr_over) ? " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\"" : ''; + $tr[$x]++; - $template->assign_block_vars("$x_full.$x_row", array( - 'ROW_BGR' => $row_bgr, - 'NAME' => ($peer['update_time']) ? $name : "$name", - 'COMPL_PRC' => $compl_perc, - 'UP_TOTAL' => ($max_up_id[$x] == $pid) ? "$up_tot" : $up_tot, - 'DOWN_TOTAL' => ($max_down_id[$x] == $pid) ? "$down_tot" : $down_tot, - 'SPEED_UP' => ($max_sp_up_id[$x] == $pid) ? "$sp_up" : $sp_up, - 'SPEED_DOWN' => ($max_sp_down_id[$x] == $pid) ? "$sp_down" : $sp_down, - 'UP_TOTAL_RAW' => $peer['uploaded'], - 'DOWN_TOTAL_RAW' => $peer['downloaded'], - 'SPEED_UP_RAW' => $peer['speed_up'], - 'SPEED_DOWN_RAW' => $peer['speed_down'], - 'UPD_EXP_TIME' => ($peer['update_time']) ? $lang['DL_UPD'] . bb_date($peer['update_time'], 'd-M-y H:i') .' · '. delta_time($peer['update_time']) . $lang['TOR_BACK'] : $lang['DL_STOPPED'], - 'TOR_RATIO' => ($up_ratio) ? $lang['USER_RATIO'] . "UL/DL: $up_ratio" : '', - )); + $peerUsername = $lang['HIDDEN_USER']; + if (IS_AM || $peer['user_id'] == $userdata['user_id'] || !bf($peer['user_opt'], 'user_opt', 'user_hide_peer_username')) { + $releaserSign = (!$guest && $peer['releaser']) ? ' ®' : ''; + $peerUsername = profile_url($peer) . $releaserSign; + $peerUsername = $peer['update_time'] ? $peerUsername : "$peerUsername"; + } - if ($ip) - { - $template->assign_block_vars("$x_full.$x_row.ip", array('IP' => $ip)); - } - if ($port !== false) - { - $template->assign_block_vars("$x_full.$x_row.port", array('PORT' => $port)); - } - } - // Count only & only names modes - else - { - if ($peer['seeder']) - { - $seeders .= ''. $peer['username'] .', '; - $seed_count = $peer['username']; - } - else - { - $compl_size = (@$peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; - $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; + $peerTorrentClient = $lang['HIDDEN_USER']; + if (IS_AM || $peer['user_id'] == $userdata['user_id'] || !bf($peer['user_opt'], 'user_opt', 'user_hide_torrent_client')) { + if (isset($peer['peer_id'])) { + $peerTorrentClient = get_user_torrent_client($peer['peer_id']); + } + } - $leechers .= ''. $peer['username'] .''; - $leechers .= ($s_mode == 'names') ? ' ['. $compl_perc .'%]' : ''; - $leechers .= ', '; - $leech_count = $peer['username']; - } - } - } + $peerCountry = $lang['HIDDEN_USER']; + if (config()->get('ip2country_settings.enabled')) { + if (IS_AM || $peer['user_id'] == $userdata['user_id'] || !bf($peer['user_opt'], 'user_opt', 'user_hide_peer_country')) { + if ($infoByIP = infoByIP((!empty($peer['ipv6']) ? $peer['ipv6'] : $peer['ip']), $peer['port'])) { + if (!empty($infoByIP['countryCode'])) { + $peerCountry = render_flag($infoByIP['countryCode'], false); + } else { + $peerCountry = $lang['NOT_AVAILABLE']; + } + } + } + } - if ($s_mode != 'full' && $seeders) - { - $seeders[strlen($seeders)-9] = ' '; - $template->assign_vars(array( - 'SEED_LIST' => $seeders, - 'SEED_COUNT' => ($seed_count) ? $seed_count : 0, - )); - } - if ($s_mode != 'full' && $leechers) - { - $leechers[strlen($leechers)-9] = ' '; - $template->assign_vars(array( - 'LEECH_LIST' => $leechers, - 'LEECH_COUNT' => ($leech_count) ? $leech_count : 0, - )); - } - } - unset($peers); + $template->assign_block_vars("$x_full.$x_row", [ + 'ROW_BGR' => $row_bgr, + 'NAME' => $peerUsername, + 'PEER_ID' => $peerTorrentClient, + 'COUNTRY' => $peerCountry, + 'COMPL_PRC' => $compl_perc, + 'UP_TOTAL' => ($max_up_id[$x] == $pid) ? "$up_tot" : $up_tot, + 'DOWN_TOTAL' => ($max_down_id[$x] == $pid) ? "$down_tot" : $down_tot, + 'SPEED_UP' => ($max_sp_up_id[$x] == $pid) ? "$sp_up" : $sp_up, + 'SPEED_DOWN' => ($max_sp_down_id[$x] == $pid) ? "$sp_down" : $sp_down, + 'UP_TOTAL_RAW' => $peer['uploaded'], + 'DOWN_TOTAL_RAW' => $peer['downloaded'], + 'SPEED_UP_RAW' => $peer['speed_up'], + 'SPEED_DOWN_RAW' => $peer['speed_down'], + 'UPD_EXP_TIME' => $peer['update_time'] ? $lang['DL_UPD'] . bb_date($peer['update_time'], 'd-M-y H:i') . ' · ' . delta_time($peer['update_time']) . $lang['TOR_BACK'] : $lang['DL_STOPPED'], + 'TOR_RATIO' => $up_ratio ? $lang['USER_RATIO'] . "UL/DL: $up_ratio" : '' + ]); - // Show "seeder last seen info" - if (($s_mode == 'count' && !$seed_count) || (!$seeders && !defined('SEEDER_EXIST'))) - { - $last_seen_time = ($tor_info['seeder_last_seen']) ? delta_time($tor_info['seeder_last_seen']) : $lang['NEVER']; + if ($ip) { + $template->assign_block_vars("$x_full.$x_row.ip", [ + 'U_WHOIS_IP' => config()->get('whois_info') . $ip, + 'IP' => $ip + ]); + } + if ($port !== false) { + $template->assign_block_vars("$x_full.$x_row.port", ['PORT' => $port]); + } + } // Count only & only names modes + else { + if ($peer['seeder']) { + $seeders .= '' . $peer['username'] . ', '; + $seed_count = $peer['username']; + } else { + $compl_size = (@$peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; + $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; - $template->assign_vars(array( - 'SEEDER_LAST_SEEN' => sprintf($lang['SEEDER_LAST_SEEN'], $last_seen_time), - )); - } - } + $leechers .= '' . $peer['username'] . ''; + $leechers .= ($s_mode == 'names') ? ' [' . $compl_perc . '%]' : ''; + $leechers .= ', '; + $leech_count = $peer['username']; + } + } + } - $template->assign_block_vars('tor_title', array('U_DOWNLOAD_LINK' => $download_link)); + if ($s_mode != 'full' && $seeders) { + $seeders[strlen($seeders) - 9] = ' '; + $template->assign_vars([ + 'SEED_LIST' => $seeders, + 'SEED_COUNT' => ($seed_count) ?: 0, + ]); + } + if ($s_mode != 'full' && $leechers) { + $leechers[strlen($leechers) - 9] = ' '; + $template->assign_vars([ + 'LEECH_LIST' => $leechers, + 'LEECH_COUNT' => ($leech_count) ?: 0, + ]); + } + } + unset($peers); - if ($peers_cnt > $max_peers_before_overflow && $s_mode == 'full') - { - $template->assign_vars(array('PEERS_DIV_STYLE' => $peers_div_style_overflow)); - $template->assign_vars(array('PEERS_OVERFLOW' => true)); - } - else - { - $template->assign_vars(array('PEERS_DIV_STYLE' => $peers_div_style_normal)); - } + // Show "seeder last seen info" + if (($s_mode == 'count' && !$seed_count) || (!$seeders && !defined('SEEDER_EXIST'))) { + $last_seen_time = ($tor_info['seeder_last_seen']) ? delta_time($tor_info['seeder_last_seen']) : $lang['NEVER']; + $last_seeder_username = (!empty($tor_info['last_seeder_id']) && $last_seeder = get_userdata($tor_info['last_seeder_id'])) ? ' -> ' . profile_url(['username' => $last_seeder['username'], 'user_id' => $last_seeder['user_id'], 'user_rank' => $last_seeder['user_rank']]) . '' : ($tor_info['last_seeder_id'] < 0 ? ' -> ' . $lang['GUEST'] : ''); + + $template->assign_vars(['SEEDER_LAST_SEEN' => sprintf($lang['SEEDER_LAST_SEEN'], $last_seen_time)]); + $template->assign_vars(['SEEDER_USERNAME' => $last_seeder_username]); + } + } + + $template->assign_block_vars('tor_title', ['U_DOWNLOAD_LINK' => $download_link]); + + if ($peers_cnt > $max_peers_before_overflow && $s_mode == 'full') { + $template->assign_vars([ + 'PEERS_OVERFLOW' => true, + 'PEERS_DIV_STYLE' => $peers_div_style_overflow + ]); + } else { + $template->assign_vars(['PEERS_DIV_STYLE' => $peers_div_style_normal]); + } } -if ($bb_cfg['bt_allow_spmode_change'] && $s_mode != 'full') -{ - $template->assign_vars(array( - 'PEERS_FULL_LINK' => true, - 'SPMODE_FULL_HREF' => "viewtopic.php?". POST_TOPIC_URL ."=$bt_topic_id&spmode=full#seeders", - )); +if (config()->get('bt_allow_spmode_change') && $s_mode != 'full') { + $template->assign_vars([ + 'PEERS_FULL_LINK' => true, + 'SPMODE_FULL_HREF' => TOPIC_URL . "$bt_topic_id&spmode=full#seeders" + ]); } -$template->assign_vars(array( - 'SHOW_DL_LIST_LINK' => (($bb_cfg['bt_show_dl_list'] || $bb_cfg['allow_dl_list_names_mode']) && $t_data['topic_dl_type'] == TOPIC_DL_TYPE_DL), - 'SHOW_TOR_ACT' => ($tor_reged && $show_peers && (!isset($bb_cfg['tor_no_tor_act'][$tor_info['tor_status']]) || IS_AM)), - 'S_MODE_COUNT' => ($s_mode == 'count'), - 'S_MODE_NAMES' => ($s_mode == 'names'), - 'S_MODE_FULL' => ($s_mode == 'full'), - 'PEER_EXIST' => ($seeders || $leechers || defined('SEEDER_EXIST') || defined('LEECHER_EXIST')), - 'SEED_EXIST' => ($seeders || defined('SEEDER_EXIST')), - 'LEECH_EXIST' => ($leechers || defined('LEECHER_EXIST')), - 'TOR_HELP_LINKS' => $bb_cfg['tor_help_links'], - 'CALL_SEED' => ($bb_cfg['callseed'] && $tor_reged && !isset($bb_cfg['tor_no_tor_act'][$tor_info['tor_status']]) && $seed_count < 3 && $tor_info['call_seed_time'] < (TIMENOW - 86400)), -)); \ No newline at end of file +$template->assign_vars([ + 'SHOW_DL_LIST_LINK' => ((config()->get('bt_show_dl_list') || config()->get('allow_dl_list_names_mode')) && $t_data['topic_dl_type'] == TOPIC_DL_TYPE_DL), + 'SHOW_TOR_ACT' => ($tor_reged && $show_peers && (!isset(config()->get('tor_no_tor_act')[$tor_info['tor_status']]) || IS_AM)), + 'S_MODE_COUNT' => ($s_mode == 'count'), + 'S_MODE_NAMES' => ($s_mode == 'names'), + 'S_MODE_FULL' => ($s_mode == 'full'), + 'PEER_EXIST' => ($seeders || $leechers || defined('SEEDER_EXIST') || defined('LEECHER_EXIST')), + 'SEED_EXIST' => ($seeders || defined('SEEDER_EXIST')), + 'LEECH_EXIST' => ($leechers || defined('LEECHER_EXIST')), + 'TOR_HELP_LINKS' => config()->get('tor_help_links'), + 'CALL_SEED' => (!IS_GUEST && config()->get('callseed') && $tor_reged && !isset(config()->get('tor_no_tor_act')[$tor_info['tor_status']]) && $seed_count < 3 && $tor_info['call_seed_time'] < (TIMENOW - 86400)), +]); diff --git a/library/attach_mod/includes/.htaccess b/library/attach_mod/includes/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/library/attach_mod/includes/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/library/attach_mod/includes/functions_admin.php b/library/attach_mod/includes/functions_admin.php index 2f0b0a4c3..17cb68571 100644 --- a/library/attach_mod/includes/functions_admin.php +++ b/library/attach_mod/includes/functions_admin.php @@ -1,353 +1,247 @@ sql_query($sql)) { + bb_die('Could not get entry #1'); + } - if( !($result = DB()->sql_query($sql)) ) - { - bb_die('Could not get entry #1'); - } - - if (DB()->num_rows($result) == 0) - { - $sql_ary = array( - 'user_id' => (int) $id, - 'group_id' => 0, - 'quota_type' => (int) $quota_type, - 'quota_limit_id'=> (int) $quota_limit_id - ); - - $sql = 'INSERT INTO ' . BB_QUOTA . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - } - else - { - $sql = 'UPDATE ' . BB_QUOTA . " + if (DB()->num_rows($result) == 0) { + $sql_ary = [ + 'user_id' => (int)$id, + 'group_id' => 0, + 'quota_type' => (int)$quota_type, + 'quota_limit_id' => (int)$quota_limit_id + ]; + $sql = 'INSERT INTO ' . BB_QUOTA . ' ' . DB()->build_array('INSERT', $sql_ary); + } else { + $sql = 'UPDATE ' . BB_QUOTA . " SET quota_limit_id = $quota_limit_id WHERE user_id = $id AND quota_type = $quota_type"; - } - DB()->sql_freeresult($result); - } + } + DB()->sql_freeresult($result); + } - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to update quota settings'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to update quota settings'); + } + } elseif ($mode == 'group') { + if (!$quota_limit_id) { + $sql = 'DELETE FROM ' . BB_QUOTA . " WHERE group_id = $id AND quota_type = $quota_type"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Unable to delete quota settings'); + } + } else { + // Check if user is already entered + $sql = 'SELECT group_id FROM ' . BB_QUOTA . " WHERE group_id = $id AND quota_type = $quota_type"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get entry #2'); + } - } - else if ($mode == 'group') - { - if (!$quota_limit_id) - { - $sql = 'DELETE FROM ' . BB_QUOTA . " - WHERE group_id = $id - AND quota_type = $quota_type"; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to delete quota settings'); - } - } - else - { - // Check if user is already entered - $sql = 'SELECT group_id - FROM ' . BB_QUOTA . " - WHERE group_id = $id - AND quota_type = $quota_type"; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get entry #2'); - } - - if (DB()->num_rows($result) == 0) - { - $sql = 'INSERT INTO ' . BB_QUOTA . " (user_id, group_id, quota_type, quota_limit_id) + if (DB()->num_rows($result) == 0) { + $sql = 'INSERT INTO ' . BB_QUOTA . " (user_id, group_id, quota_type, quota_limit_id) VALUES (0, $id, $quota_type, $quota_limit_id)"; - } - else - { - $sql = 'UPDATE ' . BB_QUOTA . " SET quota_limit_id = $quota_limit_id + } else { + $sql = 'UPDATE ' . BB_QUOTA . " SET quota_limit_id = $quota_limit_id WHERE group_id = $id AND quota_type = $quota_type"; - } + } - if (!DB()->sql_query($sql)) - { - bb_die('Unable to update quota settings'); - } - } - } + if (!DB()->sql_query($sql)) { + bb_die('Unable to update quota settings'); + } + } + } } /** -* sort multi-dimensional Array -*/ -function sort_multi_array ($sort_array, $key, $sort_order, $pre_string_sort = 0) + * Sort multi-dimensional array + * + * @param array $sort_array + * @param string|int $key + * @param int $sort_order + * @return array + */ +function sort_multi_array(array $sort_array, $key, int $sort_order = SORT_ASC): array { - $last_element = sizeof($sort_array) - 1; + $keys = array_column($sort_array, $key); + array_multisort($keys, $sort_order, $sort_array); - if (!$pre_string_sort) - { - $string_sort = (!is_numeric(@$sort_array[$last_element-1][$key]) ) ? true : false; - } - else - { - $string_sort = $pre_string_sort; - } - - for ($i = 0; $i < $last_element; $i++) - { - $num_iterations = $last_element - $i; - - for ($j = 0; $j < $num_iterations; $j++) - { - $next = 0; - - // do checks based on key - $switch = false; - if (!$string_sort) - { - if (($sort_order == 'DESC' && intval(@$sort_array[$j][$key]) < intval(@$sort_array[$j + 1][$key])) || ($sort_order == 'ASC' && intval(@$sort_array[$j][$key]) > intval(@$sort_array[$j + 1][$key]))) - { - $switch = true; - } - } - else - { - if (($sort_order == 'DESC' && strcasecmp(@$sort_array[$j][$key], @$sort_array[$j + 1][$key]) < 0) || ($sort_order == 'ASC' && strcasecmp(@$sort_array[$j][$key], @$sort_array[$j + 1][$key]) > 0)) - { - $switch = true; - } - } - - if ($switch) - { - $temp = $sort_array[$j]; - $sort_array[$j] = $sort_array[$j + 1]; - $sort_array[$j + 1] = $temp; - } - } - } - - return $sort_array; + return $sort_array; } /** -* Returns the filesize of the upload directory in human readable format -*/ + * Returns size of the upload directory in human readable format + * + * @return string + */ function get_formatted_dirsize() { - global $attach_config, $upload_dir, $lang; + global $lang, $upload_dir; - $upload_dir_size = 0; + $upload_dir_size = 0; - if ($dirname = @opendir($upload_dir)) - { - while ($file = @readdir($dirname)) - { - if ($file != 'index.php' && $file != '.htaccess' && !is_dir($upload_dir . '/' . $file) && !is_link($upload_dir . '/' . $file)) - { - $upload_dir_size += @filesize($upload_dir . '/' . $file); - } - } - @closedir($dirname); - } - else - { - $upload_dir_size = $lang['NOT_AVAILABLE']; - return $upload_dir_size; - } + if ($dirname = opendir($upload_dir)) { + while ($file = readdir($dirname)) { + if ( + $file != 'index.php' && + $file != '.htaccess' && + !is_dir($upload_dir . '/' . $file) && + !is_link($upload_dir . '/' . $file) + ) { + $upload_dir_size += filesize($upload_dir . '/' . $file); + } + } + closedir($dirname); + } else { + return $lang['NOT_AVAILABLE']; + } - return humn_size($upload_dir_size); -} - -/* -* Build SQL-Statement for the search feature -*/ -function search_attachments($order_by, &$total_rows) -{ - global $lang; - - $where_sql = array(); - - // Get submitted Vars - $search_vars = array('search_keyword_fname', 'search_keyword_comment', 'search_author', 'search_size_smaller', 'search_size_greater', 'search_count_smaller', 'search_count_greater', 'search_days_greater', 'search_forum', 'search_cat'); - - for ($i = 0; $i < sizeof($search_vars); $i++) - { - $$search_vars[$i] = get_var($search_vars[$i], ''); - } - - // Author name search - if ($search_author != '') - { - // Bring in line with 2.0.x expected username - $search_author = addslashes(html_entity_decode($search_author)); - $search_author = stripslashes(clean_username($search_author)); - - // Prepare for directly going into sql query - $search_author = str_replace('*', '%', attach_mod_sql_escape($search_author)); - - // We need the post_id's, because we want to query the Attachment Table - $sql = 'SELECT user_id FROM ' . BB_USERS . " WHERE username LIKE '$search_author'"; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not obtain list of matching users (searching for: ' . $search_author . ')'); - } - - $matching_userids = ''; - if ( $row = DB()->sql_fetchrow($result) ) - { - do - { - $matching_userids .= (($matching_userids != '') ? ', ' : '') . intval($row['user_id']); - } - while ($row = DB()->sql_fetchrow($result)); - - DB()->sql_freeresult($result); - } - else - { - bb_die($lang['NO_ATTACH_SEARCH_MATCH']); - } - - $where_sql[] = ' (t.user_id_1 IN (' . $matching_userids . ')) '; - } - - // Search Keyword - if ($search_keyword_fname != '') - { - $match_word = str_replace('*', '%', $search_keyword_fname); - $where_sql[] = " (a.real_filename LIKE '" . attach_mod_sql_escape($match_word) . "') "; - } - - if ($search_keyword_comment != '') - { - $match_word = str_replace('*', '%', $search_keyword_comment); - $where_sql[] = " (a.comment LIKE '" . attach_mod_sql_escape($match_word) . "') "; - } - - // Search Download Count - if ($search_count_smaller != '' || $search_count_greater != '') - { - if ($search_count_smaller != '') - { - $where_sql[] = ' (a.download_count < ' . (int) $search_count_smaller . ') '; - } - else if ($search_count_greater != '') - { - $where_sql[] = ' (a.download_count > ' . (int) $search_count_greater . ') '; - } - } - - // Search Filesize - if ($search_size_smaller != '' || $search_size_greater != '') - { - if ($search_size_smaller != '') - { - $where_sql[] = ' (a.filesize < ' . (int) $search_size_smaller . ') '; - } - else if ($search_size_greater != '') - { - $where_sql[] = ' (a.filesize > ' . (int) $search_size_greater . ') '; - } - } - - // Search Attachment Time - if ($search_days_greater != '') - { - $where_sql[] = ' (a.filetime < ' . ( TIMENOW - ((int) $search_days_greater * 86400)) . ') '; - } - - // Search Forum - if ($search_forum) - { - $where_sql[] = ' (p.forum_id = ' . intval($search_forum) . ') '; - } - - // Search Cat... nope... sorry :( - - $sql = 'SELECT a.*, t.post_id, p.post_time, p.topic_id - FROM ' . BB_ATTACHMENTS . ' t, ' . BB_ATTACHMENTS_DESC . ' a, ' . BB_POSTS . ' p WHERE '; - - if (sizeof($where_sql) > 0) - { - $sql .= implode('AND', $where_sql) . ' AND '; - } - - $sql .= 't.post_id = p.post_id AND a.attach_id = t.attach_id '; - - $total_rows_sql = $sql; - - $sql .= $order_by; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #1'); - } - - $attachments = DB()->sql_fetchrowset($result); - $num_attach = DB()->num_rows($result); - DB()->sql_freeresult($result); - - if ($num_attach == 0) - { - bb_die($lang['NO_ATTACH_SEARCH_MATCH']); - } - - if (!($result = DB()->sql_query($total_rows_sql))) - { - bb_die('Could not query attachments #2'); - } - - $total_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); - - return $attachments; + return humn_size($upload_dir_size); } /** -* perform LIMIT statement on arrays -*/ -function limit_array($array, $start, $pagelimit) + * Build SQL statement for the search feature + * + * @param $order_by + * @param $total_rows + * @return array + */ +function search_attachments($order_by, &$total_rows) { - // array from start - start+pagelimit - $limit = (sizeof($array) < ($start + $pagelimit)) ? sizeof($array) : $start + $pagelimit; + global $lang; - $limit_array = array(); + $where_sql = []; - for ($i = $start; $i < $limit; $i++) - { - $limit_array[] = $array[$i]; - } + // Author name search + $search_author = get_var('search_author', ''); + if ($search_author) { + // Bring in line with 2.0.x expected username + $search_author = addslashes(html_entity_decode($search_author)); + $search_author = stripslashes(clean_username($search_author)); - return $limit_array; -} \ No newline at end of file + // Prepare for directly going into sql query + $search_author = str_replace('*', '%', DB()->escape($search_author)); + + // We need the post_id's, because we want to query the Attachment Table + $sql = 'SELECT user_id FROM ' . BB_USERS . " WHERE username LIKE '$search_author'"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain list of matching users (searching for: ' . $search_author . ')'); + } + + $matching_userids = ''; + if ($row = DB()->sql_fetchrow($result)) { + do { + $matching_userids .= (($matching_userids != '') ? ', ' : '') . $row['user_id']; + } while ($row = DB()->sql_fetchrow($result)); + + DB()->sql_freeresult($result); + } else { + bb_die($lang['NO_ATTACH_SEARCH_MATCH']); + } + + $where_sql[] = ' (t.user_id_1 IN (' . $matching_userids . ')) '; + } + + // Search Keyword + $search_keyword_fname = get_var('search_keyword_fname', ''); + if ($search_keyword_fname) { + $match_word = str_replace('*', '%', $search_keyword_fname); + $where_sql[] = " (a.real_filename LIKE '" . DB()->escape($match_word) . "') "; + } + + $search_keyword_comment = get_var('search_keyword_comment', ''); + if ($search_keyword_comment) { + $match_word = str_replace('*', '%', $search_keyword_comment); + $where_sql[] = " (a.comment LIKE '" . DB()->escape($match_word) . "') "; + } + + // Search Download Count + $search_count_smaller = get_var('search_count_smaller', ''); + $search_count_greater = get_var('search_count_greater', ''); + if ($search_count_smaller != '') { + $where_sql[] = ' (a.download_count < ' . (int)$search_count_smaller . ') '; + } elseif ($search_count_greater != '') { + $where_sql[] = ' (a.download_count > ' . (int)$search_count_greater . ') '; + } + + // Search Filesize + $search_size_smaller = get_var('search_size_smaller', ''); + $search_size_greater = get_var('search_size_greater', ''); + if ($search_size_smaller != '') { + $where_sql[] = ' (a.filesize < ' . (int)$search_size_smaller . ') '; + } elseif ($search_size_greater != '') { + $where_sql[] = ' (a.filesize > ' . (int)$search_size_greater . ') '; + } + + // Search Attachment Time + $search_days_greater = get_var('search_days_greater', ''); + if ($search_days_greater) { + $where_sql[] = ' (a.filetime < ' . (TIMENOW - ((int)$search_days_greater * 86400)) . ') '; + } + + // Search Forum + $search_forum = get_var('search_forum', ''); + if ($search_forum) { + $where_sql[] = ' (p.forum_id = ' . (int)$search_forum . ') '; + } + + $sql = 'SELECT a.*, t.post_id, p.post_time, p.topic_id + FROM ' . BB_ATTACHMENTS . ' t, ' . BB_ATTACHMENTS_DESC . ' a, ' . BB_POSTS . ' p WHERE '; + + if (count($where_sql) > 0) { + $sql .= implode('AND', $where_sql) . ' AND '; + } + + $sql .= 't.post_id = p.post_id AND a.attach_id = t.attach_id '; + + $total_rows_sql = $sql; + + $sql .= $order_by; + + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #1'); + } + + $attachments = DB()->sql_fetchrowset($result); + $num_attach = DB()->num_rows($result); + DB()->sql_freeresult($result); + + if ($num_attach == 0) { + bb_die($lang['NO_ATTACH_SEARCH_MATCH']); + } + + if (!($result = DB()->sql_query($total_rows_sql))) { + bb_die('Could not query attachments #2'); + } + + $total_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); + + return $attachments; +} diff --git a/library/attach_mod/includes/functions_attach.php b/library/attach_mod/includes/functions_attach.php index cab4f37ca..e2d7bc67a 100644 --- a/library/attach_mod/includes/functions_attach.php +++ b/library/attach_mod/includes/functions_attach.php @@ -1,690 +1,389 @@ 4096) - { - return; - } - else if ($number < $base) - { - return $chars[$number]; - } + if ($number > 4096) { + return; + } - $hexval = ''; + if ($number < $base) { + return $chars[$number]; + } - while ($number > 0) - { - $remainder = $number%$base; + $hexval = ''; - if ($remainder < $base) - { - $hexval = $chars[$remainder] . $hexval; - } + while ($number > 0) { + $remainder = $number % $base; - $number = floor($number/$base); - } + if ($remainder < $base) { + $hexval = $chars[$remainder] . $hexval; + } - return $hexval; + $number = floor($number / $base); + } + + return $hexval; } /** -* base64todec function -*/ + * base64todec function + */ function base64_unpack($string) { - $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-'; - $base = strlen($chars); + $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-'; + $base = strlen($chars); - $length = strlen($string); - $number = 0; + $length = strlen($string); + $number = 0; - for($i = 1; $i <= $length; $i++) - { - $pos = $length - $i; - $operand = strpos($chars, substr($string,$pos,1)); - $exponent = pow($base, $i-1); - $decValue = $operand * $exponent; - $number += $decValue; - } + for ($i = 1; $i <= $length; $i++) { + $pos = $length - $i; + $operand = strpos($chars, (string)$string[$pos]); + $exponent = $base ** ($i - 1); + $decValue = $operand * $exponent; + $number += $decValue; + } - return $number; + return $number; } /** -* Per Forum based Extension Group Permissions (Encode Number) -> Theoretically up to 158 Forums saveable. :) -* We are using a base of 64, but splitting it to one-char and two-char numbers. :) -*/ + * Per Forum based Extension Group Permissions (Encode Number) -> Theoretically up to 158 Forums saveable. :) + * We are using a base of 64, but splitting it to one-char and two-char numbers. :) + */ function auth_pack($auth_array) { - $one_char_encoding = '#'; - $two_char_encoding = '.'; - $one_char = $two_char = false; - $auth_cache = ''; + $one_char_encoding = '#'; + $two_char_encoding = '.'; + $one_char = $two_char = false; + $auth_cache = ''; - for ($i = 0; $i < sizeof($auth_array); $i++) - { - $val = base64_pack(intval($auth_array[$i])); - if (strlen($val) == 1 && !$one_char) - { - $auth_cache .= $one_char_encoding; - $one_char = true; - } - else if (strlen($val) == 2 && !$two_char) - { - $auth_cache .= $two_char_encoding; - $two_char = true; - } + foreach ($auth_array as $i => $iValue) { + $val = base64_pack((int)$auth_array[$i]); + if (strlen($val) == 1 && !$one_char) { + $auth_cache .= $one_char_encoding; + $one_char = true; + } elseif (strlen($val) == 2 && !$two_char) { + $auth_cache .= $two_char_encoding; + $two_char = true; + } - $auth_cache .= $val; - } + $auth_cache .= $val; + } - return $auth_cache; + return $auth_cache; } /** -* Reverse the auth_pack process -*/ + * Reverse the auth_pack process + */ function auth_unpack($auth_cache) { - $one_char_encoding = '#'; - $two_char_encoding = '.'; + $one_char_encoding = '#'; + $two_char_encoding = '.'; - $auth = array(); - $auth_len = 1; + $auth = []; + $auth_len = 1; - for ($pos = 0; $pos < strlen($auth_cache); $pos += $auth_len) - { - $forum_auth = substr($auth_cache, $pos, 1); - if ($forum_auth == $one_char_encoding) - { - $auth_len = 1; - continue; - } - else if ($forum_auth == $two_char_encoding) - { - $auth_len = 2; - $pos--; - continue; - } + for ($pos = 0, $posMax = strlen($auth_cache); $pos < $posMax; $pos += $auth_len) { + $forum_auth = $auth_cache[$pos]; + if ($forum_auth == $one_char_encoding) { + $auth_len = 1; + continue; + } - $forum_auth = substr($auth_cache, $pos, $auth_len); - $forum_id = base64_unpack($forum_auth); - $auth[] = intval($forum_id); - } - return $auth; + if ($forum_auth == $two_char_encoding) { + $auth_len = 2; + $pos--; + continue; + } + + $forum_auth = substr($auth_cache, $pos, $auth_len); + $forum_id = base64_unpack($forum_auth); + $auth[] = (int)$forum_id; + } + return $auth; } /** -* Used for determining if Forum ID is authed, please use this Function on all Posting Screens -*/ + * Used for determining if Forum ID is authed, please use this Function on all Posting Screens + */ function is_forum_authed($auth_cache, $check_forum_id) { - $one_char_encoding = '#'; - $two_char_encoding = '.'; + $one_char_encoding = '#'; + $two_char_encoding = '.'; - if (trim($auth_cache) == '') - { - return true; - } + if (trim($auth_cache) == '') { + return true; + } - $auth = array(); - $auth_len = 1; + $auth = []; + $auth_len = 1; - for ($pos = 0; $pos < strlen($auth_cache); $pos+=$auth_len) - { - $forum_auth = substr($auth_cache, $pos, 1); - if ($forum_auth == $one_char_encoding) - { - $auth_len = 1; - continue; - } - else if ($forum_auth == $two_char_encoding) - { - $auth_len = 2; - $pos--; - continue; - } + for ($pos = 0, $posMax = strlen($auth_cache); $pos < $posMax; $pos += $auth_len) { + $forum_auth = $auth_cache[$pos]; + if ($forum_auth == $one_char_encoding) { + $auth_len = 1; + continue; + } - $forum_auth = substr($auth_cache, $pos, $auth_len); - $forum_id = (int) base64_unpack($forum_auth); - if ($forum_id == $check_forum_id) - { - return true; - } - } - return false; + if ($forum_auth == $two_char_encoding) { + $auth_len = 2; + $pos--; + continue; + } + + $forum_auth = substr($auth_cache, $pos, $auth_len); + $forum_id = (int)base64_unpack($forum_auth); + if ($forum_id == $check_forum_id) { + return true; + } + } + return false; } /** -* Deletes an Attachment -*/ + * Deletes an Attachment + */ function unlink_attach($filename, $mode = false) { - global $upload_dir, $attach_config; + global $upload_dir, $attach_config; - $filename = basename($filename); + $filename = basename($filename); - if ($mode == MODE_THUMBNAIL) - { - $filename = $upload_dir . '/' . THUMB_DIR . '/t_' . $filename; - } - else - { - $filename = $upload_dir . '/' . $filename; - } + if ($mode == MODE_THUMBNAIL) { + $filename = $upload_dir . '/' . THUMB_DIR . '/t_' . $filename; + } else { + $filename = $upload_dir . '/' . $filename; + } - $deleted = @unlink($filename); - - return $deleted; + return @unlink($filename); } /** -* Check if Attachment exist -*/ -function attachment_exists($filename) -{ - global $upload_dir, $attach_config; - - $filename = basename($filename); - - if (!@file_exists(@amod_realpath($upload_dir . '/' . $filename))) - { - return false; - } - else - { - return true; - } -} - -/** -* Check if Thumbnail exist -*/ -function thumbnail_exists($filename) -{ - global $upload_dir, $attach_config; - - $filename = basename($filename); - - if (!@file_exists(@amod_realpath($upload_dir . '/' . THUMB_DIR . '/t_' . $filename))) - { - return false; - } - else - { - return true; - } -} - -/** -* Physical Filename stored already ? -*/ + * Physical Filename stored already ? + */ function physical_filename_already_stored($filename) { - if ($filename == '') - { - return false; - } + if ($filename == '') { + return false; + } - $filename = basename($filename); + $filename = basename($filename); - $sql = 'SELECT attach_id + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS_DESC . " - WHERE physical_filename = '" . attach_mod_sql_escape($filename) . "' + WHERE physical_filename = '" . DB()->escape($filename) . "' LIMIT 1"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get attachment information for filename: ' . htmlspecialchars($filename)); - } - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get attachment information for filename: ' . htmlspecialchars($filename)); + } + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - return ($num_rows == 0) ? false : true; + return $num_rows != 0; } /** -* get all attachments from a post (could be an post array too) -*/ + * get all attachments from a post (could be an post array too) + */ function get_attachments_from_post($post_id_array) { - global $attach_config; + global $attach_config; - $attachments = array(); + $attachments = []; - if (!is_array($post_id_array)) - { - if (empty($post_id_array)) - { - return $attachments; - } + if (!is_array($post_id_array)) { + if (empty($post_id_array)) { + return $attachments; + } - $post_id = intval($post_id_array); + $post_id = (int)$post_id_array; - $post_id_array = array(); - $post_id_array[] = $post_id; - } + $post_id_array = []; + $post_id_array[] = $post_id; + } - $post_id_array = implode(', ', array_map('intval', $post_id_array)); + $post_id_array = implode(', ', array_map('\intval', $post_id_array)); - if ($post_id_array == '') - { - return $attachments; - } + if ($post_id_array == '') { + return $attachments; + } - $display_order = (intval($attach_config['display_order']) == 0) ? 'DESC' : 'ASC'; + $display_order = ((int)$attach_config['display_order'] == 0) ? 'DESC' : 'ASC'; - $sql = 'SELECT a.post_id, d.* + $sql = 'SELECT a.post_id, d.* FROM ' . BB_ATTACHMENTS . ' a, ' . BB_ATTACHMENTS_DESC . " d WHERE a.post_id IN ($post_id_array) AND a.attach_id = d.attach_id ORDER BY d.filetime $display_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get attachment informations for post number ' . $post_id_array); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get attachment informations for post number ' . $post_id_array); + } - $num_rows = DB()->num_rows($result); - $attachments = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + $attachments = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - if ($num_rows == 0) - { - return array(); - } + if ($num_rows == 0) { + return []; + } - return $attachments; + return $attachments; } /** -* Count Filesize of Attachments in Database based on the attachment id -*/ -function get_total_attach_filesize($attach_ids) -{ - if (!is_array($attach_ids) || !sizeof($attach_ids)) - { - return 0; - } - - $attach_ids = implode(', ', array_map('intval', $attach_ids)); - - if (!$attach_ids) - { - return 0; - } - - $sql = 'SELECT filesize FROM ' . BB_ATTACHMENTS_DESC . " WHERE attach_id IN ($attach_ids)"; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query total filesize'); - } - - $total_filesize = 0; - - while ($row = DB()->sql_fetchrow($result)) - { - $total_filesize += (int) $row['filesize']; - } - DB()->sql_freeresult($result); - - return $total_filesize; -} - -/** -* Get allowed Extensions and their respective Values -*/ + * Get allowed Extensions and their respective Values + */ function get_extension_informations() { - return $GLOBALS['datastore']->get('attach_extensions'); + return $GLOBALS['datastore']->get('attach_extensions'); } // // Sync Topic // -function attachment_sync_topic ($topics) +function attachment_sync_topic($topics) { - if (is_array($topics)) - { - $topics = join(',', $topics); - } - $posts_without_attach = $topics_without_attach = array(); + if (is_array($topics)) { + $topics = implode(',', $topics); + } + $posts_without_attach = $topics_without_attach = []; - // Check orphan post_attachment markers - $sql = "SELECT p.post_id - FROM ". BB_POSTS ." p - LEFT JOIN ". BB_ATTACHMENTS ." a USING(post_id) + // Check orphan post_attachment markers + $sql = "SELECT p.post_id + FROM " . BB_POSTS . " p + LEFT JOIN " . BB_ATTACHMENTS . " a USING(post_id) WHERE p.topic_id IN($topics) AND p.post_attachment = 1 AND a.post_id IS NULL"; - if ($rowset = DB()->fetch_rowset($sql)) - { - foreach ($rowset as $row) - { - $posts_without_attach[] = $row['post_id']; - } - if ($posts_sql = join(',', $posts_without_attach)) - { - DB()->query("UPDATE ". BB_POSTS ." SET post_attachment = 0 WHERE post_id IN($posts_sql)"); - } - } + if ($rowset = DB()->fetch_rowset($sql)) { + foreach ($rowset as $row) { + $posts_without_attach[] = $row['post_id']; + } + if ($posts_sql = implode(',', $posts_without_attach)) { + DB()->query("UPDATE " . BB_POSTS . " SET post_attachment = 0 WHERE post_id IN($posts_sql)"); + } + } - // Update missing topic_attachment markers - DB()->query(" - UPDATE ". BB_TOPICS ." t, ". BB_POSTS ." p SET + // Update missing topic_attachment markers + DB()->query(" + UPDATE " . BB_TOPICS . " t, " . BB_POSTS . " p SET t.topic_attachment = 1 WHERE p.topic_id IN($topics) AND p.post_attachment = 1 AND p.topic_id = t.topic_id "); - // Fix orphan topic_attachment markers - $sql = "SELECT t.topic_id - FROM ". BB_POSTS ." p, ". BB_TOPICS ." t + // Fix orphan topic_attachment markers + $sql = "SELECT t.topic_id + FROM " . BB_POSTS . " p, " . BB_TOPICS . " t WHERE t.topic_id = p.topic_id AND t.topic_id IN($topics) AND t.topic_attachment = 1 GROUP BY p.topic_id HAVING SUM(p.post_attachment) = 0"; - if ($rowset = DB()->fetch_rowset($sql)) - { - foreach ($rowset as $row) - { - $topics_without_attach[] = $row['topic_id']; - } - if ($topics_sql = join(',', $topics_without_attach)) - { - DB()->query("UPDATE ". BB_TOPICS ." SET topic_attachment = 0 WHERE topic_id IN($topics_sql)"); - } - } + if ($rowset = DB()->fetch_rowset($sql)) { + foreach ($rowset as $row) { + $topics_without_attach[] = $row['topic_id']; + } + if ($topics_sql = implode(',', $topics_without_attach)) { + DB()->query("UPDATE " . BB_TOPICS . " SET topic_attachment = 0 WHERE topic_id IN($topics_sql)"); + } + } } /** -* Get Extension -*/ -function get_extension($filename) -{ - if (!stristr($filename, '.')) - { - return ''; - } - $extension = strrchr(strtolower($filename), '.'); - $extension[0] = ' '; - $extension = strtolower(trim($extension)); - if (is_array($extension)) - { - return ''; - } - else - { - return $extension; - } -} - -/** -* Delete Extension -*/ -function delete_extension($filename) -{ - return substr($filename, 0, strrpos(strtolower(trim($filename)), '.')); -} - -/** -* Check if a user is within Group -*/ -function user_in_group($user_id, $group_id) -{ - $user_id = (int) $user_id; - $group_id = (int) $group_id; - - if (!$user_id || !$group_id) - { - return false; - } - - $sql = 'SELECT u.group_id - FROM ' . BB_USER_GROUP . ' u, ' . BB_GROUPS . " g - WHERE g.group_single_user = 0 - AND u.group_id = g.group_id - AND u.user_id = $user_id - AND g.group_id = $group_id - LIMIT 1"; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get user group'); - } - - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); - - if ($num_rows == 0) - { - return false; - } - - return true; -} - -/** -* Realpath replacement for attachment mod -*/ -function amod_realpath($path) -{ - return (function_exists('realpath')) ? realpath($path) : $path; -} - -/** -* _set_var -* -* Set variable, used by {@link get_var the get_var function} -* -* @private -*/ + * _set_var + * + * Set variable, used by {@link get_var the get_var function} + * + * @private + */ function _set_var(&$result, $var, $type, $multibyte = false) { - settype($var, $type); - $result = $var; + settype($var, $type); + $result = $var; - if ($type == 'string') - { - $result = trim(str_replace(array("\r\n", "\r", '\xFF'), array("\n", "\n", ' '), $result)); - // 2.0.x is doing addslashes on all variables - $result = stripslashes($result); - if ($multibyte) - { - $result = preg_replace('#&(\#[0-9]+;)#', '&\1', $result); - } - } + if ($type == 'string') { + $result = trim(str_replace(["\r\n", "\r", '\xFF'], ["\n", "\n", ' '], $result)); + // 2.0.x is doing addslashes on all variables + $result = stripslashes($result); + if ($multibyte) { + $result = preg_replace('#&(\#[0-9]+;)#', '&\1', $result); + } + } } /** -* get_var -* -* Used to get passed variable -*/ + * Used to get passed variable + * + * @param $var_name + * @param $default + * @param bool $multibyte + * @return array|string + */ function get_var($var_name, $default, $multibyte = false) { - $request_var = (isset($_POST[$var_name])) ? $_POST : $_GET; + $type = null; + if (!isset($_REQUEST[$var_name]) || + (is_array($_REQUEST[$var_name]) && !is_array($default)) || + (is_array($default) && !is_array($_REQUEST[$var_name]))) { + return (is_array($default)) ? [] : $default; + } - if (!isset($request_var[$var_name]) || (is_array($request_var[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($request_var[$var_name]))) - { - return (is_array($default)) ? array() : $default; - } + $var = $_REQUEST[$var_name]; - $var = $request_var[$var_name]; + if (!is_array($default)) { + $type = gettype($default); + $key_type = null; + } else { + foreach ($default as $key_type => $type) { + $key_type = gettype($key_type); + $type = gettype($type); + } + } - if (!is_array($default)) - { - $type = gettype($default); - } - else - { - list($key_type, $type) = each($default); - $type = gettype($type); - $key_type = gettype($key_type); - } + if (is_array($var)) { + $_var = $var; + $var = []; - if (is_array($var)) - { - $_var = $var; - $var = array(); + foreach ($_var as $k => $v) { + if (is_array($v)) { + foreach ($v as $_k => $_v) { + _set_var($k, $k, $key_type); + _set_var($_k, $_k, $key_type); + _set_var($var[$k][$_k], $_v, $type, $multibyte); + } + } else { + _set_var($k, $k, $key_type); + _set_var($var[$k], $v, $type, $multibyte); + } + } + } else { + _set_var($var, $var, $type, $multibyte); + } - foreach ($_var as $k => $v) - { - if (is_array($v)) - { - foreach ($v as $_k => $_v) - { - _set_var($k, $k, $key_type); - _set_var($_k, $_k, $key_type); - _set_var($var[$k][$_k], $_v, $type, $multibyte); - } - } - else - { - _set_var($k, $k, $key_type); - _set_var($var[$k], $v, $type, $multibyte); - } - } - } - else - { - _set_var($var, $var, $type, $multibyte); - } - - return $var; + return $var; } - -/** -* Escaping SQL -*/ -function attach_mod_sql_escape($text) -{ - if (function_exists('mysql_real_escape_string')) - { - return DB()->escape_string($text); - } - else - { - return str_replace("'", "''", str_replace('\\', '\\\\', $text)); - } -} - -/** -* Build sql statement from array for insert/update/select statements -* -* Idea for this from Ikonboard -* Possible query values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT -*/ -function attach_mod_sql_build_array($query, $assoc_ary = false) -{ - if (!is_array($assoc_ary)) - { - return false; - } - - $fields = array(); - $values = array(); - if ($query == 'INSERT' || $query == 'INSERT_SELECT') - { - foreach ($assoc_ary as $key => $var) - { - $fields[] = $key; - - if (is_null($var)) - { - $values[] = 'NULL'; - } - else if (is_string($var)) - { - $values[] = "'" . attach_mod_sql_escape($var) . "'"; - } - else if (is_array($var) && is_string($var[0])) - { - $values[] = $var[0]; - } - else - { - $values[] = (is_bool($var)) ? intval($var) : $var; - } - } - - $query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' '; - } - else if ($query == 'MULTI_INSERT') - { - $ary = array(); - foreach ($assoc_ary as $id => $sql_ary) - { - $values = array(); - foreach ($sql_ary as $key => $var) - { - if (is_null($var)) - { - $values[] = 'NULL'; - } - elseif (is_string($var)) - { - $values[] = "'" . attach_mod_sql_escape($var) . "'"; - } - else - { - $values[] = (is_bool($var)) ? intval($var) : $var; - } - } - $ary[] = '(' . implode(', ', $values) . ')'; - } - - $query = ' (' . implode(', ', array_keys($assoc_ary[0])) . ') VALUES ' . implode(', ', $ary); - } - else if ($query == 'UPDATE' || $query == 'SELECT') - { - $values = array(); - foreach ($assoc_ary as $key => $var) - { - if (is_null($var)) - { - $values[] = "$key = NULL"; - } - elseif (is_string($var)) - { - $values[] = "$key = '" . attach_mod_sql_escape($var) . "'"; - } - else - { - $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var"; - } - } - $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values); - } - - return $query; -} \ No newline at end of file diff --git a/library/attach_mod/includes/functions_delete.php b/library/attach_mod/includes/functions_delete.php index 8cf7f7598..79679db2a 100644 --- a/library/attach_mod/includes/functions_delete.php +++ b/library/attach_mod/includes/functions_delete.php @@ -1,284 +1,246 @@ sql_query($sql))) - { - bb_die('Could not select ids'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select ids'); + } - $num_post_list = DB()->num_rows($result); + $num_post_list = DB()->num_rows($result); - if ($num_post_list == 0) - { - DB()->sql_freeresult($result); - return; - } + if ($num_post_list == 0) { + DB()->sql_freeresult($result); + return; + } - while ($row = DB()->sql_fetchrow($result)) - { - $post_id_array[] = intval($row[$p_id]); - } - DB()->sql_freeresult($result); - } + while ($row = DB()->sql_fetchrow($result)) { + $post_id_array[] = (int)$row[$p_id]; + } + DB()->sql_freeresult($result); + } - if (!is_array($post_id_array)) - { - if (trim($post_id_array) == '') - { - return; - } + if (!is_array($post_id_array)) { + if (trim($post_id_array) == '') { + return; + } - if (strstr($post_id_array, ', ')) - { - $post_id_array = explode(', ', $post_id_array); - } - else if (strstr($post_id_array, ',')) - { - $post_id_array = explode(',', $post_id_array); - } - else - { - $post_id = intval($post_id_array); + if (str_contains($post_id_array, ', ')) { + $post_id_array = explode(', ', $post_id_array); + } elseif (str_contains($post_id_array, ',')) { + $post_id_array = explode(',', $post_id_array); + } else { + $post_id = (int)$post_id_array; - $post_id_array = array(); - $post_id_array[] = $post_id; - } - } + $post_id_array = []; + $post_id_array[] = $post_id; + } + } - if (!sizeof($post_id_array)) - { - return; - } + if (!count($post_id_array)) { + return; + } - // First of all, determine the post id and attach_id - if ($attach_id_array === 0) - { - $attach_id_array = array(); + // First of all, determine the post id and attach_id + if ($attach_id_array === 0) { + $attach_id_array = []; - // Get the attach_ids to fill the array - $whereclause = 'WHERE post_id IN (' . implode(', ', $post_id_array) . ')'; + // Get the attach_ids to fill the array + $whereclause = 'WHERE post_id IN (' . implode(', ', $post_id_array) . ')'; - $sql = 'SELECT attach_id + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS . " $whereclause GROUP BY attach_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select attachment id #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select attachment id #1'); + } - $num_attach_list = DB()->num_rows($result); + $num_attach_list = DB()->num_rows($result); - if ($num_attach_list == 0) - { - DB()->sql_freeresult($result); - return; - } + if ($num_attach_list == 0) { + DB()->sql_freeresult($result); + return; + } - while ($row = DB()->sql_fetchrow($result)) - { - $attach_id_array[] = (int) $row['attach_id']; - } - DB()->sql_freeresult($result); - } + while ($row = DB()->sql_fetchrow($result)) { + $attach_id_array[] = (int)$row['attach_id']; + } + DB()->sql_freeresult($result); + } - if (!is_array($attach_id_array)) - { - if (strstr($attach_id_array, ', ')) - { - $attach_id_array = explode(', ', $attach_id_array); - } - else if (strstr($attach_id_array, ',')) - { - $attach_id_array = explode(',', $attach_id_array); - } - else - { - $attach_id = intval($attach_id_array); + if (!is_array($attach_id_array)) { + if (str_contains($attach_id_array, ', ')) { + $attach_id_array = explode(', ', $attach_id_array); + } elseif (str_contains($attach_id_array, ',')) { + $attach_id_array = explode(',', $attach_id_array); + } else { + $attach_id = (int)$attach_id_array; - $attach_id_array = array(); - $attach_id_array[] = $attach_id; - } - } + $attach_id_array = []; + $attach_id_array[] = $attach_id; + } + } - if (!sizeof($attach_id_array)) - { - return; - } + if (!count($attach_id_array)) { + return; + } - $sql_id = 'post_id'; + $sql_id = 'post_id'; - if (sizeof($post_id_array) && sizeof($attach_id_array)) - { - $sql = 'DELETE FROM ' . BB_ATTACHMENTS . ' + if (count($post_id_array) && count($attach_id_array)) { + $sql = 'DELETE FROM ' . BB_ATTACHMENTS . ' WHERE attach_id IN (' . implode(', ', $attach_id_array) . ") AND $sql_id IN (" . implode(', ', $post_id_array) . ')'; - if (!(DB()->sql_query($sql))) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } + if (!(DB()->sql_query($sql))) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } - //bt - if ($sql_id == 'post_id') - { - $sql = "SELECT topic_id FROM ". BB_BT_TORRENTS ." WHERE attach_id IN(". implode(',', $attach_id_array) .")"; + //bt + if ($sql_id == 'post_id') { + $sql = "SELECT topic_id FROM " . BB_BT_TORRENTS . " WHERE attach_id IN(" . implode(',', $attach_id_array) . ")"; - if (!$result = DB()->sql_query($sql)) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } + if (!$result = DB()->sql_query($sql)) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } - $torrents_sql = array(); + $torrents_sql = []; - while ($row = DB()->sql_fetchrow($result)) - { - $torrents_sql[] = $row['topic_id']; - } + while ($row = DB()->sql_fetchrow($result)) { + $torrents_sql[] = $row['topic_id']; + } - if ($torrents_sql = implode(',', $torrents_sql)) - { - // Remove peers from tracker - $sql = "DELETE FROM ". BB_BT_TRACKER ." + if ($torrents_sql = implode(',', $torrents_sql)) { + // Remove peers from tracker + $sql = "DELETE FROM " . BB_BT_TRACKER . " WHERE topic_id IN($torrents_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not delete peers'); - } - } - // Delete torrents - $sql = "DELETE FROM ". BB_BT_TORRENTS ." - WHERE attach_id IN(". implode(',', $attach_id_array) .")"; + if (!DB()->sql_query($sql)) { + bb_die('Could not delete peers'); + } + } + // Delete torrents + $sql = "DELETE FROM " . BB_BT_TORRENTS . " + WHERE attach_id IN(" . implode(',', $attach_id_array) . ")"; - if (!DB()->sql_query($sql)) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } - } - //bt end + if (!DB()->sql_query($sql)) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } + } + //bt end - for ($i = 0; $i < sizeof($attach_id_array); $i++) - { - $sql = 'SELECT attach_id + foreach ($attach_id_array as $i => $iValue) { + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS . ' - WHERE attach_id = ' . (int) $attach_id_array[$i]; + WHERE attach_id = ' . (int)$attach_id_array[$i]; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select Attachment id #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select Attachment id #2'); + } - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows == 0) - { - $sql = 'SELECT attach_id, physical_filename, thumbnail + if ($num_rows == 0) { + $sql = 'SELECT attach_id, physical_filename, thumbnail FROM ' . BB_ATTACHMENTS_DESC . ' - WHERE attach_id = ' . (int) $attach_id_array[$i]; + WHERE attach_id = ' . (int)$attach_id_array[$i]; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attach description table'); - } - $num_rows = DB()->num_rows($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attach description table'); + } + $num_rows = DB()->num_rows($result); - if ($num_rows != 0) - { - $num_attach = $num_rows; - $attachments = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + if ($num_rows != 0) { + $num_attach = $num_rows; + $attachments = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - // delete attachments - for ($j = 0; $j < $num_attach; $j++) - { - unlink_attach($attachments[$j]['physical_filename']); + // delete attachments + for ($j = 0; $j < $num_attach; $j++) { + unlink_attach($attachments[$j]['physical_filename']); - if (intval($attachments[$j]['thumbnail']) == 1) - { - unlink_attach($attachments[$j]['physical_filename'], MODE_THUMBNAIL); - } + if ((int)$attachments[$j]['thumbnail'] == 1) { + unlink_attach($attachments[$j]['physical_filename'], MODE_THUMBNAIL); + } - $sql = 'DELETE FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int) $attachments[$j]['attach_id']; + $sql = 'DELETE FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int)$attachments[$j]['attach_id']; - if (!(DB()->sql_query($sql))) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } - } - } - else - { - DB()->sql_freeresult($result); - } - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } - // Now Sync the Topic/PM - if (sizeof($post_id_array)) - { - $sql = 'SELECT topic_id + // TorrServer integration + if (config()->get('torr_server.enabled')) { + $torrServer = new \TorrentPier\TorrServerAPI(); + $torrServer->removeM3U($attachments[$j]['attach_id']); + } + } + } else { + DB()->sql_freeresult($result); + } + } + } + } + + // Now Sync the Topic/PM + if (count($post_id_array)) { + $sql = 'SELECT topic_id FROM ' . BB_POSTS . ' WHERE post_id IN (' . implode(', ', $post_id_array) . ') GROUP BY topic_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select topic id'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select topic id'); + } - while ($row = DB()->sql_fetchrow($result)) - { - attachment_sync_topic($row['topic_id']); - } - DB()->sql_freeresult($result); - } -} \ No newline at end of file + while ($row = DB()->sql_fetchrow($result)) { + attachment_sync_topic($row['topic_id']); + } + DB()->sql_freeresult($result); + } +} diff --git a/library/attach_mod/includes/functions_filetypes.php b/library/attach_mod/includes/functions_filetypes.php deleted file mode 100644 index 928f05b4c..000000000 --- a/library/attach_mod/includes/functions_filetypes.php +++ /dev/null @@ -1,293 +0,0 @@ -= 4294967294) - { - $value -= 4294967296; - } - - return $value; -} - -/** -* Read Word (2 Bytes) from File - Note: It's an Intel Word -*/ -function read_word($fp) -{ - $data = fread($fp, 2); - - $value = ord($data[1]) * 256 + ord($data[0]); - - return $value; -} - -/** -* Read Byte -*/ -function read_byte($fp) -{ - $data = fread($fp, 1); - - $value = ord($data); - - return $value; -} - -/** -* Get Image Dimensions -*/ -function image_getdimension($file) -{ - - $size = @getimagesize($file); - - if ($size[0] != 0 || $size[1] != 0) - { - return $size; - } - - // Try to get the Dimension manually, depending on the mimetype - $fp = @fopen($file, 'rb'); - if (!$fp) - { - return $size; - } - - $error = FALSE; - - // BMP - IMAGE - - $tmp_str = fread($fp, 2); - if ($tmp_str == 'BM') - { - $length = read_longint($fp); - - if ($length <= 6) - { - $error = true; - } - - if (!$error) - { - $i = read_longint($fp); - if ( $i != 0) - { - $error = true; - } - } - - if (!$error) - { - $i = read_longint($fp); - - if ($i != 0x3E && $i != 0x76 && $i != 0x436 && $i != 0x36) - { - $error = true; - } - } - - if (!$error) - { - $tmp_str = fread($fp, 4); - $width = read_longint($fp); - $height = read_longint($fp); - - if ($width > 3000 || $height > 3000) - { - $error = true; - } - } - } - else - { - $error = true; - } - - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 6 - ); - } - - $error = false; - fclose($fp); - - // GIF - IMAGE - - $fp = @fopen($file, 'rb'); - - $tmp_str = fread($fp, 3); - - if ($tmp_str == 'GIF') - { - $tmp_str = fread($fp, 3); - $width = read_word($fp); - $height = read_word($fp); - - $info_byte = fread($fp, 1); - $info_byte = ord($info_byte); - if (($info_byte & 0x80) != 0x80 && ($info_byte & 0x80) != 0) - { - $error = true; - } - - if (!$error) - { - if (($info_byte & 8) != 0) - { - $error = true; - } - - } - } - else - { - $error = true; - } - - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 1 - ); - } - - $error = false; - fclose($fp); - - // JPG - IMAGE - $fp = @fopen($file, 'rb'); - - $tmp_str = fread($fp, 4); - $w1 = read_word($fp); - - if (intval($w1) < 16) - { - $error = true; - } - - if (!$error) - { - $tmp_str = fread($fp, 4); - if ($tmp_str == 'JFIF') - { - $o_byte = fread($fp, 1); - if (intval($o_byte) != 0) - { - $error = true; - } - - if (!$error) - { - $str = fread($fp, 2); - $b = read_byte($fp); - - if ($b != 0 && $b != 1 && $b != 2) - { - $error = true; - } - } - - if (!$error) - { - $width = read_word($fp); - $height = read_word($fp); - - if ($width <= 0 || $height <= 0) - { - $error = true; - } - } - } - } - else - { - $error = true; - } - - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 2 - ); - } - - $error = false; - fclose($fp); - - // PCX - IMAGE - - $fp = @fopen($file, 'rb'); - - $tmp_str = fread($fp, 3); - - if ((ord($tmp_str[0]) == 10) && (ord($tmp_str[1]) == 0 || ord($tmp_str[1]) == 2 || ord($tmp_str[1]) == 3 || ord($tmp_str[1]) == 4 || ord($tmp_str[1]) == 5) && (ord($tmp_str[2]) == 1)) - { - $b = fread($fp, 1); - - if (ord($b) != 1 && ord($b) != 2 && ord($b) != 4 && ord($b) != 8 && ord($b) != 24) - { - $error = true; - } - - if (!$error) - { - $xmin = read_word($fp); - $ymin = read_word($fp); - $xmax = read_word($fp); - $ymax = read_word($fp); - $tmp_str = fread($fp, 52); - - $b = fread($fp, 1); - if ($b != 0) - { - $error = true; - } - } - - if (!$error) - { - $width = $xmax - $xmin + 1; - $height = $ymax - $ymin + 1; - } - } - else - { - $error = true; - } - - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 7 - ); - } - - fclose($fp); - - return $size; -} \ No newline at end of file diff --git a/library/attach_mod/includes/functions_includes.php b/library/attach_mod/includes/functions_includes.php index a4e8708ad..6528e6c06 100644 --- a/library/attach_mod/includes/functions_includes.php +++ b/library/attach_mod/includes/functions_includes.php @@ -1,204 +1,156 @@ '; - $s_auth_can .= (($is_auth['auth_download']) ? $lang['RULES_DOWNLOAD_CAN'] : $lang['RULES_DOWNLOAD_CANNOT'] ) . '
    '; + include ATTACH_DIR . '/includes/functions_selects.php'; + if (!function_exists("process_quota_settings")) { + include ATTACH_DIR . '/includes/functions_admin.php'; + } + + $user_id = 0; + + if ($admin_mode == 'user') { + // We overwrite submit here... to be sure + $submit = isset($_POST['submit']); + + if (!$submit && $mode != 'save') { + $user_id = get_var(POST_USERS_URL, 0); + $u_name = get_var('username', ''); + + if (!$user_id && !$u_name) { + bb_die($lang['NO_USER_ID_SPECIFIED']); + } + + if ($user_id) { + $this_userdata['user_id'] = $user_id; + } else { + // Get userdata is handling the sanitizing of username + $this_userdata = get_userdata($_POST['username'], true); + } + + $user_id = (int)$this_userdata['user_id']; + } else { + $user_id = get_var('id', 0); + + if (!$user_id) { + bb_die($lang['NO_USER_ID_SPECIFIED']); + } + } + } + + if ($admin_mode == 'user' && !$submit && $mode != 'save') { + // Show the contents + $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE user_id = ' . (int)$user_id; + + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to get quota settings #1'); + } + + $pm_quota = $upload_quota = 0; + + if ($row = DB()->sql_fetchrow($result)) { + do { + if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $upload_quota = $row['quota_limit_id']; + } elseif ($row['quota_type'] == QUOTA_PM_LIMIT) { + $pm_quota = $row['quota_limit_id']; + } + } while ($row = DB()->sql_fetchrow($result)); + } else { + // Set Default Quota Limit + $upload_quota = $attach_config['default_upload_quota']; + $pm_quota = $attach_config['default_pm_quota']; + } + DB()->sql_freeresult($result); + + $template->assign_vars([ + 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('user_upload_quota', $upload_quota), + 'S_SELECT_PM_QUOTA' => quota_limit_select('user_pm_quota', $pm_quota) + ]); + } + + if ($admin_mode == 'user' && $submit && @$_POST['delete_user']) { + process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, 0); + process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, 0); + } elseif ($admin_mode == 'user' && $submit && $mode == 'save') { + // Get the contents + $upload_quota = get_var('user_upload_quota', 0); + $pm_quota = get_var('user_pm_quota', 0); + + process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, $upload_quota); + process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, $pm_quota); + } + + if ($admin_mode == 'group' && $mode == 'newgroup') { + return; + } + + if ($admin_mode == 'group' && !$submit && isset($_POST['edit'])) { + // Get group id again + $group_id = get_var(POST_GROUPS_URL, 0); + + // Show the contents + $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE group_id = ' . (int)$group_id; + + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to get quota settings #2'); + } + + $pm_quota = $upload_quota = 0; + + if ($row = DB()->sql_fetchrow($result)) { + do { + if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $upload_quota = $row['quota_limit_id']; + } elseif ($row['quota_type'] == QUOTA_PM_LIMIT) { + $pm_quota = $row['quota_limit_id']; + } + } while ($row = DB()->sql_fetchrow($result)); + } else { + // Set Default Quota Limit + $upload_quota = $attach_config['default_upload_quota']; + $pm_quota = $attach_config['default_pm_quota']; + } + DB()->sql_freeresult($result); + + $template->assign_vars([ + 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('group_upload_quota', $upload_quota), + 'S_SELECT_PM_QUOTA' => quota_limit_select('group_pm_quota', $pm_quota) + ]); + } + + if ($admin_mode == 'group' && $submit && isset($_POST['group_delete'])) { + $group_id = get_var(POST_GROUPS_URL, 0); + + process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, 0); + process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, 0); + } elseif ($admin_mode == 'group' && $submit) { + $group_id = get_var(POST_GROUPS_URL, 0); + + // Get the contents + $upload_quota = get_var('group_upload_quota', 0); + $pm_quota = get_var('group_pm_quota', 0); + + process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, $upload_quota); + process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, $pm_quota); + } } - -/** -* Called from admin_users.php and admin_groups.php in order to process Quota Settings (admin/admin_users.php:admin/admin_groups.php) -*/ -function attachment_quota_settings($admin_mode, $submit = false, $mode) -{ - global $template, $lang, $attach_config; - - if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $upload_dir = $attach_config['upload_dir']; - } - else - { - $upload_dir = BB_ROOT . $attach_config['upload_dir']; - } - - include(ATTACH_DIR .'includes/functions_selects.php'); - if (!function_exists("process_quota_settings")) - include(ATTACH_DIR . 'includes/functions_admin.php'); - - $user_id = 0; - - if ($admin_mode == 'user') - { - // We overwrite submit here... to be sure - $submit = (isset($_POST['submit'])) ? true : false; - - if (!$submit && $mode != 'save') - { - $user_id = get_var(POST_USERS_URL, 0); - $u_name = get_var('username', ''); - - if (!$user_id && !$u_name) - { - bb_die($lang['NO_USER_ID_SPECIFIED'] ); - } - - if ($user_id) - { - $this_userdata['user_id'] = $user_id; - } - else - { - // Get userdata is handling the sanitizing of username - $this_userdata = get_userdata($_POST['username'], true); - } - - $user_id = (int) $this_userdata['user_id']; - } - else - { - $user_id = get_var('id', 0); - - if (!$user_id) - { - bb_die($lang['NO_USER_ID_SPECIFIED'] ); - } - } - } - - if ($admin_mode == 'user' && !$submit && $mode != 'save') - { - // Show the contents - $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE user_id = ' . (int) $user_id; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to get quota settings #1'); - } - - $pm_quota = $upload_quota = 0; - - if ($row = DB()->sql_fetchrow($result)) - { - do - { - if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $upload_quota = $row['quota_limit_id']; - } - else if ($row['quota_type'] == QUOTA_PM_LIMIT) - { - $pm_quota = $row['quota_limit_id']; - } - } - while ($row = DB()->sql_fetchrow($result)); - } - else - { - // Set Default Quota Limit - $upload_quota = $attach_config['default_upload_quota']; - $pm_quota = $attach_config['default_pm_quota']; - - } - DB()->sql_freeresult($result); - - $template->assign_vars(array( - 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('user_upload_quota', $upload_quota), - 'S_SELECT_PM_QUOTA' => quota_limit_select('user_pm_quota', $pm_quota), - )); - } - - if ($admin_mode == 'user' && $submit && @$_POST['delete_user']) - { - process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, 0); - process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, 0); - } - else if ($admin_mode == 'user' && $submit && $mode == 'save') - { - // Get the contents - $upload_quota = get_var('user_upload_quota', 0); - $pm_quota = get_var('user_pm_quota', 0); - - process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, $upload_quota); - process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, $pm_quota); - } - - if ($admin_mode == 'group' && $mode == 'newgroup') - { - return; - } - - if ($admin_mode == 'group' && !$submit && isset($_POST['edit'])) - { - // Get group id again - $group_id = get_var(POST_GROUPS_URL, 0); - - // Show the contents - $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE group_id = ' . (int) $group_id; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to get quota settings #2'); - } - - $pm_quota = $upload_quota = 0; - - if ($row = DB()->sql_fetchrow($result)) - { - do - { - if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $upload_quota = $row['quota_limit_id']; - } - else if ($row['quota_type'] == QUOTA_PM_LIMIT) - { - $pm_quota = $row['quota_limit_id']; - } - } - while ($row = DB()->sql_fetchrow($result)); - } - else - { - // Set Default Quota Limit - $upload_quota = $attach_config['default_upload_quota']; - $pm_quota = $attach_config['default_pm_quota']; - } - DB()->sql_freeresult($result); - - $template->assign_vars(array( - 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('group_upload_quota', $upload_quota), - 'S_SELECT_PM_QUOTA' => quota_limit_select('group_pm_quota', $pm_quota), - )); - } - - if ($admin_mode == 'group' && $submit && isset($_POST['group_delete'])) - { - $group_id = get_var(POST_GROUPS_URL, 0); - - process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, 0); - process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, 0); - } - else if ($admin_mode == 'group' && $submit) - { - $group_id = get_var(POST_GROUPS_URL, 0); - - // Get the contents - $upload_quota = get_var('group_upload_quota', 0); - $pm_quota = get_var('group_pm_quota', 0); - - process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, $upload_quota); - process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, $pm_quota); - } -} \ No newline at end of file diff --git a/library/attach_mod/includes/functions_selects.php b/library/attach_mod/includes/functions_selects.php index be709e94c..ab027e63f 100644 --- a/library/attach_mod/includes/functions_selects.php +++ b/library/attach_mod/includes/functions_selects.php @@ -1,251 +1,232 @@ sql_query($sql))) - { - bb_die('Could not query extension groups table #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups table #1'); + } - $group_select = ''; - $group_name = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $group_name = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - $group_name[$num_rows]['group_id'] = 0; - $group_name[$num_rows]['group_name'] = $lang['NOT_ASSIGNED']; + if ($num_rows > 0) { + $group_name[$num_rows]['group_id'] = 0; + $group_name[$num_rows]['group_name'] = $lang['NOT_ASSIGNED']; - for ($i = 0; $i < sizeof($group_name); $i++) - { - if (!$default_group) - { - $selected = ($i == 0) ? ' selected="selected"' : ''; - } - else - { - $selected = ($group_name[$i]['group_id'] == $default_group) ? ' selected="selected"' : ''; - } + for ($i = 0, $iMax = count($group_name); $i < $iMax; $i++) { + if (!$default_group) { + $selected = ($i == 0) ? ' selected' : ''; + } else { + $selected = ($group_name[$i]['group_id'] == $default_group) ? ' selected' : ''; + } - $group_select .= ''; - } - } + $group_select .= ''; + } + } - $group_select .= ''; + $group_select .= ''; - return $group_select; + return $group_select; } /** -* select download mode -*/ + * select download mode + */ function download_select($select_name, $group_id = 0) { - global $types_download, $modes_download; + global $types_download, $modes_download; - if ($group_id) - { - $sql = 'SELECT download_mode + if ($group_id) { + $sql = 'SELECT download_mode FROM ' . BB_EXTENSION_GROUPS . ' - WHERE group_id = ' . (int) $group_id; + WHERE group_id = ' . (int)$group_id; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extension groups table #2'); - } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups table #2'); + } + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - if (!isset($row['download_mode'])) - { - return ''; - } + if (!isset($row['download_mode'])) { + return ''; + } - $download_mode = $row['download_mode']; - } + $download_mode = $row['download_mode']; + } - $group_select = ''; - for ($i = 0; $i < sizeof($types_download); $i++) - { - if (!$group_id) - { - $selected = ($types_download[$i] == INLINE_LINK) ? ' selected="selected"' : ''; - } - else - { - $selected = ($row['download_mode'] == $types_download[$i]) ? ' selected="selected"' : ''; - } + for ($i = 0, $iMax = count($types_download); $i < $iMax; $i++) { + if (!$group_id) { + $selected = ($types_download[$i] == INLINE_LINK) ? ' selected' : ''; + } else { + $selected = ($row['download_mode'] == $types_download[$i]) ? ' selected' : ''; + } - $group_select .= ''; - } + $group_select .= ''; + } - $group_select .= ''; + $group_select .= ''; - return $group_select; + return $group_select; } /** -* select category types -*/ + * select category types + */ function category_select($select_name, $group_id = 0) { - global $types_category, $modes_category; + global $types_category, $modes_category, $lang; + $category_type = null; - $sql = 'SELECT group_id, cat_id FROM ' . BB_EXTENSION_GROUPS; + $sql = 'SELECT group_id, cat_id FROM ' . BB_EXTENSION_GROUPS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select category'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select category'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - $type_category = 0; + $type_category = 0; - if ($num_rows > 0) - { - for ($i = 0; $i < $num_rows; $i++) - { - if ($group_id == $rows[$i]['group_id']) - { - $category_type = $rows[$i]['cat_id']; - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if ($group_id == $rows[$i]['group_id']) { + $category_type = $rows[$i]['cat_id']; + } + } + } - $types = array(NONE_CAT); - $modes = array('none'); + $types = [NONE_CAT]; + $modes = [$lang['NONE']]; - for ($i = 0; $i < sizeof($types_category); $i++) - { - $types[] = $types_category[$i]; - $modes[] = $modes_category[$i]; - } + for ($i = 0, $iMax = count($types_category); $i < $iMax; $i++) { + $types[] = $types_category[$i]; + $modes[] = $modes_category[$i]; + } - $group_select = ''; - for ($i = 0; $i < sizeof($types); $i++) - { - if (!$group_id) - { - $selected = ($types[$i] == NONE_CAT) ? ' selected="selected"' : ''; - } - else - { - $selected = ($types[$i] == $category_type) ? ' selected="selected"' : ''; - } + for ($i = 0, $iMax = count($types); $i < $iMax; $i++) { + if (!$group_id) { + $selected = ($types[$i] == NONE_CAT) ? ' selected' : ''; + } else { + $selected = ($types[$i] == $category_type) ? ' selected' : ''; + } - $group_select .= ''; - } + $group_select .= ''; + } - $group_select .= ''; + $group_select .= ''; - return $group_select; + return $group_select; } /** -* Select size mode -*/ + * Select size mode + */ function size_select($select_name, $size_compare) { - global $lang; + global $lang; - $size_types_text = array($lang['BYTES'], $lang['KB'], $lang['MB']); - $size_types = array('b', 'kb', 'mb'); + $size_types_text = [$lang['BYTES'], $lang['KB'], $lang['MB']]; + $size_types = ['b', 'kb', 'mb']; - $select_field = ''; - for ($i = 0; $i < sizeof($size_types_text); $i++) - { - $selected = ($size_compare == $size_types[$i]) ? ' selected="selected"' : ''; - $select_field .= ''; - } + for ($i = 0, $iMax = count($size_types_text); $i < $iMax; $i++) { + $selected = ($size_compare == $size_types[$i]) ? ' selected' : ''; + $select_field .= ''; + } - $select_field .= ''; + $select_field .= ''; - return $select_field; + return $select_field; } /** -* select quota limit -*/ + * select quota limit + */ function quota_limit_select($select_name, $default_quota = 0) { - global $lang; + global $lang; + $quota_name = []; - $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; + $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query quota limits table #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query quota limits table #1'); + } - $quota_select = ''; + $quota_name[0]['quota_limit_id'] = 0; + $quota_name[0]['quota_desc'] = $lang['NOT_ASSIGNED']; - while ($row = DB()->sql_fetchrow($result)) - { - $quota_name[] = $row; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $quota_name[] = $row; + } + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($quota_name); $i++) - { - $selected = ($quota_name[$i]['quota_limit_id'] == $default_quota) ? ' selected="selected"' : ''; - $quota_select .= ''; - } - $quota_select .= ''; + foreach ($quota_name as $i => $iValue) { + $selected = ($quota_name[$i]['quota_limit_id'] == $default_quota) ? ' selected' : ''; + $quota_select .= ''; + } + $quota_select .= ''; - return $quota_select; + return $quota_select; } /** -* select default quota limit -*/ + * select default quota limit + */ function default_quota_limit_select($select_name, $default_quota = 0) { - global $lang; + global $lang; + $quota_name = []; - $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; + $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query quota limits table #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query quota limits table #2'); + } - $quota_select = ''; + $quota_name[0]['quota_limit_id'] = 0; + $quota_name[0]['quota_desc'] = $lang['NO_QUOTA_LIMIT']; - while ($row = DB()->sql_fetchrow($result)) - { - $quota_name[] = $row; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $quota_name[] = $row; + } + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($quota_name); $i++) - { - $selected = ( $quota_name[$i]['quota_limit_id'] == $default_quota ) ? ' selected="selected"' : ''; - $quota_select .= ''; - } - $quota_select .= ''; + foreach ($quota_name as $i => $iValue) { + $selected = ($quota_name[$i]['quota_limit_id'] == $default_quota) ? ' selected' : ''; + $quota_select .= ''; + } + $quota_select .= ''; - return $quota_select; -} \ No newline at end of file + return $quota_select; +} diff --git a/library/attach_mod/includes/functions_thumbs.php b/library/attach_mod/includes/functions_thumbs.php index 54b9035d2..65ac22227 100644 --- a/library/attach_mod/includes/functions_thumbs.php +++ b/library/attach_mod/includes/functions_thumbs.php @@ -1,189 +1,57 @@ $height) - { - return array( - round($width * ($max_width / $width)), - round($height * ($max_width / $width)) - ); - } - else - { - return array( - round($width * ($max_width / $height)), - round($height * ($max_width / $height)) - ); - } +if (!defined('BB_ROOT')) { + die(basename(__FILE__)); } /** -* Check if imagick is present -*/ -function is_imagick() + * Create thumbnail + * + * @param string $source + * @param string $newFile + * @param string $mimeType + * @return bool + * @throws Exception + */ +function createThumbnail(string $source, string $newFile, string $mimeType): bool { - global $imagick, $attach_config; + global $attach_config; - if ($attach_config['img_imagick'] != '') - { - $imagick = $attach_config['img_imagick']; - return true; - } - else - { - return false; - } + // Check for source image existence + if (!$source = realpath($source)) { + return false; + } + + // Checks the max allowed filesize + $min_filesize = (int)$attach_config['img_min_thumb_filesize']; + if (!filesize($source) || filesize($source) <= $min_filesize) { + return false; + } + + // Making the thumbnail image + try { + $image = new \claviska\SimpleImage(); + $image + ->fromFile($source) + ->autoOrient() + ->resize(150) + ->toFile($newFile, $mimeType, ['quality' => 85]); + } catch (Exception $e) { + // Handle errors + throw new Exception($e->getMessage()); + } + + // Check the thumbnail existence after creating + if (!is_file($newFile)) { + return false; + } + + return true; } - -/** -* Get supported image types -*/ -function get_supported_image_types($type) -{ - if (@extension_loaded('gd')) - { - $format = imagetypes(); - $new_type = 0; - - switch ($type) - { - case 1: - $new_type = ($format & IMG_GIF) ? IMG_GIF : 0; - break; - case 2: - case 9: - case 10: - case 11: - case 12: - $new_type = ($format & IMG_JPG) ? IMG_JPG : 0; - break; - case 3: - $new_type = ($format & IMG_PNG) ? IMG_PNG : 0; - break; - case 6: - case 15: - $new_type = ($format & IMG_WBMP) ? IMG_WBMP : 0; - break; - } - - return array( - 'gd' => ($new_type) ? true : false, - 'format' => $new_type, - 'version' => (function_exists('imagecreatetruecolor')) ? 2 : 1 - ); - } - - return array('gd' => false); -} - -/** -* Create thumbnail -*/ -function create_thumbnail($source, $new_file, $mimetype) -{ - global $attach_config, $imagick; - - $source = amod_realpath($source); - $min_filesize = (int) $attach_config['img_min_thumb_filesize']; - $img_filesize = (@file_exists($source)) ? @filesize($source) : false; - - if (!$img_filesize || $img_filesize <= $min_filesize) - { - return false; - } - - list($width, $height, $type, ) = getimagesize($source); - - if (!$width || !$height) - { - return false; - } - - list($new_width, $new_height) = get_img_size_format($width, $height); - - $tmp_path = $old_file = ''; - - $used_imagick = false; - - if (is_imagick()) - { - passthru($imagick . ' -quality 85 -antialias -sample ' . $new_width . 'x' . $new_height . ' "' . str_replace('\\', '/', $source) . '" +profile "*" "' . str_replace('\\', '/', $new_file) . '"'); - if (@file_exists($new_file)) - { - $used_imagick = true; - } - } - - if (!$used_imagick) - { - $type = get_supported_image_types($type); - - if ($type['gd']) - { - switch ($type['format']) - { - case IMG_GIF: - $image = imagecreatefromgif($source); - break; - case IMG_JPG: - $image = imagecreatefromjpeg($source); - break; - case IMG_PNG: - $image = imagecreatefrompng($source); - break; - case IMG_WBMP: - $image = imagecreatefromwbmp($source); - break; - } - - if ($type['version'] == 1 || !$attach_config['use_gd2']) - { - $new_image = imagecreate($new_width, $new_height); - imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); - } - else - { - $new_image = imagecreatetruecolor($new_width, $new_height); - imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); - } - - switch ($type['format']) - { - case IMG_GIF: - imagegif($new_image, $new_file); - break; - case IMG_JPG: - imagejpeg($new_image, $new_file, 90); - break; - case IMG_PNG: - imagepng($new_image, $new_file); - break; - case IMG_WBMP: - imagewbmp($new_image, $new_file); - break; - } - - imagedestroy($new_image); - } - } - - if (!@file_exists($new_file)) - { - return false; - } - - @chmod($new_file, 0664); - - return true; -} \ No newline at end of file diff --git a/library/attach_mod/posting_attachments.php b/library/attach_mod/posting_attachments.php index 368706b3a..cfc5f7468 100644 --- a/library/attach_mod/posting_attachments.php +++ b/library/attach_mod/posting_attachments.php @@ -1,1358 +1,23 @@ add_attachment_body = get_var('add_attachment_body', 0); - $this->posted_attachments_body = get_var('posted_attachments_body', 0); - - $this->file_comment = get_var('filecomment', ''); - $this->attachment_id_list = get_var('attach_id_list', array(0)); - $this->attachment_comment_list = get_var('comment_list', array('')); - $this->attachment_filesize_list = get_var('filesize_list', array(0)); - $this->attachment_filetime_list = get_var('filetime_list', array(0)); - $this->attachment_filename_list = get_var('filename_list', array('')); - $this->attachment_extension_list = get_var('extension_list', array('')); - $this->attachment_mimetype_list = get_var('mimetype_list', array('')); - - $this->filename = (isset($_FILES['fileupload']) && isset($_FILES['fileupload']['name']) && $_FILES['fileupload']['name'] != 'none') ? trim(stripslashes($_FILES['fileupload']['name'])) : ''; - - $this->attachment_list = get_var('attachment_list', array('')); - $this->attachment_thumbnail_list = get_var('attach_thumbnail_list', array(0)); - } - - /** - * Get Quota Limits - */ - function get_quota_limits($userdata_quota, $user_id = 0) - { - global $attach_config; - -// $priority = 'group;user'; - $priority = 'user;group'; - - if (IS_ADMIN) - { - $attach_config['pm_filesize_limit'] = 0; // Unlimited - $attach_config['upload_filesize_limit'] = 0; // Unlimited - return; - } - - $quota_type = QUOTA_UPLOAD_LIMIT; - $limit_type = 'upload_filesize_limit'; - $default = 'attachment_quota'; - - if (!$user_id) - { - $user_id = intval($userdata_quota['user_id']); - } - - $priority = explode(';', $priority); - $found = false; - - for ($i = 0; $i < sizeof($priority); $i++) - { - if (($priority[$i] == 'group') && (!$found)) - { - // Get Group Quota, if we find one, we have our quota - $sql = 'SELECT u.group_id - FROM ' . BB_USER_GROUP . ' u, ' . BB_GROUPS . ' g - WHERE g.group_single_user = 0 - AND u.user_pending = 0 - AND u.group_id = g.group_id - AND u.user_id = ' . $user_id; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get user group'); - } - - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); - - if ($num_rows > 0) - { - $group_id = array(); - - for ($j = 0; $j < $num_rows; $j++) - { - $group_id[] = (int) $rows[$j]['group_id']; - } - - $sql = 'SELECT l.quota_limit - FROM ' . BB_QUOTA . ' q, ' . BB_QUOTA_LIMITS . ' l - WHERE q.group_id IN (' . implode(', ', $group_id) . ') - AND q.group_id <> 0 - AND q.quota_type = ' . $quota_type . ' - AND q.quota_limit_id = l.quota_limit_id - ORDER BY l.quota_limit DESC - LIMIT 1'; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group quota'); - } - - if (DB()->num_rows($result) > 0) - { - $row = DB()->sql_fetchrow($result); - $attach_config[$limit_type] = $row['quota_limit']; - $found = TRUE; - } - DB()->sql_freeresult($result); - } - } - - if ($priority[$i] == 'user' && !$found) - { - // Get User Quota, if the user is not in a group or the group has no quotas - $sql = 'SELECT l.quota_limit - FROM ' . BB_QUOTA . ' q, ' . BB_QUOTA_LIMITS . ' l - WHERE q.user_id = ' . $user_id . ' - AND q.user_id <> 0 - AND q.quota_type = ' . $quota_type . ' - AND q.quota_limit_id = l.quota_limit_id - LIMIT 1'; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get user quota'); - } - - if (DB()->num_rows($result) > 0) - { - $row = DB()->sql_fetchrow($result); - $attach_config[$limit_type] = $row['quota_limit']; - $found = TRUE; - } - DB()->sql_freeresult($result); - } - } - - if (!$found) - { - // Set Default Quota Limit - $quota_id = ($quota_type == QUOTA_UPLOAD_LIMIT) ? $attach_config['default_upload_quota'] : $attach_config['default_pm_quota']; - - if ($quota_id == 0) - { - $attach_config[$limit_type] = $attach_config[$default]; - } - else - { - $sql = 'SELECT quota_limit - FROM ' . BB_QUOTA_LIMITS . ' - WHERE quota_limit_id = ' . (int) $quota_id . ' - LIMIT 1'; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get default quota limit'); - } - - if (DB()->num_rows($result) > 0) - { - $row = DB()->sql_fetchrow($result); - $attach_config[$limit_type] = $row['quota_limit']; - } - else - { - $attach_config[$limit_type] = $attach_config[$default]; - } - DB()->sql_freeresult($result); - } - } - - // Never exceed the complete Attachment Upload Quota - if ($quota_type == QUOTA_UPLOAD_LIMIT) - { - if ($attach_config[$limit_type] > $attach_config[$default]) - { - $attach_config[$limit_type] = $attach_config[$default]; - } - } - } - - /** - * Handle all modes... (intern) - * @private - */ - function handle_attachments($mode) - { - global $is_auth, $attach_config, $refresh, $post_id, $submit, $preview, $error, $error_msg, $lang; - - // - // ok, what shall we do ;) - // - - if (IS_ADMIN) - { - $max_attachments = ADMIN_MAX_ATTACHMENTS; - } - else - { - $max_attachments = intval($attach_config['max_attachments']); - } - - $sql_id = 'post_id'; - - // nothing, if the user is not authorized or attachment mod disabled - if (intval($attach_config['disable_mod']) || !$is_auth['auth_attachments']) - { - return false; - } - - // Init Vars - $attachments = array(); - - if (!$refresh) - { - $add = (isset($_POST['add_attachment'])) ? TRUE : FALSE; - $delete = (isset($_POST['del_attachment'])) ? TRUE : FALSE; - $edit = ( isset($_POST['edit_comment']) ) ? TRUE : FALSE; - $update_attachment = ( isset($_POST['update_attachment']) ) ? TRUE : FALSE; - $del_thumbnail = ( isset($_POST['del_thumbnail']) ) ? TRUE : FALSE; - - $add_attachment_box = (!empty($_POST['add_attachment_box'])) ? TRUE : FALSE; - $posted_attachments_box = (!empty($_POST['posted_attachments_box'])) ? TRUE : FALSE; - - $refresh = $add || $delete || $edit || $del_thumbnail || $update_attachment || $add_attachment_box || $posted_attachments_box; - } - - // Get Attachments - $attachments = get_attachments_from_post($post_id); - - $auth = ($is_auth['auth_edit'] || $is_auth['auth_mod']) ? TRUE : FALSE; - - if (!$submit && $mode == 'editpost' && $auth) - { - if (!$refresh && !$preview && !$error) - { - for ($i = 0; $i < sizeof($attachments); $i++) - { - $this->attachment_list[] = $attachments[$i]['physical_filename']; - $this->attachment_comment_list[] = $attachments[$i]['comment']; - $this->attachment_filename_list[] = $attachments[$i]['real_filename']; - $this->attachment_extension_list[] = $attachments[$i]['extension']; - $this->attachment_mimetype_list[] = $attachments[$i]['mimetype']; - $this->attachment_filesize_list[] = $attachments[$i]['filesize']; - $this->attachment_filetime_list[] = $attachments[$i]['filetime']; - $this->attachment_id_list[] = $attachments[$i]['attach_id']; - $this->attachment_thumbnail_list[] = $attachments[$i]['thumbnail']; - } - } - } - - $this->num_attachments = sizeof($this->attachment_list); - - if ($submit) - { - if ($mode == 'newtopic' || $mode == 'reply' || $mode == 'editpost') - { - if ($this->filename != '') - { - if ($this->num_attachments < intval($max_attachments)) - { - $this->upload_attachment($this->page); - - if (!$error && $this->post_attach) - { - array_unshift($this->attachment_list, $this->attach_filename); - array_unshift($this->attachment_comment_list, $this->file_comment); - array_unshift($this->attachment_filename_list, $this->filename); - array_unshift($this->attachment_extension_list, $this->extension); - array_unshift($this->attachment_mimetype_list, $this->type); - array_unshift($this->attachment_filesize_list, $this->filesize); - array_unshift($this->attachment_filetime_list, $this->filetime); - array_unshift($this->attachment_id_list, '0'); - array_unshift($this->attachment_thumbnail_list, $this->thumbnail); - - $this->file_comment = ''; - $this->post_attach = FALSE; - } - } - else - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['TOO_MANY_ATTACHMENTS'], intval($max_attachments)); - } - } - } - } - - if ($preview || $refresh || $error) - { - $delete_attachment = ( isset($_POST['del_attachment']) ) ? TRUE : FALSE; - $delete_thumbnail = (isset($_POST['del_thumbnail'])) ? TRUE : FALSE; - - $add_attachment = (isset($_POST['add_attachment'])) ? TRUE : FALSE; - $edit_attachment = (isset($_POST['edit_comment'])) ? TRUE : FALSE; - $update_attachment = (isset($_POST['update_attachment']) ) ? TRUE : FALSE; - - // Perform actions on temporary attachments - if ($delete_attachment || $delete_thumbnail) - { - // store old values - $actual_id_list = get_var('attach_id_list', array(0)); - $actual_comment_list = get_var('comment_list', array('')); - $actual_filename_list = get_var('filename_list', array('')); - $actual_extension_list = get_var('extension_list', array('')); - $actual_mimetype_list = get_var('mimetype_list', array('')); - $actual_filesize_list = get_var('filesize_list', array(0)); - $actual_filetime_list = get_var('filetime_list', array(0)); - - $actual_list = get_var('attachment_list', array('')); - $actual_thumbnail_list = get_var('attach_thumbnail_list', array(0)); - - // clean values - $this->attachment_list = array(); - $this->attachment_comment_list = array(); - $this->attachment_filename_list = array(); - $this->attachment_extension_list = array(); - $this->attachment_mimetype_list = array(); - $this->attachment_filesize_list = array(); - $this->attachment_filetime_list = array(); - $this->attachment_id_list = array(); - $this->attachment_thumbnail_list = array(); - - // restore values :) - if (isset($_POST['attachment_list'])) - { - for ($i = 0; $i < sizeof($actual_list); $i++) - { - $restore = FALSE; - $del_thumb = FALSE; - - if ($delete_thumbnail) - { - if ( !isset($_POST['del_thumbnail'][$actual_list[$i]]) ) - { - $restore = TRUE; - } - else - { - $del_thumb = TRUE; - } - } - if ( $delete_attachment ) - { - if ( !isset($_POST['del_attachment'][$actual_list[$i]]) ) - { - $restore = TRUE; - } - } - - if ( $restore ) - { - $this->attachment_list[] = $actual_list[$i]; - $this->attachment_comment_list[] = $actual_comment_list[$i]; - $this->attachment_filename_list[] = $actual_filename_list[$i]; - $this->attachment_extension_list[] = $actual_extension_list[$i]; - $this->attachment_mimetype_list[] = $actual_mimetype_list[$i]; - $this->attachment_filesize_list[] = $actual_filesize_list[$i]; - $this->attachment_filetime_list[] = $actual_filetime_list[$i]; - $this->attachment_id_list[] = $actual_id_list[$i]; - $this->attachment_thumbnail_list[] = $actual_thumbnail_list[$i]; - } - else if (!$del_thumb) - { - // delete selected attachment - if ($actual_id_list[$i] == '0' ) - { - unlink_attach($actual_list[$i]); - - if ($actual_thumbnail_list[$i] == 1) - { - unlink_attach($actual_list[$i], MODE_THUMBNAIL); - } - } - else - { - delete_attachment($post_id, $actual_id_list[$i], $this->page); - } - } - else if ($del_thumb) - { - // delete selected thumbnail - $this->attachment_list[] = $actual_list[$i]; - $this->attachment_comment_list[] = $actual_comment_list[$i]; - $this->attachment_filename_list[] = $actual_filename_list[$i]; - $this->attachment_extension_list[] = $actual_extension_list[$i]; - $this->attachment_mimetype_list[] = $actual_mimetype_list[$i]; - $this->attachment_filesize_list[] = $actual_filesize_list[$i]; - $this->attachment_filetime_list[] = $actual_filetime_list[$i]; - $this->attachment_id_list[] = $actual_id_list[$i]; - $this->attachment_thumbnail_list[] = 0; - - if ($actual_id_list[$i] == 0) - { - unlink_attach($actual_list[$i], MODE_THUMBNAIL); - } - else - { - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET thumbnail = 0 WHERE attach_id = ' . (int) $actual_id_list[$i]; - - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update ' . BB_ATTACHMENTS_DESC); - } - } - } - } - } - } - else if ($edit_attachment || $update_attachment || $add_attachment || $preview) - { - if ($edit_attachment) - { - $actual_comment_list = get_var('comment_list', array('')); - - $this->attachment_comment_list = array(); - - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - $this->attachment_comment_list[$i] = $actual_comment_list[$i]; - } - } - - if ($update_attachment) - { - if ($this->filename == '') - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= $lang['ERROR_EMPTY_ADD_ATTACHBOX']; - } - - $this->upload_attachment($this->page); - - if (!$error) - { - $actual_list = get_var('attachment_list', array('')); - $actual_id_list = get_var('attach_id_list', array(0)); - - $attachment_id = 0; - $actual_element = 0; - - for ($i = 0; $i < sizeof($actual_id_list); $i++) - { - if (isset($_POST['update_attachment'][$actual_id_list[$i]])) - { - $attachment_id = intval($actual_id_list[$i]); - $actual_element = $i; - } - } - - // Get current informations to delete the Old Attachment - $sql = 'SELECT physical_filename, comment, thumbnail - FROM ' . BB_ATTACHMENTS_DESC . ' - WHERE attach_id = ' . (int) $attachment_id; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to select old attachment entry'); - } - - if (DB()->num_rows($result) != 1) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= $lang['ERROR_MISSING_OLD_ENTRY']; - } - - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - - $comment = (trim($this->file_comment) == '') ? trim($row['comment']) : trim($this->file_comment); - - // Update Entry - $sql_ary = array( - 'physical_filename' => (string) basename($this->attach_filename), - 'real_filename' => (string) basename($this->filename), - 'comment' => (string) $comment, - 'extension' => (string) strtolower($this->extension), - 'mimetype' => (string) strtolower($this->type), - 'filesize' => (int) $this->filesize, - 'filetime' => (int) $this->filetime, - 'thumbnail' => (int) $this->thumbnail - ); - - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' - WHERE attach_id = ' . (int) $attachment_id; - - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update the attachment'); - } - - // Delete the Old Attachment - unlink_attach($row['physical_filename']); - - if (intval($row['thumbnail']) == 1) - { - unlink_attach($row['physical_filename'], MODE_THUMBNAIL); - } - - //bt - if ($this->attachment_extension_list[$actual_element] === TORRENT_EXT && $attachments[$actual_element]['tracker_status']) - { - include(INC_DIR .'functions_torrent.php'); - tracker_unregister($attachment_id); - } - //bt end - - // Make sure it is displayed - $this->attachment_list[$actual_element] = $this->attach_filename; - $this->attachment_comment_list[$actual_element] = $comment; - $this->attachment_filename_list[$actual_element] = $this->filename; - $this->attachment_extension_list[$actual_element] = $this->extension; - $this->attachment_mimetype_list[$actual_element] = $this->type; - $this->attachment_filesize_list[$actual_element] = $this->filesize; - $this->attachment_filetime_list[$actual_element] = $this->filetime; - $this->attachment_id_list[$actual_element] = $actual_id_list[$actual_element]; - $this->attachment_thumbnail_list[$actual_element] = $this->thumbnail; - $this->file_comment = ''; - } - } - - if (($add_attachment || $preview) && $this->filename != '') - { - if ($this->num_attachments < intval($max_attachments)) - { - $this->upload_attachment($this->page); - - if (!$error) - { - array_unshift($this->attachment_list, $this->attach_filename); - array_unshift($this->attachment_comment_list, $this->file_comment); - array_unshift($this->attachment_filename_list, $this->filename); - array_unshift($this->attachment_extension_list, $this->extension); - array_unshift($this->attachment_mimetype_list, $this->type); - array_unshift($this->attachment_filesize_list, $this->filesize); - array_unshift($this->attachment_filetime_list, $this->filetime); - array_unshift($this->attachment_id_list, '0'); - array_unshift($this->attachment_thumbnail_list, $this->thumbnail); - - $this->file_comment = ''; - } - } - else - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['TOO_MANY_ATTACHMENTS'], intval($max_attachments)); - } - } - } - } - - return TRUE; - } - - /** - * Basic Insert Attachment Handling for all Message Types - */ - function do_insert_attachment($mode, $message_type, $message_id) - { - global $upload_dir; - - if (intval($message_id) < 0) - { - return FALSE; - } - - global $post_info, $userdata; - - $post_id = (int) $message_id; - $user_id_1 = (isset($post_info['poster_id'])) ? (int) $post_info['poster_id'] : 0; - - if (!$user_id_1) - { - $user_id_1 = (int) $userdata['user_id']; - } - - if ($mode == 'attach_list') - { - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - if ($this->attachment_id_list[$i]) - { - //bt - if ($this->attachment_extension_list[$i] === TORRENT_EXT && !defined('TORRENT_ATTACH_ID')) - { - define('TORRENT_ATTACH_ID', $this->attachment_id_list[$i]); - } - //bt end - - // update entry in db if attachment already stored in db and filespace - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . " - SET comment = '" . @attach_mod_sql_escape($this->attachment_comment_list[$i]) . "' - WHERE attach_id = " . $this->attachment_id_list[$i]; - - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update the file comment'); - } - } - else - { - if (empty($this->attachment_mimetype_list[$i]) && $this->attachment_extension_list[$i] === TORRENT_EXT) - { - $this->attachment_mimetype_list[$i] = 'application/x-bittorrent'; - } - - // insert attachment into db - $sql_ary = array( - 'physical_filename' => (string) basename($this->attachment_list[$i]), - 'real_filename' => (string) basename($this->attachment_filename_list[$i]), - 'comment' => (string) @$this->attachment_comment_list[$i], - 'extension' => (string) strtolower($this->attachment_extension_list[$i]), - 'mimetype' => (string) strtolower($this->attachment_mimetype_list[$i]), - 'filesize' => (int) $this->attachment_filesize_list[$i], - 'filetime' => (int) $this->attachment_filetime_list[$i], - 'thumbnail' => (int) $this->attachment_thumbnail_list[$i] - ); - - $sql = 'INSERT INTO ' . BB_ATTACHMENTS_DESC . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
    Your '. $message_type .' has been stored'); - } - - $attach_id = DB()->sql_nextid(); - - //bt - if ($this->attachment_extension_list[$i] === TORRENT_EXT && !defined('TORRENT_ATTACH_ID')) - { - define('TORRENT_ATTACH_ID', $attach_id); - } - //bt end - - $sql_ary = array( - 'attach_id' => (int) $attach_id, - 'post_id' => (int) $post_id, - 'user_id_1' => (int) $user_id_1, - ); - - $sql = 'INSERT INTO ' . BB_ATTACHMENTS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
    Your '. $message_type .' has been stored'); - } - } - } - - return TRUE; - } - - if ($mode == 'last_attachment') - { - if ($this->post_attach && !isset($_POST['update_attachment'])) - { - // insert attachment into db, here the user submited it directly - $sql_ary = array( - 'physical_filename' => (string) basename($this->attach_filename), - 'real_filename' => (string) basename($this->filename), - 'comment' => (string) $this->file_comment, - 'extension' => (string) strtolower($this->extension), - 'mimetype' => (string) strtolower($this->type), - 'filesize' => (int) $this->filesize, - 'filetime' => (int) $this->filetime, - 'thumbnail' => (int) $this->thumbnail - ); - - $sql = 'INSERT INTO ' . BB_ATTACHMENTS_DESC . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - - // Inform the user that his post has been created, but nothing is attached - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
    Your '. $message_type .' has been stored'); - } - - $attach_id = DB()->sql_nextid(); - - $sql_ary = array( - 'attach_id' => (int) $attach_id, - 'post_id' => (int) $post_id, - 'user_id_1' => (int) $user_id_1, - ); - - $sql = 'INSERT INTO ' . BB_ATTACHMENTS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
    Your '. $message_type .' has been stored'); - } - } - } - } - - /** - * Attachment Mod entry switch/output (intern) - * @private - */ - function display_attachment_bodies() - { - global $attach_config, $is_auth, $lang, $template, $upload_dir, $forum_id; - - // Choose what to display - $value_add = $value_posted = 0; - - $this->add_attachment_body = 1; - $this->posted_attachments_body = 1; - - $s_hidden = ''; - $s_hidden .= ''; - - $template->assign_vars(array( - 'ADD_ATTACH_HIDDEN_FIELDS' => $s_hidden, - )); - - $attachments = array(); - - if (sizeof($this->attachment_list) > 0) - { - $hidden = ''; - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - - if (!$this->posted_attachments_body || sizeof($this->attachment_list) == 0) - { - $hidden .= ''; - } - } - $template->assign_var('POSTED_ATTACHMENTS_HIDDEN_FIELDS', $hidden); - } - - if ($this->add_attachment_body) - { - $template->assign_vars(array( - 'TPL_ADD_ATTACHMENT' => true, - 'FILE_COMMENT' => htmlspecialchars($this->file_comment), - 'FILESIZE' => $attach_config['max_filesize'], - 'FILENAME' => htmlspecialchars($this->filename), - 'S_FORM_ENCTYPE' => 'enctype="multipart/form-data"', - )); - } - - if ($this->posted_attachments_body && sizeof($this->attachment_list) > 0) - { - $template->assign_vars(array( - 'TPL_POSTED_ATTACHMENTS' => true, - )); - - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - if (@$this->attachment_id_list[$i] == 0) - { - $download_link = $upload_dir . '/' . basename($this->attachment_list[$i]); - } - else - { - $download_link = BB_ROOT . DOWNLOAD_URL . $this->attachment_id_list[$i]; - } - - $template->assign_block_vars('attach_row', array( - 'FILE_NAME' => @htmlspecialchars($this->attachment_filename_list[$i]), - 'ATTACH_FILENAME' => @$this->attachment_list[$i], - 'FILE_COMMENT' => @htmlspecialchars($this->attachment_comment_list[$i]), - 'ATTACH_ID' => @$this->attachment_id_list[$i], - 'U_VIEW_ATTACHMENT' => $download_link, - )); - - // Thumbnail there ? And is the User Admin or Mod ? Then present the 'Delete Thumbnail' Button - if (@intval($this->attachment_thumbnail_list[$i]) == 1 && ((isset($is_auth['auth_mod']) && $is_auth['auth_mod']) || IS_ADMIN)) - { - $template->assign_block_vars('attach_row.switch_thumbnail', array()); - } - - if (@$this->attachment_id_list[$i]) - { - $template->assign_block_vars('attach_row.switch_update_attachment', array()); - } - } - } - - $template->assign_var('ATTACHBOX'); - } - - /** - * Upload an Attachment to Filespace (intern) - */ - function upload_attachment() - { - global $error, $error_msg, $lang, $attach_config, $userdata, $upload_dir, $forum_id; - - $this->post_attach = ($this->filename != '') ? TRUE : FALSE; - - if ($this->post_attach) - { - $r_file = trim(basename($this->filename)); - $file = $_FILES['fileupload']['tmp_name']; - $this->type = $_FILES['fileupload']['type']; - - if (isset($_FILES['fileupload']['size']) && $_FILES['fileupload']['size'] == 0) - { - bb_die('Tried to upload empty file'); - } - - $this->type = strtolower($this->type); - $this->extension = strtolower(get_extension($this->filename)); - - $this->filesize = @filesize($file); - $this->filesize = intval($this->filesize); - - $sql = 'SELECT g.allow_group, g.max_filesize, g.cat_id, g.forum_permissions - FROM ' . BB_EXTENSION_GROUPS . ' g, ' . BB_EXTENSIONS . " e - WHERE g.group_id = e.group_id - AND e.extension = '" . attach_mod_sql_escape($this->extension) . "' - LIMIT 1"; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extensions'); - } - - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - - $allowed_filesize = ($row['max_filesize']) ? $row['max_filesize'] : $attach_config['max_filesize']; - $cat_id = intval($row['cat_id']); - $auth_cache = trim($row['forum_permissions']); - - // check Filename - if (preg_match("#[\\/:*?\"<>|]#i", $this->filename)) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['INVALID_FILENAME'], htmlspecialchars($this->filename)); - } - - // check php upload-size - if (!$error && $file == 'none') - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $ini_val = 'ini_get'; - - $max_size = @$ini_val('upload_max_filesize'); - - if ($max_size == '') - { - $error_msg .= $lang['ATTACHMENT_PHP_SIZE_NA']; - } - else - { - $error_msg .= sprintf($lang['ATTACHMENT_PHP_SIZE_OVERRUN'], $max_size); - } - } - - // Check Extension - if (!$error && intval($row['allow_group']) == 0) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['DISALLOWED_EXTENSION'], htmlspecialchars($this->extension)); - } - - // Check Forum Permissions - if (!$error && !IS_ADMIN && !is_forum_authed($auth_cache, $forum_id) && trim($auth_cache) != '') - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['DISALLOWED_EXTENSION_WITHIN_FORUM'], htmlspecialchars($this->extension)); - } - - //bt - // Check if user can post torrent - global $post_data; - - if (!$error && $this->extension === TORRENT_EXT && !$post_data['first_post']) - { - $error = TRUE; - if (!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= $lang['ALLOWED_ONLY_1ST_POST_ATTACH']; - } - //bt end - - // Upload File - - $this->thumbnail = 0; - - if (!$error) - { - // - // Prepare Values - $this->filetime = TIMENOW; - - $this->filename = $r_file; - - // physical filename - //$this->attach_filename = strtolower($this->filename); - $this->attach_filename = $this->filename; - - //bt - if (FILENAME_CRYPTIC) - { - $this->attach_filename = make_rand_str(FILENAME_CRYPTIC_LENGTH); - } - else - { // original - $this->attach_filename = html_entity_decode(trim(stripslashes($this->attach_filename))); - $this->attach_filename = delete_extension($this->attach_filename); - $this->attach_filename = str_replace(array(' ','-'), array('_','_'), $this->attach_filename); - $this->attach_filename = str_replace('__', '_', $this->attach_filename); - $this->attach_filename = str_replace(array(',', '.', '!', '?', 'ь', 'Ь', 'ц', 'Ц', 'д', 'Д', ';', ':', '@', "'", '"', '&'), array('', '', '', '', 'ue', 'ue', 'oe', 'oe', 'ae', 'ae', '', '', '', '', '', 'and'), $this->attach_filename); - $this->attach_filename = str_replace(array('$', 'Я', '>','<','§','%','=','/','(',')','#','*','+',"\\",'{','}','[',']'), array('dollar', 'ss','greater','lower','paragraph','percent','equal','','','','','','','','','','',''), $this->attach_filename); - // Remove non-latin characters - $this->attach_filename = preg_replace('#([\xC2\xC3])([\x80-\xBF])#', 'chr(ord(\'$1\')<<6&0xC0|ord(\'$2\')&0x3F)', $this->attach_filename); - $this->attach_filename = rawurlencode($this->attach_filename); - $this->attach_filename = preg_replace("/(%[0-9A-F]{1,2})/i", '', $this->attach_filename); - $this->attach_filename = trim($this->attach_filename); - } - $this->attach_filename = str_replace(array('&','&',' '), '_', $this->attach_filename); - $this->attach_filename = str_replace('php', '_php_', $this->attach_filename); - $this->attach_filename = substr(trim($this->attach_filename), 0, FILENAME_MAX_LENGTH); - - for ($i=0, $max_try=5; $i <= $max_try; $i++) - { - $fn_prefix = make_rand_str(FILENAME_PREFIX_LENGTH) .'_'; - $new_physical_filename = clean_filename($fn_prefix . $this->attach_filename); - - if (!physical_filename_already_stored($new_physical_filename)) - { - break; - } - if ($i == $max_try) - { - bb_die('Could not create filename for attachment'); - } - } - $this->attach_filename = $new_physical_filename; - - // Do we have to create a thumbnail ? - if ($cat_id == IMAGE_CAT && intval($attach_config['img_create_thumbnail'])) - { - $this->thumbnail = 1; - } - } - - if ($error) - { - $this->post_attach = FALSE; - return; - } - - // Upload Attachment - if (!$error) - { - // Descide the Upload method - $ini_val = 'ini_get'; - - $safe_mode = @$ini_val('safe_mode'); - - if (@$ini_val('open_basedir')) - { - $upload_mode = 'move'; - } - else if ( @$ini_val('safe_mode') ) - { - $upload_mode = 'move'; - } - else - { - $upload_mode = 'copy'; - } - - // Ok, upload the Attachment - if (!$error) - { - $this->move_uploaded_attachment($upload_mode, $file); - } - } - - // Now, check filesize parameters - if (!$error) - { - if (!$this->filesize) - { - $this->filesize = intval(@filesize($upload_dir . '/' . $this->attach_filename)); - } - } - - // Check Image Size, if it's an image - if (!$error && !IS_ADMIN && $cat_id == IMAGE_CAT) - { - list($width, $height) = image_getdimension($upload_dir . '/' . $this->attach_filename); - - if ($width != 0 && $height != 0 && intval($attach_config['img_max_width']) != 0 && intval($attach_config['img_max_height']) != 0) - { - if ($width > intval($attach_config['img_max_width']) || $height > intval($attach_config['img_max_height'])) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['ERROR_IMAGESIZE'], intval($attach_config['img_max_width']), intval($attach_config['img_max_height'])); - } - } - } - - // check Filesize - if (!$error && $allowed_filesize != 0 && $this->filesize > $allowed_filesize && !(IS_ADMIN || IS_MOD || IS_GROUP_MEMBER)) - { - $allowed_filesize = humn_size($allowed_filesize); - - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['ATTACHMENT_TOO_BIG'], $allowed_filesize); - } - - // Check our complete quota - if ($attach_config['attachment_quota']) - { - $sql = 'SELECT sum(filesize) as total FROM ' . BB_ATTACHMENTS_DESC; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query total filesize #1'); - } - - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - - $total_filesize = $row['total']; - - if (($total_filesize + $this->filesize) > $attach_config['attachment_quota']) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= $lang['ATTACH_QUOTA_REACHED']; - } - - } - - $this->get_quota_limits($userdata); - - // Check our user quota - if ($attach_config['upload_filesize_limit']) - { - $sql = 'SELECT attach_id - FROM ' . BB_ATTACHMENTS . ' - WHERE user_id_1 = ' . (int) $userdata['user_id'] . ' - GROUP BY attach_id'; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments'); - } - - $attach_ids = DB()->sql_fetchrowset($result); - $num_attach_ids = DB()->num_rows($result); - DB()->sql_freeresult($result); - - $attach_id = array(); - - for ($i = 0; $i < $num_attach_ids; $i++) - { - $attach_id[] = intval($attach_ids[$i]['attach_id']); - } - - if ($num_attach_ids > 0) - { - // Now get the total filesize - $sql = 'SELECT sum(filesize) as total - FROM ' . BB_ATTACHMENTS_DESC . ' - WHERE attach_id IN (' . implode(', ', $attach_id) . ')'; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query total filesize #2'); - } - - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - $total_filesize = $row['total']; - } - else - { - $total_filesize = 0; - } - - if (($total_filesize + $this->filesize) > $attach_config['upload_filesize_limit']) - { - $upload_filesize_limit = $attach_config['upload_filesize_limit']; - $size_lang = ($upload_filesize_limit >= 1048576) ? $lang['MB'] : ( ($upload_filesize_limit >= 1024) ? $lang['KB'] : $lang['BYTES'] ); - - if ($upload_filesize_limit >= 1048576) - { - $upload_filesize_limit = round($upload_filesize_limit / 1048576 * 100) / 100; - } - else if($upload_filesize_limit >= 1024) - { - $upload_filesize_limit = round($upload_filesize_limit / 1024 * 100) / 100; - } - - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['USER_UPLOAD_QUOTA_REACHED'], $upload_filesize_limit, $size_lang); - } - } - - if ($error) - { - unlink_attach($this->attach_filename); - unlink_attach($this->attach_filename, MODE_THUMBNAIL); - $this->post_attach = FALSE; - } - } - } - - // Copy the temporary attachment to the right location (copy, move_uploaded_file) - function move_uploaded_attachment($upload_mode, $file) - { - global $error, $error_msg, $lang, $upload_dir; - - if (!is_uploaded_file($file)) - { - bb_die('Unable to upload file. The given source has not been uploaded'); - } - - switch ($upload_mode) - { - case 'copy': - - if (!@copy($file, $upload_dir . '/' . basename($this->attach_filename))) - { - if (!@move_uploaded_file($file, $upload_dir . '/' . basename($this->attach_filename))) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['GENERAL_UPLOAD_ERROR'], './' . $upload_dir . '/' . $this->attach_filename); - return; - } - } - @chmod($upload_dir . '/' . basename($this->attach_filename), 0666); - - break; - - case 'move': - - if (!@move_uploaded_file($file, $upload_dir . '/' . basename($this->attach_filename))) - { - if (!@copy($file, $upload_dir . '/' . basename($this->attach_filename))) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
    '; - } - $error_msg .= sprintf($lang['GENERAL_UPLOAD_ERROR'], './' . $upload_dir . '/' . $this->attach_filename); - return; - } - } - @chmod($upload_dir . '/' . $this->attach_filename, 0666); - - break; - } - - if (!$error && $this->thumbnail == 1) - { - $source = $upload_dir . '/' . basename($this->attach_filename); - $dest_file = amod_realpath($upload_dir); - $dest_file .= '/' . THUMB_DIR . '/t_' . basename($this->attach_filename); - - if (!create_thumbnail($source, $dest_file, $this->type)) - { - if (!$file || !create_thumbnail($file, $dest_file, $this->type)) - { - $this->thumbnail = 0; - } - } - } - } +/** + * TorrentPier – Bull-powered BitTorrent tracker engine + * + * @copyright Copyright (c) 2005-2025 TorrentPier (https://torrentpier.com) + * @link https://github.com/torrentpier/torrentpier for the canonical source repository + * @license https://github.com/torrentpier/torrentpier/blob/master/LICENSE MIT License + */ + +if (!defined('BB_ROOT')) { + die(basename(__FILE__)); } /** -* @package attachment_mod -* Attachment posting -*/ -class attach_posting extends attach_parent -{ - /** - * Constructor - */ - function attach_posting() - { - $this->attach_parent(); - $this->page = 0; - } - - /** - * Insert an Attachment into a Post (this is the second function called from posting.php) - */ - function insert_attachment($post_id) - { - global $is_auth, $mode; - - // Insert Attachment ? - if (!empty($post_id) && ($mode == 'newtopic' || $mode == 'reply' || $mode == 'editpost') && $is_auth['auth_attachments']) - { - $this->do_insert_attachment('attach_list', 'post', $post_id); - $this->do_insert_attachment('last_attachment', 'post', $post_id); - - if ((sizeof($this->attachment_list) > 0 || $this->post_attach) && !isset($_POST['update_attachment'])) - { - $sql = 'UPDATE ' . BB_POSTS . ' SET post_attachment = 1 WHERE post_id = ' . (int) $post_id; - - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update posts table'); - } - - $sql = 'SELECT topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int) $post_id; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to select posts table'); - } - - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - - $sql = 'UPDATE ' . BB_TOPICS . ' SET topic_attachment = 1 WHERE topic_id = ' . (int) $row['topic_id']; - - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update topics table'); - } - } - } - } - - /** - * Handle Attachments (Add/Delete/Edit/Show) - This is the first function called from every message handler - */ - function posting_attachment_mod() - { - global $mode, $confirm, $is_auth, $post_id, $delete, $refresh; - - if (!$refresh) - { - $add_attachment_box = (!empty($_POST['add_attachment_box'])) ? TRUE : FALSE; - $posted_attachments_box = (!empty($_POST['posted_attachments_box'])) ? TRUE : FALSE; - - $refresh = $add_attachment_box || $posted_attachments_box; - } - - // Choose what to display - $result = $this->handle_attachments($mode); - - if ($result === false) - { - return; - } - - if ($confirm && ($delete || $mode == 'delete' || $mode == 'editpost') && ($is_auth['auth_delete'] || $is_auth['auth_mod'])) - { - if ($post_id) - { - delete_attachment($post_id); - } - } - - $this->display_attachment_bodies(); - } - -} - -/** -* Entry Point -*/ + * Entry Point + */ function execute_posting_attachment_handling() { - global $attachment_mod; + global $attachment_mod; - $attachment_mod['posting'] = new attach_posting(); - $attachment_mod['posting']->posting_attachment_mod(); -} \ No newline at end of file + $attachment_mod['posting'] = new TorrentPier\Legacy\AttachPosting(); + $attachment_mod['posting']->posting_attachment_mod(); +} diff --git a/library/config.php b/library/config.php index 2e7d35932..75732614c 100644 --- a/library/config.php +++ b/library/config.php @@ -1,649 +1,837 @@ (array) srv_cfg; -// порядок параметров srv_cfg (хост, название базы, пользователь, пароль, charset, pconnect); -$bb_cfg['db'] = array( - 'db1' => array('localhost', 'dbase', 'user', 'pass', $charset, $pconnect), - //'db2' => array('localhost2', 'dbase2', 'user2', 'pass2', $charset, $pconnect), - //'db3' => array('localhost3', 'dbase3', 'user2', 'pass3', $charset, $pconnect), -); - -$bb_cfg['db_alias'] = array( -// 'alias' => 'srv_name' -# db1 - 'log' => 'db1', // BB_LOG - 'search' => 'db1', // BB_TOPIC_SEARCH - 'sres' => 'db1', // BB_BT_USER_SETTINGS, BB_SEARCH_RESULTS - 'u_ses' => 'db1', // BB_USER_SES, BB_USER_LASTVISIT -# db2 - 'dls' => 'db1', // BB_BT_DLS_* - 'ip' => 'db1', // BB_POSTS_IP - 'ut' => 'db1', // BB_TOPICS_USER_POSTED -# db3 - 'cap' => 'db1', // BB_CAPTCHA - 'pm' => 'db1', // BB_PRIVMSGS, BB_PRIVMSGS_TEXT - 'pt' => 'db1', // BB_POSTS_TEXT -); - -// Cache -$bb_cfg['cache']['pconnect'] = true; -$bb_cfg['cache']['db_dir'] = realpath(BB_ROOT) .'/internal_data/cache/filecache/'; -$bb_cfg['cache']['prefix'] = 'tp_'; // Префикс кеша ('tp_') -$bb_cfg['cache']['memcache'] = array( - 'host' => '127.0.0.1', - 'port' => 11211, - 'pconnect' => true, - 'con_required' => true, -); -$bb_cfg['cache']['redis'] = array( - 'host' => '127.0.0.1', - 'port' => 6379, - 'con_required' => true, -); - -// Available cache types: memcache, sqlite, redis, apc, xcache (default of filecache) -# name => array( (string) type, (array) cfg ) -$bb_cfg['cache']['engines'] = array( - 'bb_cache' => array('filecache', array()), - 'bb_config' => array('filecache', array()), - 'tr_cache' => array('filecache', array()), - 'session_cache' => array('filecache', array()), - 'bb_cap_sid' => array('filecache', array()), - 'bb_login_err' => array('filecache', array()), - 'bb_poll_data' => array('filecache', array()), -); -// Datastore -// Available datastore types: memcache, sqlite, redis, apc, xcache (default filecache) -$bb_cfg['datastore_type'] = 'filecache'; - -// Server -$bb_cfg['server_name'] = $domain_name; // The domain name from which this board runs -$bb_cfg['server_port'] = (!empty($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : 80; // The port your server is running on -$bb_cfg['script_path'] = '/'; // The path where FORUM is located relative to the domain name - -// Cloudflare -if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) -{ - $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP']; +if (!defined('BB_ROOT')) { + die(basename(__FILE__)); } +// Server settings +$reserved_name = env('TP_HOST', 'example.com'); +$reserved_port = env('TP_PORT', 80); + +$bb_cfg = []; + +// Version info +$bb_cfg['tp_version'] = 'v2.8.3'; +$bb_cfg['tp_release_date'] = '03-07-2025'; +$bb_cfg['tp_release_codename'] = 'Cattle'; + +// Increase version number after changing JS or CSS +$bb_cfg['js_ver'] = $bb_cfg['css_ver'] = 1; + +// Database +// Settings for database ['db']['srv_name'] => (array) srv_cfg; +$bb_cfg['db'] = [ + 'db' => [ + // Don't change the settings here!!! Go to .env file + env('DB_HOST', 'localhost'), + env('DB_PORT', 3306), + env('DB_DATABASE', 'torrentpier'), + env('DB_USERNAME', 'root'), + env('DB_PASSWORD'), + 'utf8mb4', + false + ], +]; + +$bb_cfg['db_alias'] = [ + 'log' => 'db', // BB_LOG + 'search' => 'db', // BB_TOPIC_SEARCH + 'sres' => 'db', // BB_BT_USER_SETTINGS, BB_SEARCH_RESULTS + 'u_ses' => 'db', // BB_USER_SES, BB_USER_LASTVISIT + 'dls' => 'db', // BB_BT_DLS_* + 'ip' => 'db', // BB_POSTS_IP + 'ut' => 'db', // BB_TOPICS_USER_POSTED + 'pm' => 'db', // BB_PRIVMSGS, BB_PRIVMSGS_TEXT + 'pt' => 'db', // BB_POSTS_TEXT +]; + +// Cache +$bb_cfg['cache'] = [ + 'db_dir' => realpath(BB_ROOT) . '/internal_data/cache/filecache/', + 'prefix' => 'tp_', + 'memcached' => [ + 'host' => '127.0.0.1', + 'port' => 11211, + ], + // Available cache types: file, sqlite, memory, memcached (file by default) + 'engines' => [ + 'bb_cache' => ['file'], + 'bb_config' => ['file'], + 'tr_cache' => ['file'], + 'session_cache' => ['file'], + 'bb_cap_sid' => ['file'], + 'bb_login_err' => ['file'], + 'bb_poll_data' => ['file'], + 'bb_ip2countries' => ['file'], + ], +]; + +// Datastore +// Available datastore types: file, sqlite, memory, memcache (file by default) +$bb_cfg['datastore_type'] = 'file'; + +// Server +$bb_cfg['server_name'] = $domain_name = !empty($_SERVER['SERVER_NAME']) ? idn_to_utf8($_SERVER['SERVER_NAME']) : $reserved_name; +$bb_cfg['server_port'] = !empty($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : $reserved_port; +$bb_cfg['script_path'] = '/'; // The path where FORUM is located relative to the domain name + // GZip -$bb_cfg['gzip_compress'] = true; // compress output +$bb_cfg['gzip_compress'] = false; // Compress output // Tracker -$bb_cfg['announce_interval'] = 2400; // Announce interval (default: 1800) -$bb_cfg['passkey_key'] = 'uk'; // Passkey key name in GET request -$bb_cfg['ignore_reported_ip'] = false; // Ignore IP reported by client -$bb_cfg['verify_reported_ip'] = true; // Verify IP reported by client against $_SERVER['HTTP_X_FORWARDED_FOR'] -$bb_cfg['allow_internal_ip'] = false; // Allow internal IP (10.xx.. etc.) +$bb_cfg['announce_interval'] = 1800; // Announce interval (default: 1800) +$bb_cfg['scrape_interval'] = 300; // Scrape interval (default: 300) +$bb_cfg['max_scrapes'] = 150; // Allowed number of info-hashes for simultaneous scraping, only not cached info-hashes will abide by these limits (default: 150) +$bb_cfg['passkey_key'] = 'uk'; // Passkey key name in GET request +$bb_cfg['ignore_reported_ip'] = false; // Ignore IP reported by client +$bb_cfg['verify_reported_ip'] = true; // Verify IP reported by client against $_SERVER['HTTP_X_FORWARDED_FOR'] +$bb_cfg['allow_internal_ip'] = false; // Allow internal IP (10.xx.. etc.) +$bb_cfg['disallowed_ports'] = [ + // https://github.com/HDInnovations/UNIT3D-Community-Edition/blob/c64275f0b5dcb3c4c845d5204871adfe24f359d6/app/Http/Controllers/AnnounceController.php#L53 + // Hyper Text Transfer Protocol (HTTP) - port used for web traffic + 8080, + 8081, + // Kazaa - peer-to-peer file sharing, some known vulnerabilities, and at least one worm (Benjamin) targeting it. + 1214, + // IANA registered for Microsoft WBT Server, used for Windows Remote Desktop and Remote Assistance connections + 3389, + // eDonkey 2000 P2P file sharing service. http://www.edonkey2000.com/ + 4662, + // Gnutella (FrostWire, Limewire, Shareaza, etc.), BearShare file sharing app + 6346, + 6347, + // Port used by p2p software, such as WinMX, Napster. + 6699, +]; +$bb_cfg['client_ban'] = [ + 'enabled' => false, + 'only_allow_mode' => false, + // Clients to be blocked / allowed (in "only allow mode"), for example, peer id '-UT' will block all uTorrent clients, '-UT2' will block builds starting with 2 (default: false) + // The second argument is being shown in the torrent client as a failure message + // Handy client list: https://github.com/transmission/transmission/blob/f85c3b6f8db95d5363f6ec38eee603f146c6adb6/libtransmission/clients.cc#L504 + 'clients' => [ + // 'client_id' => 'Ban reason (can be empty)' + '-UT' => 'uTorrent — NOT ad-free and open-source', + '-MG' => 'Mostly leeching client', + '-ZO' => '', + ] +]; -// Ocelot -$bb_cfg['ocelot'] = array( - 'enabled' => false, - 'host' => $domain_name, - 'port' => 34000, - 'url' => "http://$domain_name:34000/", // with '/' - 'secret' => 'some_10_chars', // 10 chars - 'stats' => 'some_10_chars', // 10 chars -); +// TorrentPier updater settings +$bb_cfg['tp_updater_settings'] = [ + 'enabled' => true, + 'allow_pre_releases' => false +]; + +// TorrServer integration +$bb_cfg['torr_server'] = [ + // Read more: https://github.com/YouROK/TorrServer + 'enabled' => false, + 'url' => "http://$domain_name:8090", + 'timeout' => 5, + 'disable_for_guest' => true +]; + +// FreeIPAPI settings +$bb_cfg['ip2country_settings'] = [ + // Documentation: https://docs.freeipapi.com/ + 'enabled' => true, + 'endpoint' => 'https://freeipapi.com/api/json/', + 'api_token' => '', // not required for basic usage +]; // FAQ url help link -$bb_cfg['how_to_download_url_help'] = 'viewtopic.php?t=1'; // Как скачивать? -$bb_cfg['what_is_torrent_url_help'] = 'viewtopic.php?t=2'; // Что такое торрент? -$bb_cfg['ratio_url_help'] = 'viewtopic.php?t=3'; // Рейтинг и ограничения -$bb_cfg['search_help_url'] = 'viewtopic.php?t=4'; // Помощь по поиску +$bb_cfg['how_to_download_url_help'] = 'viewtopic.php?t=1'; // How to download? +$bb_cfg['what_is_torrent_url_help'] = 'viewtopic.php?t=2'; // What is a torrent? +$bb_cfg['ratio_url_help'] = 'viewtopic.php?t=3'; // Rating and limits +$bb_cfg['search_help_url'] = 'viewtopic.php?t=4'; // Help doc about performing basic searches // Torrents -$bb_cfg['bt_min_ratio_allow_dl_tor'] = 0.3; // 0 - disable -$bb_cfg['bt_min_ratio_warning'] = 0.6; // 0 - disable - -$tr_cfg = array( - 'autoclean' => true, - 'off' => false, - 'off_reason' => 'temporarily disabled', - 'numwant' => 50, - 'update_dlstat' => true, - 'expire_factor' => 2.5, - 'compact_mode' => true, - 'upd_user_up_down_stat' => true, - 'browser_redirect_url' => '', - 'scrape' => true, - 'limit_active_tor' => true, - 'limit_seed_count' => 0, - 'limit_leech_count' => 8, - 'leech_expire_factor' => 60, - 'limit_concurrent_ips' => false, - 'limit_seed_ips' => 0, - 'limit_leech_ips' => 0, - 'tor_topic_up' => true, - 'gold_silver_enabled' => true, - 'retracker' => true, - 'retracker_host' => 'http://retracker.local/announce', -); +$bb_cfg['bt_min_ratio_allow_dl_tor'] = 0.3; // 0 - disable +$bb_cfg['bt_min_ratio_warning'] = 0.6; // 0 - disable $bb_cfg['show_dl_status_in_search'] = true; -$bb_cfg['show_dl_status_in_forum'] = true; - +$bb_cfg['show_dl_status_in_forum'] = true; $bb_cfg['show_tor_info_in_dl_list'] = true; $bb_cfg['allow_dl_list_names_mode'] = true; -$bb_cfg['torrent_name_style'] = true; // use torrent name style [yoursite.com].txxx.torrent -$bb_cfg['tor_help_links'] = 'terms.php'; +// Null ratio +$bb_cfg['ratio_null_enabled'] = true; +$bb_cfg['ratio_to_null'] = $bb_cfg['bt_min_ratio_allow_dl_tor']; // 0.3 -// Сколько дней сохранять торрент зарегистрированным / Days to keep torrent registered, if: -$bb_cfg['seeder_last_seen_days_keep'] = 0; // сколько дней назад был сид последний раз -$bb_cfg['seeder_never_seen_days_keep'] = 0; // сколько дней имеется статус "Сида не было никогда" +// Days to keep torrent registered +$bb_cfg['seeder_last_seen_days_keep'] = 0; // Max time storing for the last seen peer status +$bb_cfg['seeder_never_seen_days_keep'] = 0; // Max time for storing status - Never seen -// Ratio limits -define('TR_RATING_LIMITS', true); // ON/OFF -define('MIN_DL_FOR_RATIO', 10737418240); // 10 GB in bytes, 0 - disable +// DL-Status (days to keep user's dlstatus records) +$bb_cfg['dl_will_days_keep'] = 360; +$bb_cfg['dl_down_days_keep'] = 180; +$bb_cfg['dl_complete_days_keep'] = 180; +$bb_cfg['dl_cancel_days_keep'] = 30; +// Tor-Stats +$bb_cfg['torstat_days_keep'] = 60; // Days to keep user's per-torrent stats + +// Tor-Help +$bb_cfg['torhelp_enabled'] = false; // Find dead torrents (without seeder) that user might help seeding + +// URL's +$bb_cfg['ajax_url'] = 'ajax.php'; # "http://{$_SERVER['SERVER_NAME']}/ajax.php" +$bb_cfg['dl_url'] = 'dl.php?id='; # "http://{$domain_name}/dl.php?id=" +$bb_cfg['login_url'] = 'login.php'; # "http://{$domain_name}/login.php" +$bb_cfg['posting_url'] = 'posting.php'; # "http://{$domain_name}/posting.php" +$bb_cfg['pm_url'] = 'privmsg.php'; # "http://{$domain_name}/privmsg.php" + +// Language +$bb_cfg['auto_language_detection'] = true; // Use browser language (auto-detect) as default language for guests +$bb_cfg['lang'] = [ + // Languages available for selecting + 'af' => [ + 'name' => 'Afrikaans', + 'locale' => 'af_ZA.UTF-8', + ], + 'sq' => [ + 'name' => 'Albanian', + 'locale' => 'sq_AL.UTF-8', + ], + 'ar' => [ + 'name' => 'Arabic', + 'locale' => 'ar_SA.UTF-8', + 'rtl' => true, + ], + 'hy' => [ + 'name' => 'Armenian', + 'locale' => 'hy_AM.UTF-8', + ], + 'az' => [ + 'name' => 'Azerbaijani', + 'locale' => 'az_AZ.UTF-8', + ], + 'be' => [ + 'name' => 'Belarusian', + 'locale' => 'be_BY.UTF-8', + ], + 'bs' => [ + 'name' => 'Bosnian', + 'locale' => 'bs_BA.UTF-8', + ], + 'bg' => [ + 'name' => 'Bulgarian', + 'locale' => 'bg_BG.UTF-8', + ], + 'ca' => [ + 'name' => 'Catalan', + 'locale' => 'ca_ES.UTF-8', + ], + 'zh' => [ + 'name' => 'Chinese Simplified', + 'locale' => 'zh_CN.UTF-8', + ], + 'hr' => [ + 'name' => 'Croatian', + 'locale' => 'hr_HR.UTF-8', + ], + 'cs' => [ + 'name' => 'Czech', + 'locale' => 'cs_CZ.UTF-8', + ], + 'da' => [ + 'name' => 'Danish', + 'locale' => 'da_DK.UTF-8', + ], + 'nl' => [ + 'name' => 'Dutch', + 'locale' => 'nl_NL.UTF-8', + ], + 'en' => [ + 'name' => 'English', + 'locale' => 'en_US.UTF-8', + ], + 'et' => [ + 'name' => 'Estonian', + 'locale' => 'et_EE.UTF-8', + ], + 'fi' => [ + 'name' => 'Finnish', + 'locale' => 'fi_FI.UTF-8', + ], + 'fr' => [ + 'name' => 'French', + 'locale' => 'fr_FR.UTF-8', + ], + 'ka' => [ + 'name' => 'Georgian', + 'locale' => 'ka_GE.UTF-8', + ], + 'de' => [ + 'name' => 'German', + 'locale' => 'de_DE.UTF-8', + ], + 'el' => [ + 'name' => 'Greek', + 'locale' => 'el_GR.UTF-8', + ], + 'he' => [ + 'name' => 'Hebrew', + 'locale' => 'he_IL.UTF-8', + 'rtl' => true, + ], + 'hi' => [ + 'name' => 'Hindi', + 'locale' => 'hi_IN.UTF-8', + ], + 'hu' => [ + 'name' => 'Hungarian', + 'locale' => 'hu_HU.UTF-8', + ], + 'id' => [ + 'name' => 'Indonesian', + 'locale' => 'id_ID.UTF-8', + ], + 'it' => [ + 'name' => 'Italian', + 'locale' => 'it_IT.UTF-8', + ], + 'ja' => [ + 'name' => 'Japanese', + 'locale' => 'ja_JP.UTF-8', + ], + 'kk' => [ + 'name' => 'Kazakh', + 'locale' => 'kk_KZ.UTF-8', + ], + 'ko' => [ + 'name' => 'Korean', + 'locale' => 'ko_KR.UTF-8', + ], + 'lv' => [ + 'name' => 'Latvian', + 'locale' => 'lv_LV.UTF-8', + ], + 'lt' => [ + 'name' => 'Lithuanian', + 'locale' => 'lt_LT.UTF-8', + ], + 'no' => [ + 'name' => 'Norwegian', + 'locale' => 'nn_NO.UTF-8', + ], + 'pl' => [ + 'name' => 'Polish', + 'locale' => 'pl_PL.UTF-8', + ], + 'pt' => [ + 'name' => 'Portuguese', + 'locale' => 'pt_PT.UTF-8', + ], + 'ro' => [ + 'name' => 'Romanian', + 'locale' => 'ro_RO.UTF-8', + ], + 'ru' => [ + 'name' => 'Russian', + 'locale' => 'ru_RU.UTF-8', + ], + 'sr' => [ + 'name' => 'Serbian', + 'locale' => 'sr_CS.UTF-8', + ], + 'sk' => [ + 'name' => 'Slovak', + 'locale' => 'sk_SK.UTF-8', + ], + 'sl' => [ + 'name' => 'Slovenian', + 'locale' => 'sl_SI.UTF-8', + ], + 'es' => [ + 'name' => 'Spanish', + 'locale' => 'es_ES.UTF-8', + ], + 'sv' => [ + 'name' => 'Swedish', + 'locale' => 'sv_SE.UTF-8', + ], + 'tg' => [ + 'name' => 'Tajik', + 'locale' => 'tg_TJ.UTF-8', + ], + 'th' => [ + 'name' => 'Thai', + 'locale' => 'th_TH.UTF-8', + ], + 'tr' => [ + 'name' => 'Turkish', + 'locale' => 'tr_TR.UTF-8', + ], + 'uk' => [ + 'name' => 'Ukrainian', + 'locale' => 'uk_UA.UTF-8', + ], + 'uz' => [ + 'name' => 'Uzbek', + 'locale' => 'uz_UZ.UTF-8', + ], + 'vi' => [ + 'name' => 'Vietnamese', + 'locale' => 'vi_VN.UTF-8', + ], +]; + +// Templates +$bb_cfg['templates'] = [ + // Available templates for selecting + 'default' => 'Default', +]; + +$bb_cfg['tpl_name'] = 'default'; // Default template +$bb_cfg['stylesheet'] = 'main.css'; + +$bb_cfg['show_sidebar1_on_every_page'] = false; // Show left sidebar in every page +$bb_cfg['show_sidebar2_on_every_page'] = false; // Show right sidebar in every page + +// Cookie +$bb_cfg['cookie_domain'] = in_array($domain_name, [$_SERVER['SERVER_ADDR'], 'localhost'], true) ? '' : ".$domain_name"; +$bb_cfg['cookie_secure'] = \TorrentPier\Helpers\IsHelper::isHTTPS(); +$bb_cfg['cookie_prefix'] = 'bb_'; // 'bb_' +$bb_cfg['cookie_same_site'] = 'Lax'; // Lax, None, Strict | https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite + +// Sessions +$bb_cfg['session_update_intrv'] = 180; // sec +$bb_cfg['user_session_duration'] = 1800; // sec +$bb_cfg['admin_session_duration'] = 6 * 3600; // sec +$bb_cfg['user_session_gc_ttl'] = 1800; // number of seconds that a staled session entry may remain in sessions table +$bb_cfg['session_cache_gc_ttl'] = 1200; // sec +$bb_cfg['max_last_visit_days'] = 14; // days +$bb_cfg['last_visit_update_intrv'] = 3600; // sec + +// Registration +$bb_cfg['invalid_logins'] = 5; // Max incorrect password submits before showing captcha +$bb_cfg['new_user_reg_disabled'] = false; // Disable registration of new users +$bb_cfg['unique_ip'] = false; // Disallow registration from multiple IP addresses +$bb_cfg['new_user_reg_restricted'] = false; // Disallow registration in below hours +$bb_cfg['new_user_reg_interval'] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]; // Available hours +$bb_cfg['reg_email_activation'] = true; // Demand to activate profile by email confirmation +$bb_cfg['invites_system'] = [ + 'enabled' => false, + 'codes' => [ + // Syntax: 'invite_code' => 'validity_period' + // The 'validity_period' value is based on strtotime() function: https://www.php.net/manual/en/function.strtotime.php + // You can also create a permanent invite, set 'permanent' value for 'validity_period' + // Invite link example: site_url/profile.php?mode=register&invite=new_year2023 + 'new_year2023' => '2022-12-31 00:00:01', + '340c4bb6ea2d284c13e085b60b990a8a' => '12 April 1961', + 'tp_birthday' => '2005-04-04', + 'endless' => 'permanent' + ] +]; +$bb_cfg['password_symbols'] = [ + // What symbols should be required in the password + 'nums' => true, + 'spec_symbols' => false, + 'letters' => [ + 'uppercase' => false, + 'lowercase' => true + ] +]; +$bb_cfg['password_hash_options'] = [ + // https://www.php.net/manual/ru/password.constants.php + 'algo' => PASSWORD_BCRYPT, + 'options' => ['cost' => 12] +]; + +// Email +$bb_cfg['emailer'] = [ + 'enabled' => true, + 'sendmail_command' => '/usr/sbin/sendmail -bs', + 'smtp' => [ + 'enabled' => false, // send email via external SMTP server + 'host' => 'localhost', // SMTP server host + 'port' => 25, // SMTP server port + 'username' => '', // SMTP username (if server requires it) + 'password' => '', // SMTP password (if server requires it) + 'ssl_type' => '', // SMTP ssl type (ssl or tls) + ], +]; +$bb_cfg['extended_email_validation'] = true; // DNS & RFC checks for entered email addresses + +$bb_cfg['board_email'] = "noreply@$domain_name"; // admin email address +$bb_cfg['board_email_form'] = false; // can users send email to each other via board +$bb_cfg['board_email_sig'] = ''; // this text will be attached to all emails the board sends +$bb_cfg['board_email_sitename'] = $domain_name; // sitename used in all emails header + +$bb_cfg['topic_notify_enabled'] = true; // Send emails to users if subscribed to the topic +$bb_cfg['pm_notify_enabled'] = true; // Send emails to users if there's a new message in inbox +$bb_cfg['group_send_email'] = true; // Send emails to users if user was invited/added to a group +$bb_cfg['email_change_disabled'] = false; // Allow changing emails for users +$bb_cfg['show_email_visibility_settings'] = true; // Allow changing privacy status of profile for users (e.g. last time seen) + +$bb_cfg['bounce_email'] = "bounce@$domain_name"; // bounce email address +$bb_cfg['tech_admin_email'] = "admin@$domain_name"; // email for sending error reports +$bb_cfg['abuse_email'] = "abuse@$domain_name"; // abuse email (e.g. DMCA) +$bb_cfg['adv_email'] = "adv@$domain_name"; // advertisement email + +// Error reporting +$bb_cfg['whoops'] = [ + 'error_message' => 'Sorry, something went wrong. Drink coffee and come back after some time... ☕️', + 'blacklist' => [ + '_COOKIE' => array_keys($_COOKIE), + '_SERVER' => array_keys($_SERVER), + '_ENV' => array_keys($_ENV), + ] +]; + +$bb_cfg['bugsnag'] = [ + 'enabled' => true, + 'api_key' => '33b3ed0102946bab71341f9edc125e21', // Don't change this if you want to help us find bugs +]; + +$bb_cfg['telegram_sender'] = [ + // How to get chat_id? https://api.telegram.org/bot{YOUR_TOKEN}/getUpdates + 'enabled' => false, + 'token' => '', // Bot token + 'chat_id' => '', // Bot chat_id + 'timeout' => 10 // Timeout for responses +]; + +// Special users +$bb_cfg['dbg_users'] = [ + // Syntax: 'user_id' => 'username' + 2 => 'admin', +]; +$bb_cfg['unlimited_users'] = [ + // Syntax: 'user_id' => 'username' + 2 => 'admin', +]; +$bb_cfg['super_admins'] = [ + // Syntax: 'user_id' => 'username' + 2 => 'admin', +]; + +// Subforums +$bb_cfg['sf_on_first_page_only'] = true; // Show subforums only on the first page of the forum + +// Forums +$bb_cfg['allowed_topics_per_page'] = [50, 100, 150, 200, 250, 300]; // Allowed number of topics per page + +// Topics +$bb_cfg['show_post_bbcode_button'] = [ // Show "Code" button in topic to display BBCode of topic + 'enabled' => true, + 'only_for_first_post' => true, +]; +$bb_cfg['show_quick_reply'] = true; // Show quick reply forim +$bb_cfg['show_rank_text'] = false; // Show user rank name in topics +$bb_cfg['show_rank_image'] = true; // Show user rank image in topics +$bb_cfg['show_poster_joined'] = true; // Show user's registration date in topics +$bb_cfg['show_poster_posts'] = true; // Show user's post count in topics +$bb_cfg['show_poster_from'] = true; // Show user's country in topics +$bb_cfg['show_bot_nick'] = true; // Show bot's nickname +$bb_cfg['text_buttons'] = false; // replace EDIT, QUOTE... images with text links +$bb_cfg['post_date_format'] = 'd-M-Y H:i'; // Date format for topics +$bb_cfg['ext_link_new_win'] = true; // open external links in new window + +$bb_cfg['topic_moved_days_keep'] = 7; // remove topic moved links after xx days (or FALSE to disable) +$bb_cfg['allowed_posts_per_page'] = [15, 30, 50, 100]; +$bb_cfg['user_signature_start'] = '

    _________________
    '; +$bb_cfg['user_signature_end'] = '
    '; // It allows user signatures to have closings "<>" + +// Posts +$bb_cfg['use_posts_cache'] = true; +$bb_cfg['posts_cache_days_keep'] = 14; +$bb_cfg['use_ajax_posts'] = true; + +// Search +$bb_cfg['search_engine_type'] = 'mysql'; // none, mysql, sphinx + +$bb_cfg['sphinx_topic_titles_host'] = '127.0.0.1'; +$bb_cfg['sphinx_topic_titles_port'] = 3312; +$bb_cfg['sphinx_config_path'] = '../install/sphinx/sphinx.conf'; + +$bb_cfg['disable_ft_search_in_posts'] = false; // disable searching in post bodies +$bb_cfg['disable_search_for_guest'] = true; // Disable search for guests +$bb_cfg['allow_search_in_bool_mode'] = true; +$bb_cfg['max_search_words_per_post'] = 200; // Max word count for a post +$bb_cfg['search_min_word_len'] = 3; // Min letters to perform a search +$bb_cfg['search_max_word_len'] = 35; // Maximum letters to perform a search +$bb_cfg['limit_max_search_results'] = false; // Limit for number of search results (false - unlimited) + +// Posting +$bb_cfg['prevent_multiposting'] = true; // TODO: replace "reply" with "edit last msg" if user (not admin or mod) is last topic poster +$bb_cfg['max_smilies'] = 25; //Max number of smilies in a post (0 - unlimited) +$bb_cfg['max_symbols_post'] = 5000; // TODO: Max number of symbols in a post (0 - unlimited) + +// PM +$bb_cfg['privmsg_disable'] = false; // Disable private messages +$bb_cfg['max_outgoing_pm_cnt'] = 10; // TODO: Max number of messages in a short period of time to fight spam +$bb_cfg['max_inbox_privmsgs'] = 500; // Max number of messages in pm's inbox folder +$bb_cfg['max_savebox_privmsgs'] = 500; // Max number of messages in pm's saved folder +$bb_cfg['max_sentbox_privmsgs'] = 500; // Max number of messages in pm's sent folder +$bb_cfg['max_smilies_pm'] = 15; // Max number of smilies in a message (0 - unlimited) +$bb_cfg['max_symbols_pm'] = 1500; // TODO: Max number of symbols in a message (0 - unlimited) +$bb_cfg['pm_days_keep'] = 0; // Max time for storing personal messages (0 - unlimited) + +// Actions log +$bb_cfg['log_days_keep'] = 365; // How much time will action history will be stored (0 - unlimited) + +// Users +$bb_cfg['color_nick'] = true; // Colour usernames in accordance with user_rank +$bb_cfg['user_not_activated_days_keep'] = 7; // After how many days to delete users who have not completed registration (that is, the account is not activated) +$bb_cfg['user_not_active_days_keep'] = 180; // After how many days should I delete users who were inactive and did not have a single post? + +// Vote for torrents +$bb_cfg['tor_thank'] = true; +$bb_cfg['tor_thanks_list_guests'] = true; // Show voters to guests +$bb_cfg['tor_thank_limit_per_topic'] = 50; + +// Groups +$bb_cfg['group_members_per_page'] = 50; // How many groups will be displayed in a page + +// Tidy +$bb_cfg['tidy_post'] = extension_loaded('tidy'); + +// Misc +$bb_cfg['mem_on_start'] = memory_get_usage(); +$bb_cfg['translate_dates'] = true; // in displaying time +$bb_cfg['use_word_censor'] = true; +$bb_cfg['show_jumpbox'] = true; // Whether to show jumpbox (on viewtopic.php and viewforum.php) +$bb_cfg['flist_timeout'] = 15; // Max number of seconds to process file lists in forum before throwing an error (default: 15) +$bb_cfg['flist_max_files'] = 0; // Max allowed number of files to process for giving out to indexers (0 - unlimited) +$bb_cfg['last_visit_date_format'] = 'd-M H:i'; +$bb_cfg['last_post_date_format'] = 'd-M-y H:i'; +$bb_cfg['poll_max_days'] = 180; // How many days will the poll be active + +$bb_cfg['allow_change'] = [ + 'language' => true, // Allow user to change language + 'timezone' => true // Allow user to change time zone +]; + +$bb_cfg['trash_forum_id'] = 0; // (int) 7 + +$bb_cfg['first_logon_redirect_url'] = 'index.php'; // Which page should the user be redirected to after registration is completed? +$bb_cfg['terms_and_conditions_url'] = 'terms.php'; // Link to forum rules page +$bb_cfg['tor_help_links'] = ''; + +$bb_cfg['user_agreement_url'] = 'info.php?show=user_agreement'; +$bb_cfg['copyright_holders_url'] = 'info.php?show=copyright_holders'; +$bb_cfg['advert_url'] = 'info.php?show=advert'; + +// Extensions +$bb_cfg['file_id_ext'] = [ + 1 => 'gif', + 2 => 'gz', + 3 => 'jpg', + 4 => 'png', + 5 => 'rar', + 6 => 'tar', + 8 => 'torrent', + 9 => 'zip', + 10 => '7z', + 11 => 'bmp', + 12 => 'webp', + 13 => 'avif' +]; + +// Attachments +$bb_cfg['attach'] = [ + 'upload_path' => DATA_DIR . '/uploads', // Storage path for torrent files + 'max_size' => 5 * 1024 * 1024, // TODO: Max size of a file +]; + +$bb_cfg['tor_forums_allowed_ext'] = ['torrent', 'zip', 'rar']; // TODO: For sections with releases +$bb_cfg['gen_forums_allowed_ext'] = ['zip', 'rar']; // TODO: For regular sections + +// Avatars +$bb_cfg['avatars'] = [ + 'allowed_ext' => ['gif', 'jpg', 'png', 'bmp', 'webp', 'avif'], // Allowed file extensions (after changing, do the same for $bb_cfg['file_id_ext']) + 'bot_avatar' => '/gallery/bot.gif', // The bot's avatar + 'max_size' => 100 * 1024, // Avatar's allowed dimensions + 'max_height' => 100, // Avatar height in px + 'max_width' => 100, // Avatar width in px + 'no_avatar' => '/gallery/noavatar.png', // Default avatar + 'display_path' => '/data/avatars', // Location for avatar files for displaying + 'upload_path' => BB_PATH . '/data/avatars/', // Storage path for avatar files + 'up_allowed' => true, // Allow changing avatars +]; + +// Group avatars +$bb_cfg['group_avatars'] = [ + 'allowed_ext' => ['gif', 'jpg', 'png', 'bmp', 'webp', 'avif'], // Allowed file extensions (add the same for $bb_cfg['file_id_ext']) + 'max_size' => 300 * 1024, // max avatar size in bytes + 'max_height' => 300, // Avatar height in px + 'max_width' => 300, // Avatar weight in px + 'no_avatar' => '/gallery/noavatar.png', // Default avatar + 'display_path' => '/data/avatars', // Location for avatar files for displaying + 'upload_path' => BB_PATH . '/data/avatars/', // Storage path for avatar files + 'up_allowed' => true, // Allow changing avatars +]; + +// Captcha +$bb_cfg['captcha'] = [ + 'disabled' => true, + 'service' => 'googleV3', // Available services: text, googleV2, googleV3, hCaptcha, yandex, cloudflare + 'public_key' => '', + 'secret_key' => '', + 'theme' => 'light', // theming (available: light, dark) (working only if supported by captcha service) +]; + +// Atom feed +$bb_cfg['atom'] = [ + 'path' => INT_DATA_DIR . '/atom', // without ending slash + 'url' => './internal_data/atom', // without ending slash + 'direct_down' => true, // Allow direct downloading of torrents from feeds + 'direct_view' => true, // Allow direct viewing of post texts in feeds +]; + +// Nofollow +$bb_cfg['nofollow'] = [ + 'disabled' => false, + 'allowed_url' => [$domain_name], // 'allowed.site', 'www.allowed.site' +]; + +// Page settings +$bb_cfg['page'] = [ + 'show_torhelp' => [ + #BB_SCRIPT => true + 'index' => true, + 'tracker' => true, + ], + 'show_sidebar1' => [ + #BB_SCRIPT => true + 'index' => true, + ], + 'show_sidebar2' => [ + #BB_SCRIPT => true + 'index' => true, + ] +]; + +// Tracker settings +$bb_cfg['tracker'] = [ + 'autoclean' => true, + 'bt_off' => false, + 'bt_off_reason' => 'Temporarily disabled', + 'numwant' => 50, + 'update_dlstat' => true, + 'expire_factor' => 2.5, + 'compact_mode' => true, + 'scrape' => true, + 'limit_active_tor' => true, + 'limit_seed_count' => 0, + 'limit_leech_count' => 8, + 'leech_expire_factor' => 60, + 'limit_concurrent_ips' => false, + 'limit_seed_ips' => 0, + 'limit_leech_ips' => 0, + 'tor_topic_up' => true, + 'retracker' => true, + 'retracker_host' => 'http://retracker.local/announce', + 'guest_tracker' => true, + 'search_by_tor_status' => true, + 'random_release_button' => true, + 'freeleech' => false, // freeleech mode (If enabled, then disable "gold_silver_enabled") + 'gold_silver_enabled' => true, // golden / silver days mode (If enabled, then disable "freeleech") + 'hybrid_stat_protocol' => 1, // For hybrid torrents there are two identical requests sent by clients, for counting stats we gotta choose one, you can change this to '2' in future, when v1 protocol is outdated + 'disabled_v1_torrents' => false, // disallow registration of v1-only torrents, for future implementations where client will use v2 only and there won't be need for v1, thus relieving tracker + 'disabled_v2_torrents' => false, // disallow registration of v2-only torrents + 'use_old_torrent_name_format' => false, // when enabled, the names of torrent files will have the classic format: [yoursite.com].txxx.torrent +]; + +// Ratio settings // Don't change the order of ratios (from 0 to 1) // rating < 0.4 -- allow only 1 torrent for leeching // rating < 0.5 -- only 2 // rating < 0.6 -- only 3 // rating > 0.6 -- depend on your tracker config limits (in "ACP - Tracker Config - Limits") -$rating_limits = array( - '0.4' => 1, - '0.5' => 2, - '0.6' => 3, -); +$bb_cfg['rating'] = [ + '0.4' => 1, + '0.5' => 2, + '0.6' => 3, +]; -// DL-Status (days to keep user's dlstatus records) -$bb_cfg['dl_will_days_keep'] = 360; -$bb_cfg['dl_down_days_keep'] = 180; -$bb_cfg['dl_complete_days_keep'] = 180; -$bb_cfg['dl_cancel_days_keep'] = 30; +// Icons for statuses of releases +$bb_cfg['tor_icons'] = [ + TOR_NOT_APPROVED => '*', + TOR_CLOSED => 'x', + TOR_APPROVED => '', + TOR_NEED_EDIT => '?', + TOR_NO_DESC => '!', + TOR_DUP => 'D', + TOR_CLOSED_CPHOLD => '©', + TOR_CONSUMED => '', + TOR_DOUBTFUL => '#', + TOR_CHECKING => '%', + TOR_TMP => 'T', + TOR_PREMOD => '', + TOR_REPLENISH => 'R', +]; -// Tor-Stats -$bb_cfg['torstat_days_keep'] = 60; // days to keep user's per-torrent stats +// Disallowed for downloading +$bb_cfg['tor_frozen'] = [ + TOR_CHECKING => true, + TOR_CLOSED => true, + TOR_CLOSED_CPHOLD => true, + TOR_CONSUMED => true, + TOR_DUP => true, + TOR_NO_DESC => true, + TOR_PREMOD => true, +]; -// Tor-Help -$bb_cfg['torhelp_enabled'] = false; // find dead torrents (without seeder) that user might help seeding +// Can the creator download torrent if release status is closed +$bb_cfg['tor_frozen_author_download'] = [ + TOR_CHECKING => true, + TOR_NO_DESC => true, + TOR_PREMOD => true, +]; -$page_cfg['show_torhelp'] = array( -# BB_SCRIPT => true - 'index' => true, - 'tracker' => true, -); +// Disallowed release editing with a certain status +$bb_cfg['tor_cannot_edit'] = [TOR_CHECKING, TOR_CLOSED, TOR_CONSUMED, TOR_DUP]; -// Path (trailing slash '/' at the end: XX_PATH - without, XX_DIR - with) -define('BB_PATH', realpath(BB_ROOT) ); -define('ADMIN_DIR', BB_PATH .'/admin/' ); -define('DATA_DIR', BB_PATH .'/data/' ); -define('INT_DATA_DIR', BB_PATH .'/internal_data/' ); -define('AJAX_HTML_DIR', BB_ROOT .'/internal_data/ajax_html/' ); -define('CACHE_DIR', BB_PATH .'/internal_data/cache/' ); -define('LOG_DIR', BB_PATH .'/internal_data/log/' ); -define('SITEMAP_DIR', BB_PATH .'/internal_data/sitemap/' ); -define('TRIGGERS_DIR', BB_PATH .'/internal_data/triggers/' ); -define('AJAX_DIR', BB_ROOT .'/library/ajax/' ); -define('ATTACH_DIR', BB_PATH .'/library/attach_mod/' ); -define('CFG_DIR', BB_PATH .'/library/config/' ); -define('INC_DIR', BB_PATH .'/library/includes/' ); -define('CLASS_DIR', BB_PATH .'/library/includes/classes/'); -define('CORE_DIR', BB_PATH .'/library/includes/core/' ); -define('UCP_DIR', BB_PATH .'/library/includes/ucp/' ); -define('LANG_ROOT_DIR', BB_PATH .'/library/language/' ); -define('IMAGES_DIR', BB_PATH .'/styles/images/' ); -define('TEMPLATES_DIR', BB_PATH .'/styles/templates/' ); +// Disallowed for creating new releases if status is not fully formatted/unformatted/suspicious +$bb_cfg['tor_cannot_new'] = [TOR_NEED_EDIT, TOR_NO_DESC, TOR_DOUBTFUL]; -// URL's -$bb_cfg['ajax_url'] = 'ajax.php'; # "http://{$_SERVER['SERVER_NAME']}/ajax.php" -$bb_cfg['login_url'] = 'login.php'; # "http://{$domain_name}/login.php" -$bb_cfg['posting_url'] = 'posting.php'; # "http://{$domain_name}/posting.php" -$bb_cfg['pm_url'] = 'privmsg.php'; # "http://{$domain_name}/privmsg.php" +// If the creator is allowed to answer if release has been changed +$bb_cfg['tor_reply'] = [TOR_NEED_EDIT, TOR_NO_DESC, TOR_DOUBTFUL]; -// Language -$bb_cfg['charset'] = 'utf8'; // page charset -$bb_cfg['auto_language'] = true; // select user-preferred language automatically +// If release statistics are closed +$bb_cfg['tor_no_tor_act'] = [ + TOR_CLOSED => true, + TOR_DUP => true, + TOR_CLOSED_CPHOLD => true, + TOR_CONSUMED => true, +]; -if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $bb_cfg['auto_language']) -{ - $user_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); - if (file_exists(LANG_ROOT_DIR . $user_lang .'/')) - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . $user_lang .'/'; - $bb_cfg['default_lang'] = $user_lang; - } - else - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR .'en/'; - $bb_cfg['default_lang'] = 'en'; - } +// PeerID's of torrent clients list +$bb_cfg['tor_clients'] = [ + '-AG' => 'Ares', '-AZ' => 'Vuze', '-A~' => 'Ares', '-BC' => 'BitComet', + '-BE' => 'BitTorrent SDK', '-BI' => 'BiglyBT', '-BL' => 'BitLord', '-BT' => 'BitTorrent', + '-CT' => 'CTorrent', '-DE' => 'Deluge', '-FD' => 'Free Download Manager', 'FD6' => 'Free Download Manager', + '-FG' => 'FlashGet', '-FL' => 'Folx', '-HL' => 'Halite', '-KG' => 'KGet', + '-KT' => 'KTorrent', '-LT' => 'libTorrent', '-Lr' => 'LibreTorrent', + '-TR' => 'Transmission', '-tT' => 'tTorrent', '-UM' => "uTorrent Mac", '-UT' => 'uTorrent', + '-UW' => 'uTorrent Web', '-WW' => 'WebTorrent', '-WD' => 'WebTorrent', '-XL' => 'Xunlei', + '-PI' => 'PicoTorrent', '-qB' => 'qBittorrent', 'M' => 'BitTorrent', 'MG' => 'MediaGet', + '-MG' => 'MediaGet', 'OP' => 'Opera', 'TIX' => 'Tixati', 'aria2-' => 'Aria2', 'A2' => 'Aria2', +]; + +// Vote graphic length defines the maximum length of a vote result graphic, ie. 100% = this length +$bb_cfg['vote_graphic_length'] = 205; +$bb_cfg['privmsg_graphic_length'] = 175; +$bb_cfg['topic_left_column_witdh'] = 150; + +// Images auto-resize +$bb_cfg['post_img_width_decr'] = 52; +$bb_cfg['attach_img_width_decr'] = 130; + +// Get default lang +if (isset($bb_cfg['default_lang']) && is_file(LANG_ROOT_DIR . '/' . $bb_cfg['default_lang'])) { + $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . '/' . $bb_cfg['default_lang'] . '/'; +} else { + $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . '/en/'; } -else -{ - if (isset($bb_cfg['default_lang']) && file_exists(LANG_ROOT_DIR . $bb_cfg['default_lang'] .'/')) - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . $bb_cfg['default_lang'] .'/'; - } - else - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR .'en/'; - } -} - -$bb_cfg['languages'] = array( -// 'folder' => 'Name', - 'ru' => 'Русский', - 'uk' => 'Український', - 'en' => 'English', -); - -// Templates -define('ADMIN_TPL_DIR', TEMPLATES_DIR .'/admin/'); - -$bb_cfg['templates'] = array( -// 'folder' => 'Name', - 'default' => 'Стандартный', -); - -$bb_cfg['tpl_name'] = 'default'; -$bb_cfg['stylesheet'] = 'main.css'; - -$bb_cfg['show_sidebar1_on_every_page'] = false; -$bb_cfg['show_sidebar2_on_every_page'] = false; - -$page_cfg['show_sidebar1'] = array( -# BB_SCRIPT => true - 'index' => true, -); -$page_cfg['show_sidebar2'] = array( -# BB_SCRIPT => true - 'index' => true, -); - -// Cookie -$bb_cfg['cookie_domain'] = in_array($domain_name, array(getenv('SERVER_ADDR'), 'localhost')) ? '' : ".$domain_name"; -$bb_cfg['cookie_secure'] = (!empty($_SERVER['HTTPS']) ? 1 : 0); -$bb_cfg['cookie_prefix'] = 'bb_'; // 'bb_' - -// Sessions -$bb_cfg['session_update_intrv'] = 180; // sec -$bb_cfg['user_session_duration'] = 1800; // sec -$bb_cfg['admin_session_duration'] = 6*3600; // sec -$bb_cfg['user_session_gc_ttl'] = 1800; // number of seconds that a staled session entry may remain in sessions table -$bb_cfg['session_cache_gc_ttl'] = 1200; // sec -$bb_cfg['max_last_visit_days'] = 14; // days -$bb_cfg['last_visit_update_intrv'] = 3600; // sec - -// Registration -$bb_cfg['invalid_logins'] = 5; // Количество неверных попыток ввода пароля, перед выводом проверки капчей -$bb_cfg['new_user_reg_disabled'] = false; // Запретить регистрацию новых учетных записей -$bb_cfg['unique_ip'] = false; // Запретить регистрацию нескольких учетных записей с одного ip -$bb_cfg['new_user_reg_restricted'] = false; // Ограничить регистрацию новых пользователей по времени с 01:00 до 17:00 -$bb_cfg['reg_email_activation'] = false; // Требовать активацию учетной записи по email - -// Email -$bb_cfg['emailer_disabled'] = false; - -$bb_cfg['smtp_delivery'] = false; // send email via a named server instead of the local mail function -$bb_cfg['smtp_ssl'] = false; // use ssl connect -$bb_cfg['smtp_host'] = ''; // SMTP server host -$bb_cfg['smtp_port'] = 25; // SMTP server port -$bb_cfg['smtp_username'] = ''; // enter a username if your SMTP server requires it -$bb_cfg['smtp_password'] = ''; // enter a password if your SMTP server requires it - -$bb_cfg['board_email'] = "noreply@$domain_name"; // admin email address -$bb_cfg['board_email_form'] = false; // can users send email to each other via board -$bb_cfg['board_email_sig'] = ''; // this text will be attached to all emails the board sends -$bb_cfg['board_email_sitename'] = $domain_name; // sitename used in all emails header - -$bb_cfg['topic_notify_enabled'] = true; -$bb_cfg['pm_notify_enabled'] = true; -$bb_cfg['group_send_email'] = true; -$bb_cfg['email_change_disabled'] = false; // disable changing email by user - -$bb_cfg['tech_admin_email'] = "admin@$domain_name"; // email for sending error reports -$bb_cfg['abuse_email'] = "abuse@$domain_name"; -$bb_cfg['adv_email'] = "adv@$domain_name"; - -// Debug -define('DBG_LOG', false); // enable forum debug (off on production) -define('DBG_TRACKER', false); // enable tracker debug (off on production) -define('COOKIE_DBG', 'bb_dbg'); // debug cookie name -define('SQL_DEBUG', true); // enable forum sql & cache debug -define('SQL_LOG_ERRORS', true); // all SQL_xxx options enabled only if SQL_DEBUG == TRUE -define('SQL_CALC_QUERY_TIME', true); // for stats -define('SQL_LOG_SLOW_QUERIES', true); // log sql slow queries -define('SQL_SLOW_QUERY_TIME', 10); // slow query in seconds -define('SQL_PREPEND_SRC_COMM', false); // prepend source file comment to sql query - -// Special users -$bb_cfg['dbg_users'] = array( -# user_id => 'name', - 2 => 'admin', -); - -$bb_cfg['unlimited_users'] = array( -# user_id => 'name', - 2 => 'admin', -); - -$bb_cfg['super_admins'] = array( -# user_id => 'name', - 2 => 'admin', -); - -// Log options -define('LOG_EXT', 'log'); -define('LOG_SEPR', ' | '); -define('LOG_LF', "\n"); -define('LOG_MAX_SIZE', 1048576); // bytes - -// Log request -$log_ip_req = array( -# '127.0.0.1' => 'user1', // CLIENT_IP => 'name' -# '7f000001' => 'user2', // USER_IP => 'name' -); - -$log_passkey = array( -# 'passkey' => 'log_filename', -); - -// Log response -$log_ip_resp = array( -# '127.0.0.1' => 'user1', // CLIENT_IP => 'name' -# '7f000001' => 'user2', // USER_IP => 'name' -); - -// Error reporting -ini_set('error_reporting', E_ALL); -ini_set('display_errors', 0); -ini_set('log_errors', 1); -ini_set('error_log', LOG_DIR .'php_err.log'); - -// Check some variable -// Magic quotes -if (get_magic_quotes_gpc()) die('Set magic_quotes off'); -// JSON -if (!function_exists('json_encode')) die('Json_encode not installed'); - -// Triggers -define('BB_ENABLED', TRIGGERS_DIR .'$on'); -define('BB_DISABLED', TRIGGERS_DIR .'$off'); -define('CRON_ALLOWED', TRIGGERS_DIR .'cron_allowed'); -define('CRON_RUNNING', TRIGGERS_DIR .'cron_running'); - -// Date format -$bb_cfg['date_format'] = 'Y-m-d'; - -// Subforums -$bb_cfg['sf_on_first_page_only'] = true; - -// Forums -$bb_cfg['allowed_topics_per_page'] = array(50, 100, 150, 200, 250, 300); - -// Topics -$bb_cfg['show_quick_reply'] = true; -$bb_cfg['show_rank_text'] = false; -$bb_cfg['show_rank_image'] = true; -$bb_cfg['show_poster_joined'] = true; -$bb_cfg['show_poster_posts'] = true; -$bb_cfg['show_poster_from'] = true; -$bb_cfg['show_bot_nick'] = false; -$bb_cfg['text_buttons'] = false; // replace EDIT, QUOTE... images with text links -$bb_cfg['parse_ed2k_links'] = true; // make ed2k links clickable -$bb_cfg['post_date_format'] = 'd-M-Y H:i'; -$bb_cfg['ext_link_new_win'] = true; // open external links in new window - -$bb_cfg['topic_moved_days_keep'] = 7; // remove topic moved links after xx days (or FALSE to disable) - -$bb_cfg['allowed_posts_per_page'] = array(15, 30, 50, 100); -$bb_cfg['user_signature_start'] = '

    _________________
    '; -$bb_cfg['user_signature_end'] = '
    '; // Это позволит использовать html теги, которые требуют закрытия. Например или - -// Posts -$bb_cfg['use_posts_cache'] = true; // if you switch from ON to OFF, you need to TRUNCATE `bb_posts_html` table -$bb_cfg['posts_cache_days_keep'] = 14; -$bb_cfg['max_post_length'] = 120000; // bytes -$bb_cfg['use_ajax_posts'] = true; - -// Search -$bb_cfg['search_engine_type'] = 'mysql'; // none, mysql, sphinx -$bb_cfg['sphinx_topic_titles_host'] = '127.0.0.1'; -$bb_cfg['sphinx_topic_titles_port'] = 3312; -$bb_cfg['sphinx_config_path'] = realpath("../install/sphinx/sphinx.conf"); -$bb_cfg['disable_ft_search_in_posts'] = false; // disable searching in post bodies -$bb_cfg['disable_search_for_guest'] = true; -$bb_cfg['allow_search_in_bool_mode'] = true; -$bb_cfg['max_search_words_per_post'] = 200; -$bb_cfg['search_min_word_len'] = 3; -$bb_cfg['search_max_word_len'] = 35; -$bb_cfg['limit_max_search_results'] = false; -$bb_cfg['spam_filter_file_path'] = ''; // BB_PATH .'/misc/spam_filter_words.txt'; -$bb_cfg['autocorrect_wkl'] = true; // autocorrect wrong keyboard layout - -// Posting -$bb_cfg['prevent_multiposting'] = true; // replace "reply" with "edit last msg" if user (not admin or mod) is last topic poster -$bb_cfg['max_smilies'] = 10; // Максимальное число смайлов в посте (0 - без ограничения) - -// PM -$bb_cfg['privmsg_disable'] = false; // отключить систему личных сообщений на форуме -$bb_cfg['max_outgoing_pm_cnt'] = 10; // ограничение на кол. одновременных исходящих лс (для замедления рассылки спама) -$bb_cfg['max_inbox_privmsgs'] = 200; // максимальное число сообщений в папке входящие -$bb_cfg['max_savebox_privmsgs'] = 25; // максимальное число сообщений в папке сохраненные -$bb_cfg['max_sentbox_privmsgs'] = 50; // максимальное число сообщений в папке отправленные -$bb_cfg['pm_days_keep'] = 180; // время хранения ЛС - -// Actions log -$bb_cfg['log_days_keep'] = 90; - -// Users -$bb_cfg['color_nick'] = true; // Окраска ников пользователей по user_rank -$bb_cfg['user_not_activated_days_keep'] = 7; // "not activated" == "not finished registration" -$bb_cfg['user_not_active_days_keep'] = 180; // inactive users but only with no posts - -// Groups -$bb_cfg['group_members_per_page'] = 50; - -// Tidy -$bb_cfg['tidy_post'] = (!in_array('tidy', get_loaded_extensions())) ? false : true; - -// Ads -$bb_cfg['show_ads'] = false; -$bb_cfg['show_ads_users'] = array( -# user_id => 'name', - 2 => 'admin', -); - -// block_type => [block_id => block_desc] -$bb_cfg['ad_blocks'] = array( - 'trans' => array( - 100 => 'сквозная сверху', - ), - 'index' => array( - 200 => 'главная, под новостями', - ), -); - -// Misc -define('MEM_USAGE', function_exists('memory_get_usage')); - -$bb_cfg['mem_on_start'] = (MEM_USAGE) ? memory_get_usage() : 0; - -$bb_cfg['translate_dates'] = true; // in displaying time -$bb_cfg['use_word_censor'] = true; - -$bb_cfg['last_visit_date_format'] = 'd-M H:i'; -$bb_cfg['last_post_date_format'] = 'd-M-y H:i'; -$bb_cfg['poll_max_days'] = 180; // сколько дней с момента создания темы опрос будет активным - -$bb_cfg['allow_change'] = array( - 'language' => true, - 'dateformat' => true, -); - -define('GZIP_OUTPUT_ALLOWED', (extension_loaded('zlib') && !ini_get('zlib.output_compression'))); - -$banned_user_agents = array( -// Download Master -# 'download', -# 'master', -// Others -# 'wget', -); - -$bb_cfg['trash_forum_id'] = 0; // (int) 7 - -$bb_cfg['first_logon_redirect_url'] = 'index.php'; -$bb_cfg['terms_and_conditions_url'] = 'terms.php'; - -$bb_cfg['user_agreement_url'] = 'info.php?show=user_agreement'; -$bb_cfg['copyright_holders_url'] = 'info.php?show=copyright_holders'; -$bb_cfg['advert_url'] = 'info.php?show=advert'; - -// Extensions -$bb_cfg['file_id_ext'] = array( - 1 => 'gif', - 2 => 'gz', - 3 => 'jpg', - 4 => 'png', - 5 => 'rar', - 6 => 'tar', - 7 => 'tiff', - 8 => 'torrent', - 9 => 'zip', -); - -// Attachments -$bb_cfg['attach'] = array( - 'upload_path' => DATA_DIR . 'torrent_files', // путь к директории с torrent файлами - 'max_size' => 250*1024, // размер аватары в байтах -); - -$bb_cfg['tor_forums_allowed_ext'] = array('torrent', 'zip', 'rar'); // для разделов с раздачами -$bb_cfg['gen_forums_allowed_ext'] = array('zip', 'rar'); // для обычных разделов - -// Avatars -$bb_cfg['avatars'] = array( - 'allowed_ext' => array('gif','jpg','jpeg','png'), // разрешенные форматы файлов - 'bot_avatar' => 'gallery/bot.gif', // аватара бота - 'max_size' => 100*1024, // размер аватары в байтах - 'max_height' => 100, // высота аватара в px - 'max_width' => 100, // ширина аватара в px - 'no_avatar' => 'gallery/noavatar.png', // дефолтная аватара - 'upload_path' => BB_ROOT . 'data/avatars/', // путь к директории с аватарами - 'up_allowed' => true, // разрешить загрузку аватар -); - -// Group avatars -$bb_cfg['group_avatars'] = array( - 'allowed_ext' => array('gif','jpg','jpeg','png'), // разрешенные форматы файлов - 'max_size' => 300*1024, // размер аватары в байтах - 'max_height' => 300, // высота аватара в px - 'max_width' => 300, // ширина аватара в px - 'no_avatar' => 'gallery/noavatar.png', // дефолтная аватара - 'upload_path' => BB_ROOT . 'data/avatars/', // путь к директории с аватарами - 'up_allowed' => true, // разрешить загрузку аватар -); - -// Captcha -$bb_cfg['captcha'] = array( - 'disabled' => false, - 'secret_key' => 'secret_key', - 'img_path' => INT_DATA_DIR .'captcha/', // with ending slash - 'img_url' => './internal_data/captcha/', // with ending slash -); - -// Atom feed -$bb_cfg['atom'] = array( - 'path' => INT_DATA_DIR .'atom', // without ending slash - 'url' => './internal_data/atom', // without ending slash -); - -// Nofollow -$bb_cfg['nofollow'] = array( - 'disabled' => false, - 'allowed_url' => array($domain_name), // 'allowed.site', 'www.allowed.site' -); - -// Local config -if (file_exists(BB_ROOT. '/library/config.local.php')) -{ - include_once(BB_ROOT. '/library/config.local.php'); -} - -define('BB_CFG_LOADED', true); \ No newline at end of file diff --git a/library/defines.php b/library/defines.php new file mode 100644 index 000000000..5ca49bdf2 --- /dev/null +++ b/library/defines.php @@ -0,0 +1,151 @@ +=8 ) - { - $v = (int)$v; - return pack ( "NN", $v>>32, $v&0xFFFFFFFF ); - } - - // x32, int - if ( is_int($v) ) - return pack ( "NN", $v < 0 ? -1 : 0, $v ); - - // x32, bcmath - if ( function_exists("bcmul") ) - { - if ( bccomp ( $v, 0 ) == -1 ) - $v = bcadd ( "18446744073709551616", $v ); - $h = bcdiv ( $v, "4294967296", 0 ); - $l = bcmod ( $v, "4294967296" ); - return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit - } - - // x32, no-bcmath - $p = max(0, strlen($v) - 13); - $lo = abs((float)substr($v, $p)); - $hi = abs((float)substr($v, 0, $p)); - - $m = $lo + $hi*1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912 - $q = floor($m/4294967296.0); - $l = $m - ($q*4294967296.0); - $h = $hi*2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328 - - if ( $v<0 ) - { - if ( $l==0 ) - $h = 4294967296.0 - $h; - else - { - $h = 4294967295.0 - $h; - $l = 4294967296.0 - $l; - } - } - return pack ( "NN", $h, $l ); -} - -/// pack 64-bit unsigned -function sphPackU64 ( $v ) -{ - assert ( is_numeric($v) ); - - // x64 - if ( PHP_INT_SIZE>=8 ) - { - assert ( $v>=0 ); - - // x64, int - if ( is_int($v) ) - return pack ( "NN", $v>>32, $v&0xFFFFFFFF ); - - // x64, bcmath - if ( function_exists("bcmul") ) - { - $h = bcdiv ( $v, 4294967296, 0 ); - $l = bcmod ( $v, 4294967296 ); - return pack ( "NN", $h, $l ); - } - - // x64, no-bcmath - $p = max ( 0, strlen($v) - 13 ); - $lo = (int)substr ( $v, $p ); - $hi = (int)substr ( $v, 0, $p ); - - $m = $lo + $hi*1316134912; - $l = $m % 4294967296; - $h = $hi*2328 + (int)($m/4294967296); - - return pack ( "NN", $h, $l ); - } - - // x32, int - if ( is_int($v) ) - return pack ( "NN", 0, $v ); - - // x32, bcmath - if ( function_exists("bcmul") ) - { - $h = bcdiv ( $v, "4294967296", 0 ); - $l = bcmod ( $v, "4294967296" ); - return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit - } - - // x32, no-bcmath - $p = max(0, strlen($v) - 13); - $lo = (float)substr($v, $p); - $hi = (float)substr($v, 0, $p); - - $m = $lo + $hi*1316134912.0; - $q = floor($m / 4294967296.0); - $l = $m - ($q * 4294967296.0); - $h = $hi*2328.0 + $q; - - return pack ( "NN", $h, $l ); -} - -// unpack 64-bit unsigned -function sphUnpackU64 ( $v ) -{ - list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) ); - - if ( PHP_INT_SIZE>=8 ) - { - if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again - if ( $lo<0 ) $lo += (1<<32); - - // x64, int - if ( $hi<=2147483647 ) - return ($hi<<32) + $lo; - - // x64, bcmath - if ( function_exists("bcmul") ) - return bcadd ( $lo, bcmul ( $hi, "4294967296" ) ); - - // x64, no-bcmath - $C = 100000; - $h = ((int)($hi / $C) << 32) + (int)($lo / $C); - $l = (($hi % $C) << 32) + ($lo % $C); - if ( $l>$C ) - { - $h += (int)($l / $C); - $l = $l % $C; - } - - if ( $h==0 ) - return $l; - return sprintf ( "%d%05d", $h, $l ); - } - - // x32, int - if ( $hi==0 ) - { - if ( $lo>0 ) - return $lo; - return sprintf ( "%u", $lo ); - } - - $hi = sprintf ( "%u", $hi ); - $lo = sprintf ( "%u", $lo ); - - // x32, bcmath - if ( function_exists("bcmul") ) - return bcadd ( $lo, bcmul ( $hi, "4294967296" ) ); - - // x32, no-bcmath - $hi = (float)$hi; - $lo = (float)$lo; - - $q = floor($hi/10000000.0); - $r = $hi - $q*10000000.0; - $m = $lo + $r*4967296.0; - $mq = floor($m/10000000.0); - $l = $m - $mq*10000000.0; - $h = $q*4294967296.0 + $r*429.0 + $mq; - - $h = sprintf ( "%.0f", $h ); - $l = sprintf ( "%07.0f", $l ); - if ( $h=="0" ) - return sprintf( "%.0f", (float)$l ); - return $h . $l; -} - -// unpack 64-bit signed -function sphUnpackI64 ( $v ) -{ - list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) ); - - // x64 - if ( PHP_INT_SIZE>=8 ) - { - if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again - if ( $lo<0 ) $lo += (1<<32); - - return ($hi<<32) + $lo; - } - - // x32, int - if ( $hi==0 ) - { - if ( $lo>0 ) - return $lo; - return sprintf ( "%u", $lo ); - } - // x32, int - elseif ( $hi==-1 ) - { - if ( $lo<0 ) - return $lo; - return sprintf ( "%.0f", $lo - 4294967296.0 ); - } - - $neg = ""; - $c = 0; - if ( $hi<0 ) - { - $hi = ~$hi; - $lo = ~$lo; - $c = 1; - $neg = "-"; - } - - $hi = sprintf ( "%u", $hi ); - $lo = sprintf ( "%u", $lo ); - - // x32, bcmath - if ( function_exists("bcmul") ) - return $neg . bcadd ( bcadd ( $lo, bcmul ( $hi, "4294967296" ) ), $c ); - - // x32, no-bcmath - $hi = (float)$hi; - $lo = (float)$lo; - - $q = floor($hi/10000000.0); - $r = $hi - $q*10000000.0; - $m = $lo + $r*4967296.0; - $mq = floor($m/10000000.0); - $l = $m - $mq*10000000.0 + $c; - $h = $q*4294967296.0 + $r*429.0 + $mq; - if ( $l==10000000 ) - { - $l = 0; - $h += 1; - } - - $h = sprintf ( "%.0f", $h ); - $l = sprintf ( "%07.0f", $l ); - if ( $h=="0" ) - return $neg . sprintf( "%.0f", (float)$l ); - return $neg . $h . $l; -} - - -function sphFixUint ( $value ) -{ - if ( PHP_INT_SIZE>=8 ) - { - // x64 route, workaround broken unpack() in 5.2.2+ - if ( $value<0 ) $value += (1<<32); - return $value; - } - else - { - // x32 route, workaround php signed/unsigned braindamage - return sprintf ( "%u", $value ); - } -} - - -/// sphinx searchd client class -class SphinxClient extends cache_common -{ - var $_host; ///< searchd host (default is "localhost") - var $_port; ///< searchd port (default is 9312) - var $_offset; ///< how many records to seek from result-set start (default is 0) - var $_limit; ///< how many records to return from result-set starting at offset (default is 20) - var $_mode; ///< query matching mode (default is SPH_MATCH_ALL) - var $_weights; ///< per-field weights (default is 1 for all fields) - var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) - var $_sortby; ///< attribute to sort by (defualt is "") - var $_min_id; ///< min ID to match (default is 0, which means no limit) - var $_max_id; ///< max ID to match (default is 0, which means no limit) - var $_filters; ///< search filters - var $_groupby; ///< group-by attribute name - var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) - var $_groupsort; ///< group-by sorting clause (to sort groups in result set with) - var $_groupdistinct;///< group-by count-distinct attribute - var $_maxmatches; ///< max matches to retrieve - var $_cutoff; ///< cutoff to stop searching at (default is 0) - var $_retrycount; ///< distributed retries count - var $_retrydelay; ///< distributed retries delay - var $_anchor; ///< geographical anchor point - var $_indexweights; ///< per-index weights - var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) - var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) - var $_fieldweights; ///< per-field-name weights - var $_overrides; ///< per-query attribute values overrides - var $_select; ///< select-list (attributes or expressions, with optional aliases) - - var $_error; ///< last error message - var $_warning; ///< last warning message - var $_connerror; ///< connection error vs remote error flag - - var $_reqs; ///< requests array for multi-query - var $_mbenc; ///< stored mbstring encoding - var $_arrayresult; ///< whether $result["matches"] should be a hash or an array - var $_timeout; ///< connect timeout - - var $bb_queries = array(); - var $bb_indexes = array(); - - ///////////////////////////////////////////////////////////////////////////// - // common stuff - ///////////////////////////////////////////////////////////////////////////// - - /// create a new client object and fill defaults - function SphinxClient () - { - $this->dbg_enabled = sql_dbg_enabled(); - - // per-client-object settings - $this->_host = "localhost"; - $this->_port = 9312; - $this->_path = false; - $this->_socket = false; - - // per-query settings - $this->_offset = 0; - $this->_limit = 2000; - $this->_mode = SPH_MATCH_ALL; - $this->_weights = array (); - $this->_sort = SPH_SORT_RELEVANCE; - $this->_sortby = ""; - $this->_min_id = 0; - $this->_max_id = 0; - $this->_filters = array (); - $this->_groupby = ""; - $this->_groupfunc = SPH_GROUPBY_DAY; - $this->_groupsort = "@group desc"; - $this->_groupdistinct= ""; - $this->_maxmatches = 1000; - $this->_cutoff = 0; - $this->_retrycount = 0; - $this->_retrydelay = 0; - $this->_anchor = array (); - $this->_indexweights= array (); - $this->_ranker = SPH_RANK_PROXIMITY_BM25; - $this->_maxquerytime= 0; - $this->_fieldweights= array(); - $this->_overrides = array(); - $this->_select = "*"; - - $this->_error = ""; // per-reply fields (for single-query case) - $this->_warning = ""; - $this->_connerror = false; - - $this->_reqs = array (); // requests storage (for multi-query case) - $this->_mbenc = ""; - $this->_arrayresult = false; - $this->_timeout = 0; - } - - function __destruct() - { - if ( $this->_socket !== false ) - fclose ( $this->_socket ); - } - - /// get last error message (string) - function GetLastError () - { - return $this->_error; - } - - /// get last warning message (string) - function GetLastWarning () - { - return $this->_warning; - } - - /// get last error flag (to tell network connection errors from searchd errors or broken responses) - function IsConnectError() - { - return $this->_connerror; - } - - /// set searchd host name (string) and port (integer) - function SetServer ( $host, $port = 0 ) - { - assert ( is_string($host) ); - if ( $host[0] == '/') - { - $this->_path = 'unix://' . $host; - return; - } - if ( substr ( $host, 0, 7 )=="unix://" ) - { - $this->_path = $host; - return; - } - - assert ( is_int($port) ); - $this->_host = $host; - $this->_port = $port; - $this->_path = ''; - - } - - /// set server connection timeout (0 to remove) - function SetConnectTimeout ( $timeout ) - { - assert ( is_numeric($timeout) ); - $this->_timeout = $timeout; - } - - - function _Send ( $handle, $data, $length ) - { - if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length ) - { - $this->_error = 'connection unexpectedly closed (timed out?)'; - $this->_connerror = true; - return false; - } - return true; - } - - ///////////////////////////////////////////////////////////////////////////// - - /// enter mbstring workaround mode - function _MBPush () - { - $this->_mbenc = ""; - if ( ini_get ( "mbstring.func_overload" ) & 2 ) - { - $this->_mbenc = mb_internal_encoding(); - mb_internal_encoding ( "latin1" ); - } - } - - /// leave mbstring workaround mode - function _MBPop () - { - if ( $this->_mbenc ) - mb_internal_encoding ( $this->_mbenc ); - } - - /// connect to searchd server - function _Connect () - { - $this->cur_query = "connect to: {$this->_host}"; - $this->debug('start'); - - if ( $this->_socket!==false ) - { - // we are in persistent connection mode, so we have a socket - // however, need to check whether it's still alive - if ( !@feof ( $this->_socket ) ) - return $this->_socket; - - // force reopen - $this->_socket = false; - } - - $errno = 0; - $errstr = ""; - $this->_connerror = false; - - if ( $this->_path ) - { - $host = $this->_path; - $port = 0; - } - else - { - $host = $this->_host; - $port = $this->_port; - } - - if ( $this->_timeout<=0 ) - $fp = @fsockopen ( $host, $port, $errno, $errstr ); - else - $fp = @fsockopen ( $host, $port, $errno, $errstr, $this->_timeout ); - - if ( !$fp ) - { - if ( $this->_path ) - $location = $this->_path; - else - $location = "{$this->_host}:{$this->_port}"; - - $errstr = trim ( $errstr ); - $this->_error = "connection to $location failed (errno=$errno, msg=$errstr)"; - $this->_connerror = true; - return false; - } - - // send my version - // this is a subtle part. we must do it before (!) reading back from searchd. - // because otherwise under some conditions (reported on FreeBSD for instance) - // TCP stack could throttle write-write-read pattern because of Nagle. - if ( !$this->_Send ( $fp, pack ( "N", 1 ), 4 ) ) - { - fclose ( $fp ); - $this->_error = "failed to send client protocol version"; - return false; - } - - // check version - list(,$v) = unpack ( "N*", fread ( $fp, 4 ) ); - $v = (int)$v; - if ( $v<1 ) - { - fclose ( $fp ); - $this->_error = "expected searchd protocol version 1+, got version '$v'"; - return false; - } - - $this->debug('stop'); - return $fp; - } - - /// get and check response packet from searchd server - function _GetResponse ( $fp, $client_ver ) - { - $response = ""; - $len = 0; - - $header = fread ( $fp, 8 ); - if ( strlen($header)==8 ) - { - list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) ); - $left = $len; - while ( $left>0 && !feof($fp) ) - { - $chunk = fread ( $fp, $left ); - if ( $chunk ) - { - $response .= $chunk; - $left -= strlen($chunk); - } - } - } - if ( $this->_socket === false ) - fclose ( $fp ); - - // check response - $read = strlen ( $response ); - if ( !$response || $read!=$len ) - { - $this->_error = $len - ? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)" - : "received zero-sized searchd response"; - return false; - } - - // check status - if ( $status==SEARCHD_WARNING ) - { - list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) ); - $this->_warning = substr ( $response, 4, $wlen ); - return substr ( $response, 4+$wlen ); - } - if ( $status==SEARCHD_ERROR ) - { - $this->_error = "searchd error: " . substr ( $response, 4 ); - return false; - } - if ( $status==SEARCHD_RETRY ) - { - $this->_error = "temporary searchd error: " . substr ( $response, 4 ); - return false; - } - if ( $status!=SEARCHD_OK ) - { - $this->_error = "unknown status code '$status'"; - return false; - } - - // check version - if ( $ver<$client_ver ) - { - $this->_warning = sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work", - $ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff ); - } - - return $response; - } - - ///////////////////////////////////////////////////////////////////////////// - // searching - ///////////////////////////////////////////////////////////////////////////// - - /// set offset and count into result set, - /// and optionally set max-matches and cutoff limits - function SetLimits ( $offset, $limit, $max=0, $cutoff=0 ) - { - assert ( is_int($offset) ); - assert ( is_int($limit) ); - assert ( $offset>=0 ); - assert ( $limit>0 ); - assert ( $max>=0 ); - $this->_offset = $offset; - $this->_limit = $limit; - if ( $max>0 ) - $this->_maxmatches = $max; - if ( $cutoff>0 ) - $this->_cutoff = $cutoff; - } - - /// set maximum query time, in milliseconds, per-index - /// integer, 0 means "do not limit" - function SetMaxQueryTime ( $max ) - { - assert ( is_int($max) ); - assert ( $max>=0 ); - $this->_maxquerytime = $max; - } - - /// set matching mode - function SetMatchMode ( $mode ) - { - assert ( $mode==SPH_MATCH_ALL - || $mode==SPH_MATCH_ANY - || $mode==SPH_MATCH_PHRASE - || $mode==SPH_MATCH_BOOLEAN - || $mode==SPH_MATCH_EXTENDED - || $mode==SPH_MATCH_FULLSCAN - || $mode==SPH_MATCH_EXTENDED2 ); - $this->_mode = $mode; - } - - /// set ranking mode - function SetRankingMode ( $ranker ) - { - assert ( $ranker==SPH_RANK_PROXIMITY_BM25 - || $ranker==SPH_RANK_BM25 - || $ranker==SPH_RANK_NONE - || $ranker==SPH_RANK_WORDCOUNT - || $ranker==SPH_RANK_PROXIMITY ); - $this->_ranker = $ranker; - } - - /// set matches sorting mode - function SetSortMode ( $mode, $sortby="" ) - { - assert ( - $mode==SPH_SORT_RELEVANCE || - $mode==SPH_SORT_ATTR_DESC || - $mode==SPH_SORT_ATTR_ASC || - $mode==SPH_SORT_TIME_SEGMENTS || - $mode==SPH_SORT_EXTENDED || - $mode==SPH_SORT_EXPR ); - assert ( is_string($sortby) ); - assert ( $mode==SPH_SORT_RELEVANCE || strlen($sortby)>0 ); - - $this->_sort = $mode; - $this->_sortby = $sortby; - } - - /// bind per-field weights by order - /// DEPRECATED; use SetFieldWeights() instead - function SetWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $weight ) - assert ( is_int($weight) ); - - $this->_weights = $weights; - } - - /// bind per-field weights by name - function SetFieldWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $name=>$weight ) - { - assert ( is_string($name) ); - assert ( is_int($weight) ); - } - $this->_fieldweights = $weights; - } - - /// bind per-index weights by name - function SetIndexWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $index=>$weight ) - { - assert ( is_string($index) ); - assert ( is_int($weight) ); - } - $this->_indexweights = $weights; - } - - /// set IDs range to match - /// only match records if document ID is beetwen $min and $max (inclusive) - function SetIDRange ( $min, $max ) - { - assert ( is_numeric($min) ); - assert ( is_numeric($max) ); - assert ( $min<=$max ); - $this->_min_id = $min; - $this->_max_id = $max; - } - - /// set values set filter - /// only match records where $attribute value is in given set - function SetFilter ( $attribute, $values, $exclude=false ) - { - assert ( is_string($attribute) ); - assert ( is_array($values) ); - assert ( count($values) ); - - if ( is_array($values) && count($values) ) - { - foreach ( $values as $value ) - assert ( is_numeric($value) ); - - $this->_filters[] = array ( "type"=>SPH_FILTER_VALUES, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values ); - } - } - - /// set range filter - /// only match records if $attribute value is beetwen $min and $max (inclusive) - function SetFilterRange ( $attribute, $min, $max, $exclude=false ) - { - assert ( is_string($attribute) ); - assert ( is_numeric($min) ); - assert ( is_numeric($max) ); - assert ( $min<=$max ); - - $this->_filters[] = array ( "type"=>SPH_FILTER_RANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max ); - } - - /// set float range filter - /// only match records if $attribute value is beetwen $min and $max (inclusive) - function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false ) - { - assert ( is_string($attribute) ); - assert ( is_float($min) ); - assert ( is_float($max) ); - assert ( $min<=$max ); - - $this->_filters[] = array ( "type"=>SPH_FILTER_FLOATRANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max ); - } - - /// setup anchor point for geosphere distance calculations - /// required to use @geodist in filters and sorting - /// latitude and longitude must be in radians - function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long ) - { - assert ( is_string($attrlat) ); - assert ( is_string($attrlong) ); - assert ( is_float($lat) ); - assert ( is_float($long) ); - - $this->_anchor = array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long ); - } - - /// set grouping attribute and function - function SetGroupBy ( $attribute, $func, $groupsort="@group desc" ) - { - assert ( is_string($attribute) ); - assert ( is_string($groupsort) ); - assert ( $func==SPH_GROUPBY_DAY - || $func==SPH_GROUPBY_WEEK - || $func==SPH_GROUPBY_MONTH - || $func==SPH_GROUPBY_YEAR - || $func==SPH_GROUPBY_ATTR - || $func==SPH_GROUPBY_ATTRPAIR ); - - $this->_groupby = $attribute; - $this->_groupfunc = $func; - $this->_groupsort = $groupsort; - } - - /// set count-distinct attribute for group-by queries - function SetGroupDistinct ( $attribute ) - { - assert ( is_string($attribute) ); - $this->_groupdistinct = $attribute; - } - - /// set distributed retries count and delay - function SetRetries ( $count, $delay=0 ) - { - assert ( is_int($count) && $count>=0 ); - assert ( is_int($delay) && $delay>=0 ); - $this->_retrycount = $count; - $this->_retrydelay = $delay; - } - - /// set result set format (hash or array; hash by default) - /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs - function SetArrayResult ( $arrayresult ) - { - assert ( is_bool($arrayresult) ); - $this->_arrayresult = $arrayresult; - } - - /// set attribute values override - /// there can be only one override per attribute - /// $values must be a hash that maps document IDs to attribute values - function SetOverride ( $attrname, $attrtype, $values ) - { - assert ( is_string ( $attrname ) ); - assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) ); - assert ( is_array ( $values ) ); - - $this->_overrides[$attrname] = array ( "attr"=>$attrname, "type"=>$attrtype, "values"=>$values ); - } - - /// set select-list (attributes or expressions), SQL-like syntax - function SetSelect ( $select ) - { - assert ( is_string ( $select ) ); - $this->_select = $select; - } - - ////////////////////////////////////////////////////////////////////////////// - - /// clear all filters (for multi-queries) - function ResetFilters () - { - $this->_filters = array(); - $this->_anchor = array(); - } - - /// clear groupby settings (for multi-queries) - function ResetGroupBy () - { - $this->_groupby = ""; - $this->_groupfunc = SPH_GROUPBY_DAY; - $this->_groupsort = "@group desc"; - $this->_groupdistinct= ""; - } - - /// clear all attribute value overrides (for multi-queries) - function ResetOverrides () - { - $this->_overrides = array (); - } - - ////////////////////////////////////////////////////////////////////////////// - - /// connect to searchd server, run given search query through given indexes, - /// and return the search results - function Query ( $query, $index="*", $comment="" ) - { - assert ( empty($this->_reqs) ); - - $this->AddQuery ( $query, $index, $comment ); - $results = $this->RunQueries (); - $this->_reqs = array (); // just in case it failed too early - $this->bb_queries = array(); - $this->bb_indexes = array(); - - if ( !is_array($results) ) - return false; // probably network error; error message should be already filled - - $this->_error = $results[0]["error"]; - $this->_warning = $results[0]["warning"]; - if ( $results[0]["status"]==SEARCHD_ERROR ) - return false; - else - return $results[0]; - } - - /// helper to pack floats in network byte order - function _PackFloat ( $f ) - { - $t1 = pack ( "f", $f ); // machine order - list(,$t2) = unpack ( "L*", $t1 ); // int in machine order - return pack ( "N", $t2 ); - } - - /// add query to multi-query batch - /// returns index into results array from RunQueries() call - function AddQuery ( $query, $index="*", $comment="" ) - { - // mbstring workaround - $this->_MBPush (); - - // build request - $req = pack ( "NNNNN", $this->_offset, $this->_limit, $this->_mode, $this->_ranker, $this->_sort ); // mode and limits - $req .= pack ( "N", strlen($this->_sortby) ) . $this->_sortby; - $req .= pack ( "N", strlen($query) ) . $query; // query itself - $req .= pack ( "N", count($this->_weights) ); // weights - foreach ( $this->_weights as $weight ) - $req .= pack ( "N", (int)$weight ); - $req .= pack ( "N", strlen($index) ) . $index; // indexes - $req .= pack ( "N", 1 ); // id64 range marker - $req .= sphPackU64 ( $this->_min_id ) . sphPackU64 ( $this->_max_id ); // id64 range - - // filters - $req .= pack ( "N", count($this->_filters) ); - foreach ( $this->_filters as $filter ) - { - $req .= pack ( "N", strlen($filter["attr"]) ) . $filter["attr"]; - $req .= pack ( "N", $filter["type"] ); - switch ( $filter["type"] ) - { - case SPH_FILTER_VALUES: - $req .= pack ( "N", count($filter["values"]) ); - foreach ( $filter["values"] as $value ) - $req .= sphPackI64 ( $value ); - break; - - case SPH_FILTER_RANGE: - $req .= sphPackI64 ( $filter["min"] ) . sphPackI64 ( $filter["max"] ); - break; - - case SPH_FILTER_FLOATRANGE: - $req .= $this->_PackFloat ( $filter["min"] ) . $this->_PackFloat ( $filter["max"] ); - break; - - default: - assert ( 0 && "internal error: unhandled filter type" ); - } - $req .= pack ( "N", $filter["exclude"] ); - } - - // group-by clause, max-matches count, group-sort clause, cutoff count - $req .= pack ( "NN", $this->_groupfunc, strlen($this->_groupby) ) . $this->_groupby; - $req .= pack ( "N", $this->_maxmatches ); - $req .= pack ( "N", strlen($this->_groupsort) ) . $this->_groupsort; - $req .= pack ( "NNN", $this->_cutoff, $this->_retrycount, $this->_retrydelay ); - $req .= pack ( "N", strlen($this->_groupdistinct) ) . $this->_groupdistinct; - - // anchor point - if ( empty($this->_anchor) ) - { - $req .= pack ( "N", 0 ); - } else - { - $a =& $this->_anchor; - $req .= pack ( "N", 1 ); - $req .= pack ( "N", strlen($a["attrlat"]) ) . $a["attrlat"]; - $req .= pack ( "N", strlen($a["attrlong"]) ) . $a["attrlong"]; - $req .= $this->_PackFloat ( $a["lat"] ) . $this->_PackFloat ( $a["long"] ); - } - - // per-index weights - $req .= pack ( "N", count($this->_indexweights) ); - foreach ( $this->_indexweights as $idx=>$weight ) - $req .= pack ( "N", strlen($idx) ) . $idx . pack ( "N", $weight ); - - // max query time - $req .= pack ( "N", $this->_maxquerytime ); - - // per-field weights - $req .= pack ( "N", count($this->_fieldweights) ); - foreach ( $this->_fieldweights as $field=>$weight ) - $req .= pack ( "N", strlen($field) ) . $field . pack ( "N", $weight ); - - // comment - $req .= pack ( "N", strlen($comment) ) . $comment; - - // attribute overrides - $req .= pack ( "N", count($this->_overrides) ); - foreach ( $this->_overrides as $key => $entry ) - { - $req .= pack ( "N", strlen($entry["attr"]) ) . $entry["attr"]; - $req .= pack ( "NN", $entry["type"], count($entry["values"]) ); - foreach ( $entry["values"] as $id=>$val ) - { - assert ( is_numeric($id) ); - assert ( is_numeric($val) ); - - $req .= sphPackU64 ( $id ); - switch ( $entry["type"] ) - { - case SPH_ATTR_FLOAT: $req .= $this->_PackFloat ( $val ); break; - case SPH_ATTR_BIGINT: $req .= sphPackI64 ( $val ); break; - default: $req .= pack ( "N", $val ); break; - } - } - } - - // select-list - $req .= pack ( "N", strlen($this->_select) ) . $this->_select; - - // mbstring workaround - $this->_MBPop (); - - // store request to requests array - $this->_reqs[] = $req; - $this->bb_queries[] = $query; - $this->bb_indexes[] = $index; - return count($this->_reqs)-1; - } - - /// connect to searchd, run queries batch, and return an array of result sets - function RunQueries () - { - if ( empty($this->_reqs) ) - { - $this->_error = "no queries defined, issue AddQuery() first"; - return false; - } - - // mbstring workaround - $this->_MBPush (); - - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop (); - return false; - } - - // send query, get response - $nreqs = count($this->_reqs); - $req = join ( "", $this->_reqs ); - $len = 4+strlen($req); - $req = pack ( "nnNN", SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, $nreqs ) . $req; // add header - - $this->cur_query = 'query: `'. join ('` `', $this->bb_queries) .'` idx: `'. join ('` `', $this->bb_indexes) .'`'; - $this->debug('start'); - - if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_SEARCH ) ) ) - { - $this->_MBPop (); - return false; - } - - $this->debug('stop'); - - // query sent ok; we can reset reqs now - $this->_reqs = array (); - $this->bb_queries = array(); - $this->bb_indexes = array(); - - // parse and return response - return $this->_ParseSearchResponse ( $response, $nreqs ); - } - - /// parse and return search query (or queries) response - function _ParseSearchResponse ( $response, $nreqs ) - { - $p = 0; // current position - $max = strlen($response); // max position for checks, to protect against broken responses - - $this->cur_query = "parsing results"; - $this->debug('start'); - - $results = array (); - for ( $ires=0; $ires<$nreqs && $p<$max; $ires++ ) - { - $results[] = array(); - $result =& $results[$ires]; - - $result["error"] = ""; - $result["warning"] = ""; - - // extract status - list(,$status) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $result["status"] = $status; - if ( $status!=SEARCHD_OK ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $message = substr ( $response, $p, $len ); $p += $len; - - if ( $status==SEARCHD_WARNING ) - { - $result["warning"] = $message; - } else - { - $result["error"] = $message; - continue; - } - } - - // read schema - $fields = array (); - $attrs = array (); - - list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - while ( $nfields-->0 && $p<$max ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $fields[] = substr ( $response, $p, $len ); $p += $len; - } - $result["fields"] = $fields; - - list(,$nattrs) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - while ( $nattrs-->0 && $p<$max ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $attr = substr ( $response, $p, $len ); $p += $len; - list(,$type) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $attrs[$attr] = $type; - } - $result["attrs"] = $attrs; - - // read match count - list(,$count) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - list(,$id64) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - - // read matches - $idx = -1; - while ( $count-->0 && $p<$max ) - { - // index into result array - $idx++; - - // parse document id and weight - if ( $id64 ) - { - $doc = sphUnpackU64 ( substr ( $response, $p, 8 ) ); $p += 8; - list(,$weight) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - } - else - { - list ( $doc, $weight ) = array_values ( unpack ( "N*N*", - substr ( $response, $p, 8 ) ) ); - $p += 8; - $doc = sphFixUint($doc); - } - $weight = sprintf ( "%u", $weight ); - - // create match entry - if ( $this->_arrayresult ) - $result["matches"][$idx] = array ( "id"=>$doc, "weight"=>$weight ); - else - $result["matches"][$doc]["weight"] = $weight; - - // parse and create attributes - $attrvals = array (); - foreach ( $attrs as $attr=>$type ) - { - // handle 64bit ints - if ( $type==SPH_ATTR_BIGINT ) - { - $attrvals[$attr] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8; - continue; - } - - // handle floats - if ( $type==SPH_ATTR_FLOAT ) - { - list(,$uval) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - list(,$fval) = unpack ( "f*", pack ( "L", $uval ) ); - $attrvals[$attr] = $fval; - continue; - } - - // handle everything else as unsigned ints - list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - if ( $type & SPH_ATTR_MULTI ) - { - $attrvals[$attr] = array (); - $nvalues = $val; - while ( $nvalues-->0 && $p<$max ) - { - list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $attrvals[$attr][] = sphFixUint($val); - } - } else - { - $attrvals[$attr] = sphFixUint($val); - } - } - - if ( $this->_arrayresult ) - $result["matches"][$idx]["attrs"] = $attrvals; - else - $result["matches"][$doc]["attrs"] = $attrvals; - } - - list ( $total, $total_found, $msecs, $words ) = - array_values ( unpack ( "N*N*N*N*", substr ( $response, $p, 16 ) ) ); - $result["total"] = sprintf ( "%u", $total ); - $result["total_found"] = sprintf ( "%u", $total_found ); - $result["time"] = sprintf ( "%.3f", $msecs/1000 ); - $p += 16; - - while ( $words-->0 && $p<$max ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $word = substr ( $response, $p, $len ); $p += $len; - list ( $docs, $hits ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8; - $result["words"][$word] = array ( - "docs"=>sprintf ( "%u", $docs ), - "hits"=>sprintf ( "%u", $hits ) ); - } - } - - $this->debug('stop'); - - $this->_MBPop (); - return $results; - } - - ///////////////////////////////////////////////////////////////////////////// - // excerpts generation - ///////////////////////////////////////////////////////////////////////////// - - /// connect to searchd server, and generate exceprts (snippets) - /// of given documents for given query. returns false on failure, - /// an array of snippets on success - function BuildExcerpts ( $docs, $index, $words, $opts=array() ) - { - assert ( is_array($docs) ); - assert ( is_string($index) ); - assert ( is_string($words) ); - assert ( is_array($opts) ); - - $this->_MBPush (); - - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop(); - return false; - } - - ///////////////// - // fixup options - ///////////////// - - if ( !isset($opts["before_match"]) ) $opts["before_match"] = ""; - if ( !isset($opts["after_match"]) ) $opts["after_match"] = ""; - if ( !isset($opts["chunk_separator"]) ) $opts["chunk_separator"] = " ... "; - if ( !isset($opts["limit"]) ) $opts["limit"] = 256; - if ( !isset($opts["around"]) ) $opts["around"] = 5; - if ( !isset($opts["exact_phrase"]) ) $opts["exact_phrase"] = false; - if ( !isset($opts["single_passage"]) ) $opts["single_passage"] = false; - if ( !isset($opts["use_boundaries"]) ) $opts["use_boundaries"] = false; - if ( !isset($opts["weight_order"]) ) $opts["weight_order"] = false; - - ///////////////// - // build request - ///////////////// - - // v.1.0 req - $flags = 1; // remove spaces - if ( $opts["exact_phrase"] ) $flags |= 2; - if ( $opts["single_passage"] ) $flags |= 4; - if ( $opts["use_boundaries"] ) $flags |= 8; - if ( $opts["weight_order"] ) $flags |= 16; - $req = pack ( "NN", 0, $flags ); // mode=0, flags=$flags - $req .= pack ( "N", strlen($index) ) . $index; // req index - $req .= pack ( "N", strlen($words) ) . $words; // req words - - // options - $req .= pack ( "N", strlen($opts["before_match"]) ) . $opts["before_match"]; - $req .= pack ( "N", strlen($opts["after_match"]) ) . $opts["after_match"]; - $req .= pack ( "N", strlen($opts["chunk_separator"]) ) . $opts["chunk_separator"]; - $req .= pack ( "N", (int)$opts["limit"] ); - $req .= pack ( "N", (int)$opts["around"] ); - - // documents - $req .= pack ( "N", count($docs) ); - foreach ( $docs as $doc ) - { - assert ( is_string($doc) ); - $req .= pack ( "N", strlen($doc) ) . $doc; - } - - //////////////////////////// - // send query, get response - //////////////////////////// - - $len = strlen($req); - $req = pack ( "nnN", SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, $len ) . $req; // add header - if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_EXCERPT ) ) ) - { - $this->_MBPop (); - return false; - } - - ////////////////// - // parse response - ////////////////// - - $pos = 0; - $res = array (); - $rlen = strlen($response); - for ( $i=0; $i $rlen ) - { - $this->_error = "incomplete reply"; - $this->_MBPop (); - return false; - } - $res[] = $len ? substr ( $response, $pos, $len ) : ""; - $pos += $len; - } - - $this->_MBPop (); - return $res; - } - - - ///////////////////////////////////////////////////////////////////////////// - // keyword generation - ///////////////////////////////////////////////////////////////////////////// - - /// connect to searchd server, and generate keyword list for a given query - /// returns false on failure, - /// an array of words on success - function BuildKeywords ( $query, $index, $hits ) - { - assert ( is_string($query) ); - assert ( is_string($index) ); - assert ( is_bool($hits) ); - - $this->_MBPush (); - - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop(); - return false; - } - - ///////////////// - // build request - ///////////////// - - // v.1.0 req - $req = pack ( "N", strlen($query) ) . $query; // req query - $req .= pack ( "N", strlen($index) ) . $index; // req index - $req .= pack ( "N", (int)$hits ); - - //////////////////////////// - // send query, get response - //////////////////////////// - - $len = strlen($req); - $req = pack ( "nnN", SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, $len ) . $req; // add header - if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_KEYWORDS ) ) ) - { - $this->_MBPop (); - return false; - } - - ////////////////// - // parse response - ////////////////// - - $pos = 0; - $res = array (); - $rlen = strlen($response); - list(,$nwords) = unpack ( "N*", substr ( $response, $pos, 4 ) ); - $pos += 4; - for ( $i=0; $i<$nwords; $i++ ) - { - list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4; - $tokenized = $len ? substr ( $response, $pos, $len ) : ""; - $pos += $len; - - list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4; - $normalized = $len ? substr ( $response, $pos, $len ) : ""; - $pos += $len; - - $res[] = array ( "tokenized"=>$tokenized, "normalized"=>$normalized ); - - if ( $hits ) - { - list($ndocs,$nhits) = array_values ( unpack ( "N*N*", substr ( $response, $pos, 8 ) ) ); - $pos += 8; - $res [$i]["docs"] = $ndocs; - $res [$i]["hits"] = $nhits; - } - - if ( $pos > $rlen ) - { - $this->_error = "incomplete reply"; - $this->_MBPop (); - return false; - } - } - - $this->_MBPop (); - return $res; - } - - function EscapeString ( $string ) - { - $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' ); - $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' ); - - return str_replace ( $from, $to, $string ); - } - - ///////////////////////////////////////////////////////////////////////////// - // attribute updates - ///////////////////////////////////////////////////////////////////////////// - - /// batch update given attributes in given rows in given indexes - /// returns amount of updated documents (0 or more) on success, or -1 on failure - function UpdateAttributes ( $index, $attrs, $values, $mva=false ) - { - // verify everything - assert ( is_string($index) ); - assert ( is_bool($mva) ); - - assert ( is_array($attrs) ); - foreach ( $attrs as $attr ) - assert ( is_string($attr) ); - - assert ( is_array($values) ); - foreach ( $values as $id=>$entry ) - { - assert ( is_numeric($id) ); - assert ( is_array($entry) ); - assert ( count($entry)==count($attrs) ); - foreach ( $entry as $v ) - { - if ( $mva ) - { - assert ( is_array($v) ); - foreach ( $v as $vv ) - assert ( is_int($vv) ); - } else - assert ( is_int($v) ); - } - } - - // build request - $req = pack ( "N", strlen($index) ) . $index; - - $req .= pack ( "N", count($attrs) ); - foreach ( $attrs as $attr ) - { - $req .= pack ( "N", strlen($attr) ) . $attr; - $req .= pack ( "N", $mva ? 1 : 0 ); - } - - $req .= pack ( "N", count($values) ); - foreach ( $values as $id=>$entry ) - { - $req .= sphPackU64 ( $id ); - foreach ( $entry as $v ) - { - $req .= pack ( "N", $mva ? count($v) : $v ); - if ( $mva ) - foreach ( $v as $vv ) - $req .= pack ( "N", $vv ); - } - } - - // connect, send query, get response - if (!( $fp = $this->_Connect() )) - return -1; - - $len = strlen($req); - $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len ) . $req; // add header - if ( !$this->_Send ( $fp, $req, $len+8 ) ) - return -1; - - if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE ) )) - return -1; - - // parse response - list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) ); - return $updated; - } - - ///////////////////////////////////////////////////////////////////////////// - // persistent connections - ///////////////////////////////////////////////////////////////////////////// - - function Open() - { - if ( $this->_socket !== false ) - { - $this->_error = 'already connected'; - return false; - } - if ( !$fp = $this->_Connect() ) - return false; - - // command, command version = 0, body length = 4, body = 1 - $req = pack ( "nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1 ); - if ( !$this->_Send ( $fp, $req, 12 ) ) - return false; - - $this->_socket = $fp; - return true; - } - - function Close() - { - if ( $this->_socket === false ) - { - $this->_error = 'not connected'; - return false; - } - - fclose ( $this->_socket ); - $this->_socket = false; - - return true; - } - - ////////////////////////////////////////////////////////////////////////// - // status - ////////////////////////////////////////////////////////////////////////// - - function Status () - { - $this->_MBPush (); - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop(); - return false; - } - - $req = pack ( "nnNN", SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, 1 ); // len=4, body=1 - if ( !( $this->_Send ( $fp, $req, 12 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_STATUS ) ) ) - { - $this->_MBPop (); - return false; - } - - $res = substr ( $response, 4 ); // just ignore length, error handling, etc - $p = 0; - list ( $rows, $cols ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8; - - $res = array(); - for ( $i=0; $i<$rows; $i++ ) - for ( $j=0; $j<$cols; $j++ ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $res[$i][] = substr ( $response, $p, $len ); $p += $len; - } - - $this->_MBPop (); - return $res; - } -} - -// -// $Id: sphinxapi.php 2055 2009-11-06 23:09:58Z shodan $ -// \ No newline at end of file diff --git a/library/includes/bbcode.php b/library/includes/bbcode.php index fe5c619ca..391814489 100644 --- a/library/includes/bbcode.php +++ b/library/includes/bbcode.php @@ -1,962 +1,449 @@ enqueue(array( - 'smile_replacements', -)); +$datastore->enqueue([ + 'smile_replacements', + 'cat_forums', +]); $page_cfg['include_bbcode_js'] = true; // // BBCode templates // -function get_bbcode_tpl () +function get_bbcode_tpl() { -$bbcode_tpl = array(); + $bbcode_tpl = []; // Quote -$bbcode_tpl['quote_open'] = <<
    HTML; -$bbcode_tpl['quote_username_open'] = <<
    HTML; -$bbcode_tpl['quote_close'] = <<
    HTML; // Code -$bbcode_tpl['code_open'] = <<
    HTML; -$bbcode_tpl['code_close'] = <<
    HTML; // Spoiler -$bbcode_tpl['spoiler_open'] = <<
    HTML; -$bbcode_tpl['spoiler_title_open'] = <<

    \\1

    HTML; -$bbcode_tpl['spoiler_close'] = <<
    HTML; // Image -$bbcode_tpl['img'] = << HTML; -$bbcode_tpl['img_aligned'] = << HTML; // HR -$bbcode_tpl['hr'] = <<- HTML; -array_deep($bbcode_tpl, 'bbcode_tpl_compact'); -return $bbcode_tpl; +// Box + $bbcode_tpl['box_open'] = <<
    +HTML; + + $bbcode_tpl['box_open_color'] = <<
    +HTML; + + $bbcode_tpl['box_open_color_single'] = <<
    +HTML; + + $bbcode_tpl['box_close'] = <<
    +HTML; + + array_deep($bbcode_tpl, 'bbcode_tpl_compact'); + return $bbcode_tpl; } -function bbcode_tpl_compact ($text) +function bbcode_tpl_compact($text) { - $text = str_compact($text); - $text = str_replace('> <', '><', $text); - return $text; + $text = str_compact($text); + $text = str_replace('> <', '><', $text); + return $text; } // prepare a posted message for entry into the database -function prepare_message ($message) +function prepare_message($message) { - $message = bbcode::clean_up($message); - $message = htmlCHR($message, false, ENT_NOQUOTES); - return $message; + $message = \TorrentPier\Legacy\BBCode::clean_up($message); + $message = htmlCHR($message, false, ENT_NOQUOTES); + return $message; } // Fill smiley templates (or just the variables) with smileys // Either in a window or inline function generate_smilies($mode) { - global $bb_cfg, $template, $lang, $user, $datastore; + global $template, $lang, $user, $datastore; - $inline_columns = 4; - $inline_rows = 7; - $window_columns = 8; + $inline_columns = 4; + $inline_rows = 7; + $window_columns = 8; - if ($mode == 'window') - { - $user->session_start(); - } + if ($mode == 'window') { + $user->session_start(); + } - $data = $datastore->get('smile_replacements'); + $data = $datastore->get('smile_replacements'); - if ($sql = $data['smile']) - { - $num_smilies = 0; - $rowset = array(); - foreach ($sql as $row) - { - if (empty($rowset[$row['smile_url']])) - { - $rowset[$row['smile_url']]['code'] = addslashes($row['code']); - $rowset[$row['smile_url']]['emoticon'] = $row['emoticon']; - $num_smilies++; - } - } + if (isset($data['smile']) && $sql = $data['smile']) { + $num_smilies = 0; + $rowset = []; + foreach ($sql as $row) { + if (empty($rowset[$row['smile_url']])) { + $rowset[$row['smile_url']]['code'] = addslashes($row['code']); + $rowset[$row['smile_url']]['emoticon'] = $row['emoticon']; + $num_smilies++; + } + } - if ($num_smilies) - { - $smilies_count = ($mode == 'inline') ? min(19, $num_smilies) : $num_smilies; - $smilies_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1; + if ($num_smilies) { + $smilies_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1; - $s_colspan = 0; - $row = 0; - $col = 0; + $s_colspan = 0; + $row = 0; + $col = 0; - while (list($smile_url, $data) = @each($rowset)) - { - if (!$col) - { - $template->assign_block_vars('smilies_row', array()); - } + foreach ($rowset as $smile_url => $data) { + if (!$col) { + $template->assign_block_vars('smilies_row', []); + } - $template->assign_block_vars('smilies_row.smilies_col', array( - 'SMILEY_CODE' => $data['code'], - 'SMILEY_IMG' => $bb_cfg['smilies_path'] . '/' . $smile_url, - 'SMILEY_DESC' => $data['emoticon'], - )); + $template->assign_block_vars('smilies_row.smilies_col', [ + 'SMILEY_CODE' => $data['code'], + 'SMILEY_IMG' => config()->get('smilies_path') . '/' . $smile_url, + 'SMILEY_DESC' => $data['emoticon'], + ]); - $s_colspan = max($s_colspan, $col + 1); + $s_colspan = max($s_colspan, $col + 1); - if ($col == $smilies_split_row) - { - if ($mode == 'inline' && $row == $inline_rows - 1) - { - break; - } - $col = 0; - $row++; - } - else - { - $col++; - } - } + if ($col == $smilies_split_row) { + if ($mode == 'inline' && $row == $inline_rows - 1) { + break; + } + $col = 0; + $row++; + } else { + $col++; + } + } - if ($mode == 'inline' && $num_smilies > $inline_rows * $inline_columns) - { - $template->assign_block_vars('switch_smilies_extra', array()); + if ($mode == 'inline' && $num_smilies > $inline_rows * $inline_columns) { + $template->assign_block_vars('switch_smilies_extra', []); - $template->assign_vars(array( - 'U_MORE_SMILIES' => POSTING_URL ."?mode=smilies", - )); - } + $template->assign_vars([ + 'U_MORE_SMILIES' => POSTING_URL . "?mode=smilies", + ]); + } - $template->assign_vars(array( - 'PAGE_TITLE' => $lang['EMOTICONS'], - 'S_SMILIES_COLSPAN' => $s_colspan, - )); - } - } + $template->assign_vars([ + 'PAGE_TITLE' => $lang['EMOTICONS'], + 'S_SMILIES_COLSPAN' => $s_colspan, + ]); + } + } - if ($mode == 'window') - { - print_page('posting_smilies.tpl', 'simple'); - } + if ($mode == 'window') { + print_page('posting_smilies.tpl', 'simple'); + } } // some functions from vB // ############################################################################# /** -* Strips away [quote] tags and their contents from the specified string -* -* @param string Text to be stripped of quote tags -* -* @return string -*/ -function strip_quotes ($text) + * Strips away [quote] tags and their contents from the specified string + * + * @param string Text to be stripped of quote tags + * + * @return string + */ +function strip_quotes($text) { - $lowertext = strtolower($text); + $lowertext = strtolower($text); - // find all [quote tags - $start_pos = array(); - $curpos = 0; - do - { - $pos = strpos($lowertext, '[quote', $curpos); - if ($pos !== false) - { - $start_pos["$pos"] = 'start'; - $curpos = $pos + 6; - } - } - while ($pos !== false); + // find all [quote tags + $start_pos = []; + $curpos = 0; + do { + $pos = strpos($lowertext, '[quote', $curpos); + if ($pos !== false) { + $start_pos[(string)$pos] = 'start'; + $curpos = $pos + 6; + } + } while ($pos !== false); - if (sizeof($start_pos) == 0) - { - return $text; - } + if (count($start_pos) == 0) { + return $text; + } - // find all [/quote] tags - $end_pos = array(); - $curpos = 0; - do - { - $pos = strpos($lowertext, '[/quote', $curpos); - if ($pos !== false) - { - $end_pos["$pos"] = 'end'; - $curpos = $pos + 8; - } - } - while ($pos !== false); + // find all [/quote] tags + $end_pos = []; + $curpos = 0; + do { + $pos = strpos($lowertext, '[/quote', $curpos); + if ($pos !== false) { + $end_pos[(string)$pos] = 'end'; + $curpos = $pos + 8; + } + } while ($pos !== false); - if (sizeof($end_pos) == 0) - { - return $text; - } + if (count($end_pos) == 0) { + return $text; + } - // merge them together and sort based on position in string - $pos_list = $start_pos + $end_pos; - ksort($pos_list); + // merge them together and sort based on position in string + $pos_list = $start_pos + $end_pos; + ksort($pos_list); - do - { - // build a stack that represents when a quote tag is opened - // and add non-quote text to the new string - $stack = array(); - $newtext = '[...] '; - $substr_pos = 0; - foreach ($pos_list AS $pos => $type) - { - $stacksize = sizeof($stack); - if ($type == 'start') - { - // empty stack, so add from the last close tag or the beginning of the string - if ($stacksize == 0) - { - $newtext .= substr($text, $substr_pos, $pos - $substr_pos); - } - array_push($stack, $pos); - } - else - { - // pop off the latest opened tag - if ($stacksize) - { - array_pop($stack); - $substr_pos = $pos + 8; - } - } - } + do { + // build a stack that represents when a quote tag is opened + // and add non-quote text to the new string + $stack = []; + $newtext = '[...] '; + $substr_pos = 0; + foreach ($pos_list as $pos => $type) { + $stacksize = count($stack); + if ($type == 'start') { + // empty stack, so add from the last close tag or the beginning of the string + if ($stacksize == 0) { + $newtext .= substr($text, $substr_pos, $pos - $substr_pos); + } + $stack[] = $pos; + } else { + // pop off the latest opened tag + if ($stacksize) { + array_pop($stack); + $substr_pos = $pos + 8; + } + } + } - // add any trailing text - $newtext .= substr($text, $substr_pos); + // add any trailing text + $newtext .= substr($text, $substr_pos); - // check to see if there's a stack remaining, remove those points - // as key points, and repeat. Allows emulation of a non-greedy-type - // recursion. - if ($stack) - { - foreach ($stack AS $pos) - { - unset($pos_list["$pos"]); - } - } - } - while ($stack); + // check to see if there's a stack remaining, remove those points + // as key points, and repeat. Allows emulation of a non-greedy-type + // recursion. + if ($stack) { + foreach ($stack as $pos) { + unset($pos_list[(string)$pos]); + } + } + } while ($stack); - return $newtext; + return $newtext; } // ############################################################################# /** * Strips away bbcode from a given string, leaving plain text * - * @param string Text to be stripped of bbcode tags - * @param boolean If true, strip away quote tags AND their contents - * @param boolean If true, use the fast-and-dirty method rather than the shiny and nice method + * @param string Text to be stripped of bbcode tags + * @param boolean If true, strip away quote tags AND their contents + * @param boolean If true, use the fast-and-dirty method rather than the shiny and nice method * - * @return string + * @return string */ -function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $showlinks = true) +function strip_bbcode($message, $stripquotes = true, $fast_and_dirty = false, $showlinks = true) { - $find = array(); - $replace = array(); + $find = []; + $replace = []; - if ($stripquotes) - { - // [quote=username] and [quote] - $message = strip_quotes($message); - } + if ($stripquotes) { + // [quote=username] and [quote] + $message = strip_quotes($message); + } - // a really quick and rather nasty way of removing bbcode - if ($fast_and_dirty) - { - // any old thing in square brackets - $find[] = '#\[.*/?\]#siU'; - $replace = ''; + // a really quick and rather nasty way of removing bbcode + if ($fast_and_dirty) { + // any old thing in square brackets + $find[] = '#\[.*/?\]#siU'; + $replace = []; - $message = preg_replace($find, $replace, $message); - } - // the preferable way to remove bbcode - else - { - // simple links - $find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU'; - $replace[] = '\3'; + $message = preg_replace($find, $replace, $message); + } // the preferable way to remove bbcode + else { + // simple links + $find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU'; + $replace[] = '\3'; - // named links - $find[] = '#\[(email|url)=("??)(.+)\\2\](.+)\[/\\1\]#siU'; - $replace[] = ($showlinks ? '\4 (\3)' : '\4'); + // named links + $find[] = '#\[(email|url)=("??)(.+)\\2\](.+)\[/\\1\]#siU'; + $replace[] = ($showlinks ? '\4 (\3)' : '\4'); - // smilies - $find[] = '#(?<=^|\W)(:\w+?:)(?=$|\W)#'; - $replace[] = ''; + // smilies + $find[] = '#(?<=^|\W)(:\w+?:)(?=$|\W)#'; + $replace[] = ''; - // replace - $message = preg_replace($find, $replace, $message); + // replace + $message = preg_replace($find, $replace, $message); - // strip out all other instances of [x]...[/x] - while (preg_match('#\[([a-z]+)\s*?(?:[^\]]*?)\](.*?)(\[/\1\])#is', $message, $m)) - { - $message = str_replace($m[0], $m[2], $message); - } + // strip out all other instances of [x]...[/x] + while (preg_match('#\[([a-z]+)\s*?(?:[^\]]*?)\](.*?)(\[/\1\])#is', $message, $m)) { + $message = str_replace($m[0], $m[2], $message); + } - $replace = array('[*]', '[hr]', '[br]', '[align=center]', '[align=left]', '[align=right]'); - $message = str_replace($replace, ' ', $message); - } + $replace = ['[*]', '[hr]', '[br]', '[align=center]', '[align=left]', '[align=right]']; + $message = str_replace($replace, ' ', $message); + } - return $message; + return $message; } -function extract_search_words ($text) +function extract_search_words($text) { - global $bb_cfg; + $max_words_count = config()->get('max_search_words_per_post'); + $min_word_len = max(2, config()->get('search_min_word_len') - 1); + $max_word_len = config()->get('search_max_word_len'); - $max_words_count = $bb_cfg['max_search_words_per_post']; - $min_word_len = max(2, $bb_cfg['search_min_word_len'] - 1); - $max_word_len = $bb_cfg['search_max_word_len']; + $text = ' ' . str_compact(strip_tags(mb_strtolower($text))) . ' '; + $text = str_replace(['[', ']'], ['[', ']'], $text); - $text = ' ' . str_compact(strip_tags(mb_strtolower($text))) . ' '; - $text = str_replace(array('[', ']'), array('[', ']'), $text); + // HTML entities like   + $text = preg_replace('/(\w*?)&#?[0-9a-z]+;(\w*?)/iu', '', $text); + // Remove URL's ((www|ftp)\.[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]*?) + $text = preg_replace('#\b[a-z0-9]+://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+(/[0-9a-z\?\.%_\-\+=&/]+)?#u', ' ', $text); + $text = str_replace(['[url=', '?', '!'], ' ', $text); - // HTML entities like   - $text = preg_replace('/(\w*?)&#?[0-9a-z]+;(\w*?)/iu', '', $text); - // Remove URL's ((www|ftp)\.[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]*?) - $text = preg_replace('#\b[a-z0-9]+://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+(/[0-9a-z\?\.%_\-\+=&/]+)?#u', ' ', $text); - $text = str_replace('[url=', ' ', $text); - $text = str_replace('?', ' ', $text); - $text = str_replace('!', ' ', $text); + $text = strip_bbcode($text); - $text = strip_bbcode($text); + // Filter out characters like ^, $, &, change "it's" to "its" + $text = preg_replace('#[.,:;]#u', ' ', $text); - // Filter out characters like ^, $, &, change "it's" to "its" - $text = preg_replace('#[.,:;]#u', ' ', $text); + // Trim 1+ spaces to one space and split this string into unique words + $text = array_unique(explode(' ', str_compact($text))); - // short & long words - // $text = preg_replace('#(?<=^|\s)(\S{1,'.$min_word_len.'}|\S{'.$max_word_len.',}|\W*)(?=$|\s)#u', ' ', $text); + // short & long words 2 + $text_out = []; + foreach ($text as $word) { + if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) { + $text_out[] = $word; + } + } + $text = $text_out; - $text = remove_stopwords($text); -# $text = replace_synonyms($text); + if (count($text) > $max_words_count) { + $text = array_splice($text, 0, $max_words_count); + } - // Trim 1+ spaces to one space and split this string into unique words - $text = array_unique(explode(' ', str_compact($text))); - - // short & long words 2 - $text_out = array(); - foreach ($text as $word) - { - if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) $text_out[] = $word; - } - $text = $text_out; - - if (sizeof($text) > $max_words_count) - { -# shuffle($text); - $text = array_splice($text, 0, $max_words_count); - } - - return $text; + return $text; } -function replace_synonyms ($text) +function add_search_words($post_id, $post_message, $topic_title = '', $only_return_words = false) { - static $syn_match = null, $syn_replace = null; + $text = $topic_title . ' ' . $post_message; + $words = ($text) ? extract_search_words($text) : []; - if (is_null($syn_match)) - { - preg_match_all("#(\w+) (\w+)(\r?\n|$)#", @file_get_contents(LANG_DIR .'search_synonyms.txt'), $m); + if ($only_return_words || config()->get('search_engine_type') == 'sphinx') { + return implode("\n", $words); + } - $syn_match = $m[2]; - $syn_replace = $m[1]; + DB()->query("DELETE FROM " . BB_POSTS_SEARCH . " WHERE post_id = $post_id"); - array_deep($syn_match, 'pad_with_space'); - array_deep($syn_replace, 'pad_with_space'); - } - - return ($syn_match && $syn_replace) ? str_replace($syn_match, $syn_replace, $text) : $text; + if ($words_sql = DB()->escape(implode("\n", $words))) { + DB()->query("REPLACE INTO " . BB_POSTS_SEARCH . " (post_id, search_words) VALUES ($post_id, '$words_sql')"); + } } -function add_search_words ($post_id, $post_message, $topic_title = '', $only_return_words = false) +/** + * Dirty class removed from here since 2.2.0 + * To add new bbcodes see at src/Legacy/BBCode.php + */ + +function bbcode2html($text) { - global $bb_cfg; + global $bbcode; - $text = $topic_title .' '. $post_message; - $words = ($text) ? extract_search_words($text) : array(); - - if ($only_return_words || $bb_cfg['search_engine_type'] == 'sphinx') - { - return join("\n", $words); - } - else - { - DB()->query("DELETE FROM ". BB_POSTS_SEARCH ." WHERE post_id = $post_id"); - - if ($words_sql = DB()->escape(join("\n", $words))) - { - DB()->query("REPLACE INTO ". BB_POSTS_SEARCH ." (post_id, search_words) VALUES ($post_id, '$words_sql')"); - } - } + if (!isset($bbcode)) { + $bbcode = new TorrentPier\Legacy\BBCode(); + } + $text = censor()->censorString($text); + return $bbcode->bbcode2html($text); } -class bbcode +function get_words_rate($text) { - var $tpl = array(); // шаблоны для замены тегов - var $smilies = null; // смайлы - var $found_spam = null; // найденные спам "слова" - var $del_words = array(); // см. get_words_rate() - var $tidy_cfg = array( - 'drop-empty-paras' => false, - 'fix-uri' => false, - 'force-output' => true, - 'hide-comments' => true, - 'join-classes' => false, - 'join-styles' => false, - 'merge-divs' => false, - 'merge-spans' => false, - 'newline' => 'LF', - 'output-xhtml' => true, - 'preserve-entities' => true, - 'quiet' => true, - 'quote-ampersand' => false, - 'show-body-only' => true, - 'show-errors' => false, - 'show-warnings' => false, - 'wrap' => 0, - ); - var $block_tags = array( - 'align', - 'br', - 'clear', - 'hr', - 'list', - 'pre', - 'quote', - 'spoiler', - ); - var $preg = array(); - var $str = array(); - var $preg_search = array(); - var $preg_repl = array(); - var $str_search = array(); - var $str_repl = array(); - - /** - * Constructor - */ - function bbcode () - { - $this->tpl = get_bbcode_tpl(); - - $this->init_replacements(); - } - - /** - * init_replacements - */ - function init_replacements () - { - $tpl = $this->tpl; - $img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?'; - $email_exp = '[a-z0-9&\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+'; - - $this->preg = array( - '#\[quote="(.+?)"\]#isu' => $tpl['quote_username_open'], - '#\[spoiler="(.+?)"\]#isu' => $tpl['spoiler_title_open'], - '#\[list=(a|A|i|I|1)\]#isu' => '
      ', - '#\[\*=(\d+)\]#isu' => '
    • ', - '#\[pre\](.*?)\[/pre\]#isu' => '
      $1
      ', - '#\[name=([a-zA-Z0-9_]+?)\]#isu' => '', - '#\[url=\#([a-zA-Z0-9_]+?)\](.*?)\[/url\]#isu' => '$2', - '#\[color=([\#0-9a-zA-Z]+)\]#isu' => '', - '#\[size=([1-2]?[0-9])\]#isu' => '', - '#\[align=(left|right|center|justify)\]#isu' => '', - '#\[font="([\w\- \']+)"\]#isu' => '', - "#\[img\]($img_exp)\[/img\]#isu" => $tpl['img'], - "#\[img=(left|right|center)\]($img_exp)\[/img\]\s*#isu" => $tpl['img_aligned'], - "#\[email\]($email_exp)\[/email\]#isu" => '$1', - "#\[qpost=([0-9]*)\]#isu" => '$1', - ); - - $this->str = array( - '[quote]' => $tpl['quote_open'], - '[/quote]' => $tpl['quote_close'], - '[spoiler]' => $tpl['spoiler_open'], - '[/spoiler]' => $tpl['spoiler_close'], - '[list]' => '
        ', - '[*]' => '
      • ', - '[/list]' => '
      ', - '[/color]' => '
      ', - '[/size]' => '
      ', - '[/align]' => '
      ', - '[/font]' => '
      ', - '[tab]' => '    ', - '[br]' => "\n\n", - '[hr]' => $tpl['hr'], - '[b]' => '', - '[/b]' => '', - '[u]' => '', - '[/u]' => '', - '[i]' => '', - '[/i]' => '', - '[s]' => '', - '[/s]' => '', - '[del]' => '', - '[/del]' => '', - '[clear]' => '
       
      ', - ); - - $this->preg_search = array_keys($this->preg); - $this->preg_repl = array_values($this->preg); - $this->str_search = array_keys($this->str); - $this->str_repl = array_values($this->str); - } - - /** - * bbcode2html - * $text должен быть уже обработан htmlCHR($text, false, ENT_NOQUOTES); - */ - function bbcode2html ($text) - { - global $bb_cfg; - - $text = " $text "; - $text = $this->clean_up($text); - $text = $this->spam_filter($text); - - // Tag parse - if (strpos($text, '[') !== false) - { - // [code] - $text = preg_replace_callback('#(\s*)\[code\](.+?)\[/code\](\s*)#s', array(&$this, 'code_callback'), $text); - - // Escape tags inside tiltes in [quote="tilte"] - $text = preg_replace_callback('#(\[(quote|spoiler)=")(.+?)("\])#', array(&$this, 'escape_tiltes_callback'), $text); - - // [url] - $url_exp = '[\w\#!$%&~/.\-;:=,?@а-яА-Я()\[\]+]+?'; - $text = preg_replace_callback("#\[url\]((?:https?://)?$url_exp)\[/url\]#isu", array(&$this, 'url_callback'), $text); - $text = preg_replace_callback("#\[url\](www\.$url_exp)\[/url\]#isu", array(&$this, 'url_callback'), $text); - $text = preg_replace_callback("#\[url=((?:https?://)?$url_exp)\]([^?\n\t].*?)\[/url\]#isu", array(&$this, 'url_callback'), $text); - $text = preg_replace_callback("#\[url=(www\.$url_exp)\]([^?\n\t].*?)\[/url\]#isu", array(&$this, 'url_callback'), $text); - - // Normalize block level tags wrapped with new lines - $block_tags = join('|', $this->block_tags); - $text = str_replace("\n\n[hr]\n\n", '[br][hr][br]', $text); - $text = preg_replace("#(\s*)(\[/?($block_tags)(.*?)\])(\s*)#", '$2', $text); - - // Tag replacements - $text = preg_replace($this->preg_search, $this->preg_repl, $text); - $text = str_replace($this->str_search, $this->str_repl, $text); - } - - $text = $this->make_clickable($text); - $text = $this->smilies_pass($text); - $text = $this->new_line2html($text); - $text = trim($text); - - if ($bb_cfg['tidy_post']) - { - $text = $this->tidy($text); - } - - return trim($text); - } - - /** - * Clean up - */ - static function clean_up ($text) - { - $text = trim($text); - $text = str_replace("\r", '', $text); - $text = preg_replace('#[ \t]+$#m', '', $text); // trailing spaces - $text = preg_replace('#\n{3,}#', "\n\n", $text); - return $text; - } - - /** - * Spam filter - */ - private function spam_filter ($text) - { - global $bb_cfg; - static $spam_words = null; - static $spam_replace = ' СПАМ'; - - if (isset($this)) - { - $found_spam =& $this->found_spam; - } - - // set $spam_words and $spam_replace - if (!$bb_cfg['spam_filter_file_path']) - { - return $text; - } - if (is_null($spam_words)) - { - $spam_words = file_get_contents($bb_cfg['spam_filter_file_path']); - $spam_words = strtolower($spam_words); - $spam_words = explode("\n", $spam_words); - } - - $found_spam = array(); - - $tm_start = utime(); - - $msg_decoded = $text; - $msg_decoded = html_entity_decode($msg_decoded); - $msg_decoded = urldecode($msg_decoded); - $msg_decoded = str_replace('&', ' &', $msg_decoded); - - $msg_search = strtolower($msg_decoded); - - foreach ($spam_words as $spam_str) - { - if (!$spam_str = trim($spam_str)) - { - continue; - } - if (strpos($msg_search, $spam_str) !== false) - { - $found_spam[] = $spam_str; - } - } - if ($found_spam) - { - $spam_exp = array(); - foreach ($found_spam as $keyword) - { - $spam_exp[] = preg_quote($keyword, '/'); - } - $spam_exp = join('|', $spam_exp); - - $text = preg_replace("/($spam_exp)(\S*)/i", $spam_replace, $msg_decoded); - $text = htmlCHR($text, false, ENT_NOQUOTES); -# bb_log(date("H:i:s") ." | ". sprintf('%.4f', (utime() - $tm_start)) ." | ". sprintf('%-6s', strlen($text)) ." | ". join(' ** ', $found_spam) ."\n", 'spam_filter'); - } - - return $text; - } - - /** - * [code] callback - */ - function code_callback ($m) - { - $code = trim($m[2]); - $code = str_replace(' ', '  ', $code); - $code = str_replace(' ', '  ', $code); - $code = str_replace("\t", '  ', $code); - $code = str_replace(array('[', ']', ':', ')'), array('[', ']', ':', ')'), $code); - return $this->tpl['code_open'] . $code . $this->tpl['code_close']; - } - - /** - * [url] callback - */ - function url_callback ($m) - { - global $bb_cfg; - - $url = trim($m[1]); - $url_name = (isset($m[2])) ? trim($m[2]) : $url; - - if (!preg_match("#^https?://#isu", $url) && !preg_match("/^#/", $url)) $url = 'http://' . $url; - - if (in_array(parse_url($url, PHP_URL_HOST), $bb_cfg['nofollow']['allowed_url']) || $bb_cfg['nofollow']['disabled']) - { - $link = "$url_name"; - } - else - { - $link = "$url_name"; - } - - return $link; - } - - /** - * Escape tags inside tiltes in [quote="tilte"] - */ - function escape_tiltes_callback ($m) - { - $tilte = substr($m[3], 0, 250); - $tilte = str_replace(array('[', ']', ':', ')', '"'), array('[', ']', ':', ')', '"'), $tilte); - // еще раз htmlspecialchars, т.к. при извлечении из title происходит обратное преобразование - $tilte = htmlspecialchars($tilte, ENT_QUOTES); - return $m[1] . $tilte . $m[4]; - } - - /** - * make_clickable - */ - function make_clickable ($text) - { - $url_regexp = "# - (? $max_len) ? mb_substr($href, 0, $max_len - 19) .'...'. mb_substr($href, -16) : $href; - - if (in_array(parse_url($href, PHP_URL_HOST), $bb_cfg['nofollow']['allowed_url']) || $bb_cfg['nofollow']['disabled']) - { - $link = "$name"; - } - else - { - $link = "$name"; - } - - return $link; - } - - /** - * smilies_pass - */ - function smilies_pass ($text) - { - global $datastore; - - if (is_null($this->smilies)) - { - $this->smilies = $datastore->get('smile_replacements'); - } - if ($this->smilies) - { - $parsed_text = preg_replace($this->smilies['orig'], $this->smilies['repl'], $text, 101, $smilies_cnt); - $text = ($smilies_cnt <= 100) ? $parsed_text : $text; - } - - return $text; - } - - /** - * new_line2html - */ - function new_line2html ($text) - { - $text = preg_replace('#\n{2,}#', '
      ', $text); - $text = str_replace("\n", '
      ', $text); - return $text; - } - - /** - * tidy - */ - function tidy ($text) - { - $text = tidy_repair_string($text, $this->tidy_cfg, 'utf8'); - return $text; - } + static $wr = null; + if (!isset($wr)) { + $wr = new TorrentPier\Legacy\WordsRate(); + } + return $wr->get_words_rate($text); } -function bbcode2html ($text) +function hide_passkey($str) { - global $bbcode; - - if (!isset($bbcode)) - { - $bbcode = new bbcode(); - } - $orig_word = array(); - $replacement_word = array(); - obtain_word_list($orig_word, $replacement_word); - if ( count($orig_word) ) - { - $text = preg_replace($orig_word, $replacement_word, $text); - } - return $bbcode->bbcode2html($text); + return preg_replace("#\?{config()->get('passkey_key')}=[a-zA-Z0-9]{" . BT_AUTH_KEY_LENGTH . "}#", "?{config()->get('passkey_key')}=passkey", $str); } -class words_rate +function get_parsed_post($postrow, $mode = 'full', $return_chars = 600) { - var $dbg_mode = false; - var $words_rate = 0; - var $deleted_words = array(); - var $del_text_hl = ''; - var $words_del_exp = ''; - var $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; + if (config()->get('use_posts_cache') && !empty($postrow['post_html'])) { + return $postrow['post_html']; + } - function words_rate () - { - // слова начинающиеся на.. - $del_list = file_get_contents(BB_ROOT .'/library/words_rate_del_list.txt'); - $del_list = str_compact($del_list); - $del_list = str_replace(' ', '|', preg_quote($del_list, '/')); - $del_exp = '/\b('.$del_list.')[\w\-]*/i'; + $message = bbcode2html($postrow['post_text']); - $this->words_del_exp = $del_exp; - } + // Posts cache + if (config()->get('use_posts_cache')) { + DB()->shutdown['post_html'][] = [ + 'post_id' => (int)$postrow['post_id'], + 'post_html' => (string)$message + ]; + } - /** - * возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д. - */ - function get_words_rate ($text) - { - $this->words_rate = 127; // максимальное значение по умолчанию - $this->deleted_words = array(); - $this->del_text_hl = $text; - - // длинное сообщение - if (strlen($text) > 600) - { - return $this->words_rate; - } - // вырезаем цитаты если содержит +1 - if (preg_match('#\+\d+#', $text)) - { - $text = strip_quotes($text); - } - // содержит ссылку - if (strpos($text, '://')) - { - return $this->words_rate; - } - // вопрос - if ($questions = preg_match_all('#\w\?+#', $text, $m)) - { - if ($questions >= 1) - { - return $this->words_rate; - } - } - - if ($this->dbg_mode) - { - preg_match_all($this->words_del_exp, $text, $this->deleted_words); - $text_dbg = preg_replace($this->words_del_exp, '$0', $text); - $this->del_text_hl = '
      '. $text_dbg . '
      '; - } - $text = preg_replace($this->words_del_exp, '', $text); - - // удаление смайлов - $text = preg_replace('#:\w+:#', '', $text); - // удаление bbcode тегов - $text = preg_replace('#\[\S+\]#', '', $text); - - $words_count = preg_match_all($this->words_cnt_exp, $text, $m); - - if ($words_count !== false && $words_count < 127) - { - $this->words_rate = ($words_count == 0) ? 1 : $words_count; - } - - return $this->words_rate; - } + return $message; } -function get_words_rate ($text) +function update_post_html($postrow) { - static $wr = null; - if (!isset($wr)) - { - $wr = new words_rate(); - } - return $wr->get_words_rate($text); + DB()->query("DELETE FROM " . BB_POSTS_HTML . " WHERE post_id = " . (int)$postrow['post_id']); } - -function hide_passkey ($str) -{ - global $bb_cfg; - return preg_replace("#\?{$bb_cfg['passkey_key']}=[a-zA-Z0-9]{". BT_AUTH_KEY_LENGTH ."}#", "?{$bb_cfg['passkey_key']}=passkey", $str); -} - -function get_parsed_post ($postrow, $mode = 'full', $return_chars = 600) -{ - global $bb_cfg; - - if ($bb_cfg['use_posts_cache'] && !empty($postrow['post_html'])) - { - return $postrow['post_html']; - } - - $message = bbcode2html($postrow['post_text']); - - // Posts cache - if ($bb_cfg['use_posts_cache']) - { - DB()->shutdown['post_html'][] = array( - 'post_id' => (int) $postrow['post_id'], - 'post_html' => (string) $message, - ); - } - - return $message; -} - -function update_post_html ($postrow) -{ - DB()->query("DELETE FROM ". BB_POSTS_HTML ." WHERE post_id = ". (int) $postrow['post_id'] ." LIMIT 1"); -} \ No newline at end of file diff --git a/library/includes/cache/apc.php b/library/includes/cache/apc.php deleted file mode 100644 index 472d79edb..000000000 --- a/library/includes/cache/apc.php +++ /dev/null @@ -1,65 +0,0 @@ -is_installed()) - { - die('Error: APC extension not installed'); - } - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } - - function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return apc_fetch($this->prefix . $name); - } - - function set ($name, $value, $ttl = 0) - { - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return apc_store($this->prefix . $name, $value, $ttl); - } - - function rm ($name = '') - { - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return apc_delete($this->prefix . $name); - } - else - { - return apc_clear_cache(); - } - } - - function is_installed () - { - return function_exists('apc_fetch'); - } -} \ No newline at end of file diff --git a/library/includes/cache/common.php b/library/includes/cache/common.php deleted file mode 100644 index 79a0ff525..000000000 --- a/library/includes/cache/common.php +++ /dev/null @@ -1,84 +0,0 @@ -dbg_enabled) return; - - $id =& $this->dbg_id; - $dbg =& $this->dbg[$id]; - - if ($mode == 'start') - { - $this->sql_starttime = utime(); - - $dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query); - $dbg['src'] = $this->debug_find_source(); - $dbg['file'] = $this->debug_find_source('file'); - $dbg['line'] = $this->debug_find_source('line'); - $dbg['time'] = ''; - } - else if ($mode == 'stop') - { - $this->cur_query_time = utime() - $this->sql_starttime; - $this->sql_timetotal += $this->cur_query_time; - $dbg['time'] = $this->cur_query_time; - $id++; - } - } - - function debug_find_source ($mode = '') - { - foreach (debug_backtrace() as $trace) - { - if ($trace['file'] !== __FILE__) - { - switch ($mode) - { - case 'file': return $trace['file']; - case 'line': return $trace['line']; - default: return hide_bb_path($trace['file']) .'('. $trace['line'] .')'; - } - } - } - return 'src not found'; - } -} \ No newline at end of file diff --git a/library/includes/cache/file.php b/library/includes/cache/file.php deleted file mode 100644 index 8538d22c6..000000000 --- a/library/includes/cache/file.php +++ /dev/null @@ -1,136 +0,0 @@ -dir = $dir; - $this->prefix = $prefix; - $this->dbg_enabled = sql_dbg_enabled(); - } - - function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; - - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - - if (file_exists($filename)) - { - require($filename); - } - - $this->debug('stop'); - $this->cur_query = null; - - return (!empty($filecache['value'])) ? $filecache['value'] : false; - } - - function set ($name, $value, $ttl = 86400) - { - if (!function_exists('var_export')) - { - return false; - } - - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - - $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; - $expire = TIMENOW + $ttl; - $cache_data = array( - 'expire' => $expire, - 'value' => $value, - ); - - $filecache = "'; - - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return (bool) file_write($filecache, $filename, false, true, true); - } - - function rm ($name = '') - { - $clear = false; - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - - $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; - if (file_exists($filename)) - { - $clear = (bool) unlink($filename); - } - - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - } - else - { - if (is_dir($this->dir)) - { - if ($dh = opendir($this->dir)) - { - while (($file = readdir($dh)) !== false) - { - if ($file != "." && $file != "..") - { - $filename = $this->dir . $file; - - unlink($filename); - $clear = true; - } - } - closedir($dh); - } - } - } - return $clear; - } - - function gc ($expire_time = TIMENOW) - { - $clear = false; - - if (is_dir($this->dir)) - { - if ($dh = opendir($this->dir)) - { - while (($file = readdir($dh)) !== false) - { - if ($file != "." && $file != "..") - { - $filename = $this->dir . $file; - - require($filename); - - if(!empty($filecache['expire']) && ($filecache['expire'] < $expire_time)) - { - unlink($filename); - $clear = true; - } - } - } - closedir($dh); - } - } - - return $clear; - } -} \ No newline at end of file diff --git a/library/includes/cache/memcache.php b/library/includes/cache/memcache.php deleted file mode 100644 index 0c76fecf6..000000000 --- a/library/includes/cache/memcache.php +++ /dev/null @@ -1,100 +0,0 @@ -is_installed()) - { - die('Error: Memcached extension not installed'); - } - - $this->cfg = $cfg; - $this->prefix = $prefix; - $this->memcache = new Memcache; - $this->dbg_enabled = sql_dbg_enabled(); - } - - function connect () - { - $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; - - $this->cur_query = $connect_type .' '. $this->cfg['host'] .':'. $this->cfg['port']; - $this->debug('start'); - - if (@$this->memcache->$connect_type($this->cfg['host'], $this->cfg['port'])) - { - $this->connected = true; - } - - if (DBG_LOG) dbg_log(' ', 'CACHE-connect'. ($this->connected ? '' : '-FAIL')); - - if (!$this->connected && $this->cfg['con_required']) - { - die('Could not connect to memcached server'); - } - - $this->debug('stop'); - $this->cur_query = null; - } - - function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - if (!$this->connected) $this->connect(); - - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return ($this->connected) ? $this->memcache->get($this->prefix . $name) : false; - } - - function set ($name, $value, $ttl = 0) - { - if (!$this->connected) $this->connect(); - - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return ($this->connected) ? $this->memcache->set($this->prefix . $name, $value, false, $ttl) : false; - } - - function rm ($name = '') - { - if (!$this->connected) $this->connect(); - - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return ($this->connected) ? $this->memcache->delete($this->prefix . $name, 0) : false; - } - else - { - return ($this->connected) ? $this->memcache->flush() : false; - } - } - - function is_installed () - { - return class_exists('Memcache'); - } -} \ No newline at end of file diff --git a/library/includes/cache/redis.php b/library/includes/cache/redis.php deleted file mode 100644 index 431dade3a..000000000 --- a/library/includes/cache/redis.php +++ /dev/null @@ -1,109 +0,0 @@ -is_installed()) - { - die('Error: Redis extension not installed'); - } - - $this->cfg = $cfg; - $this->prefix = $prefix; - $this->redis = new Redis(); - $this->dbg_enabled = sql_dbg_enabled(); - } - - function connect () - { - $this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port']; - $this->debug('start'); - - if (@$this->redis->connect($this->cfg['host'], $this->cfg['port'])) - { - $this->connected = true; - } - - if (!$this->connected && $this->cfg['con_required']) - { - die('Could not connect to redis server'); - } - - $this->debug('stop'); - $this->cur_query = null; - } - - function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - if (!$this->connected) $this->connect(); - - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return ($this->connected) ? unserialize($this->redis->get($this->prefix . $name)) : false; - } - - function set ($name, $value, $ttl = 0) - { - if (!$this->connected) $this->connect(); - - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - - if ($this->redis->set($this->prefix . $name, serialize($value))) - { - if ($ttl > 0) - { - $this->redis->expire($this->prefix . $name, $ttl); - } - - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return true; - } - else - { - return false; - } - } - - function rm ($name = '') - { - if (!$this->connected) $this->connect(); - - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return ($this->connected) ? $this->redis->del($this->prefix . $name) : false; - } - else - { - return ($this->connected) ? $this->redis->flushdb() : false; - } - } - - function is_installed () - { - return class_exists('Redis'); - } -} \ No newline at end of file diff --git a/library/includes/cache/sqlite.php b/library/includes/cache/sqlite.php deleted file mode 100644 index cc9004bcf..000000000 --- a/library/includes/cache/sqlite.php +++ /dev/null @@ -1,288 +0,0 @@ - '/path/to/cache.db.sqlite', - 'table_name' => 'cache', - 'table_schema' => 'CREATE TABLE cache ( - cache_name VARCHAR(255), - cache_expire_time INT, - cache_value TEXT, - PRIMARY KEY (cache_name) - )', - 'pconnect' => true, - 'con_required' => true, - 'log_name' => 'CACHE', - ); - - function cache_sqlite ($cfg, $prefix = null) - { - $this->cfg = array_merge($this->cfg, $cfg); - $this->db = new sqlite_common($this->cfg); - $this->prefix = $prefix; - } - - function get ($name, $get_miss_key_callback = '', $ttl = 604800) - { - if (empty($name)) - { - return is_array($name) ? array() : false; - } - $this->db->shard($name); - $cached_items = array(); - $this->prefix_len = strlen($this->prefix); - $this->prefix_sql = SQLite3::escapeString($this->prefix); - - $name_ary = $name_sql = (array) $name; - array_deep($name_sql, 'SQLite3::escapeString'); - - // get available items - $rowset = $this->db->fetch_rowset(" - SELECT cache_name, cache_value - FROM ". $this->cfg['table_name'] ." - WHERE cache_name IN('$this->prefix_sql". join("','$this->prefix_sql", $name_sql) ."') AND cache_expire_time > ". TIMENOW ." - LIMIT ". count($name) ." - "); - - $this->db->debug('start', 'unserialize()'); - foreach ($rowset as $row) - { - $cached_items[substr($row['cache_name'], $this->prefix_len)] = unserialize($row['cache_value']); - } - $this->db->debug('stop'); - - // get miss items - if ($get_miss_key_callback AND $miss_key = array_diff($name_ary, array_keys($cached_items))) - { - foreach ($get_miss_key_callback($miss_key) as $k => $v) - { - $this->set($this->prefix . $k, $v, $ttl); - $cached_items[$k] = $v; - } - } - // return - if (is_array($this->prefix . $name)) - { - return $cached_items; - } - else - { - return isset($cached_items[$name]) ? $cached_items[$name] : false; - } - } - - function set ($name, $value, $ttl = 604800) - { - $this->db->shard($this->prefix . $name); - $name_sql = SQLite3::escapeString($this->prefix . $name); - $expire = TIMENOW + $ttl; - $value_sql = SQLite3::escapeString(serialize($value)); - - $result = $this->db->query("REPLACE INTO ". $this->cfg['table_name'] ." (cache_name, cache_expire_time, cache_value) VALUES ('$name_sql', $expire, '$value_sql')"); - return (bool) $result; - } - - function rm ($name = '') - { - if ($name) - { - $this->db->shard($this->prefix . $name); - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_name = '". SQLite3::escapeString($this->prefix . $name) ."'"); - } - else - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name']); - } - return (bool) $result; - } - - function gc ($expire_time = TIMENOW) - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time"); - return ($result) ? $this->db->changes() : 0; - } -} - -class sqlite_common extends cache_common -{ - var $cfg = array( - 'db_file_path' => 'sqlite.db', - 'table_name' => 'table_name', - 'table_schema' => 'CREATE TABLE table_name (...)', - 'pconnect' => true, - 'con_required' => true, - 'log_name' => 'SQLite', - 'shard_type' => 'none', # none, string, int (тип перевичного ключа для шардинга) - 'shard_val' => 0, # для string - кол. начальных символов, для int - делитель (будет использован остаток от деления) - ); - var $engine = 'SQLite'; - var $dbh = null; - var $connected = false; - var $shard_val = false; - - var $table_create_attempts = 0; - - function sqlite_common ($cfg) - { - $this->cfg = array_merge($this->cfg, $cfg); - $this->dbg_enabled = sql_dbg_enabled(); - } - - function connect () - { - $this->cur_query = ($this->dbg_enabled) ? 'connect to: '. $this->cfg['db_file_path'] : 'connect'; - $this->debug('start'); - - if (@$this->dbh = new SQLite3($this->cfg['db_file_path'])) - { - $this->connected = true; - } - - if (DBG_LOG) dbg_log(' ', $this->cfg['log_name'] .'-connect'. ($this->connected ? '' : '-FAIL')); - - if (!$this->connected && $this->cfg['con_required']) - { - trigger_error('SQLite not connected', E_USER_ERROR); - } - - $this->debug('stop'); - $this->cur_query = null; - } - - function create_table () - { - $this->table_create_attempts++; - return $this->dbh->query($this->cfg['table_schema']); - } - - function shard ($name) - { - $type = $this->cfg['shard_type']; - - if ($type == 'none') return; - if (is_array($name)) trigger_error('cannot shard: $name is array', E_USER_ERROR); - - // define shard_val - if ($type == 'string') - { - $shard_val = substr($name, 0, $this->cfg['shard_val']); - } - else - { - $shard_val = $name % $this->cfg['shard_val']; - } - // все запросы должны быть к одному и тому же шарду - if ($this->shard_val !== false) - { - if ($shard_val != $this->shard_val) - { - trigger_error("shard cannot be reassigned. [{$this->shard_val}, $shard_val, $name]", E_USER_ERROR); - } - else - { - return; - } - } - $this->shard_val = $shard_val; - $this->cfg['db_file_path'] = str_replace('*', $shard_val, $this->cfg['db_file_path']); - } - - function query ($query) - { - if (!$this->connected) $this->connect(); - - $this->cur_query = $query; - $this->debug('start'); - - if (!$result = @$this->dbh->query($query)) - { - $rowsresult = $this->dbh->query("PRAGMA table_info({$this->cfg['table_name']})"); - $rowscount = 0; - while ($row = $rowsresult->fetchArray(SQLITE3_ASSOC)) - { - $rowscount++; - } - if (!$this->table_create_attempts && !$rowscount) - { - if ($this->create_table()) - { - $result = $this->dbh->query($query); - } - } - if (!$result) - { - $this->trigger_error($this->get_error_msg()); - } - } - - $this->debug('stop'); - $this->cur_query = null; - - $this->num_queries++; - - return $result; - } - - function fetch_row ($query) - { - $result = $this->query($query); - return is_resource($result) ? $result->fetchArray(SQLITE3_ASSOC) : false; - } - - function fetch_rowset ($query) - { - $result = $this->query($query); - $rowset = array(); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) - { - $rowset[] = $row; - } - return $rowset; - } - - function changes () - { - return is_resource($this->dbh) ? $this->dbh->changes() : 0; - } - - function escape ($str) - { - return SQLite3::escapeString($str); - } - - function get_error_msg () - { - return 'SQLite error #'. ($err_code = $this->dbh->lastErrorCode()) .': '. $this->dbh->lastErrorMsg(); - } - - function rm ($name = '') - { - if ($name) - { - $this->db->shard($this->prefix . $name); - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_name = '". SQLite3::escapeString($this->prefix . $name) ."'"); - } - else - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name']); - } - return (bool) $result; - } - - function gc ($expire_time = TIMENOW) - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time"); - return ($result) ? sqlite_changes($this->db->dbh) : 0; - } - - function trigger_error ($msg = 'DB Error') - { - if (error_reporting()) trigger_error($msg, E_USER_ERROR); - } -} \ No newline at end of file diff --git a/library/includes/cache/xcache.php b/library/includes/cache/xcache.php deleted file mode 100644 index b1e391f72..000000000 --- a/library/includes/cache/xcache.php +++ /dev/null @@ -1,67 +0,0 @@ -is_installed()) - { - die('Error: XCache extension not installed'); - } - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } - - function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return xcache_get($this->prefix . $name); - } - - function set ($name, $value, $ttl = 0) - { - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return xcache_set($this->prefix . $name, $value, $ttl); - } - - function rm ($name = '') - { - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - - return xcache_unset($this->prefix . $name); - } - else - { - xcache_clear_cache(XC_TYPE_PHP, 0); - xcache_clear_cache(XC_TYPE_VAR, 0); - return; - } - } - - function is_installed () - { - return function_exists('xcache_get'); - } -} \ No newline at end of file diff --git a/library/includes/captcha/.htaccess b/library/includes/captcha/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/library/includes/captcha/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/library/includes/captcha/captcha.php b/library/includes/captcha/captcha.php deleted file mode 100644 index 4b8366ca2..000000000 --- a/library/includes/captcha/captcha.php +++ /dev/null @@ -1,398 +0,0 @@ -cfg = $cfg; - $this->can_bypass = !empty($_POST[$this->cfg['secret_key']]); - $this->curr_code_key = $this->get_key_name(TIMENOW); - $this->prev_code_key = $this->get_key_name(TIMENOW - $this->key_ttl); - } - - function verify_code () - { - // обход - if ($this->can_bypass || $this->cfg['disabled']) - { - if (!empty($_POST[$this->cfg['secret_key']])) log_get('cap/off', @$_POST['login_username']); - return true; - } - // cap_sid - if (isset($_POST[$this->cap_sid_key]) && verify_id($_POST[$this->cap_sid_key], $this->cap_sid_len)) - { - $this->cap_sid_val = $_POST[$this->cap_sid_key]; - } - else - { - return false; - } - // code - $entered_code = ''; - if (isset($_POST[$this->curr_code_key])) - { - $entered_code = (string) $_POST[$this->curr_code_key]; - } - else if (isset($_POST[$this->prev_code_key])) - { - $entered_code = (string) $_POST[$this->prev_code_key]; - } - - $entered_code = strtolower(trim($entered_code)); - - $valid_code = $this->get_code(); - - if ($entered_code === $valid_code) - { - $this->del_sid(); - return true; - } - else - { - $this->del_sid(); - return false; - } - } - - function get_html () - { - if ($this->cfg['disabled']) return ''; - - $this->gen_cap_sid(); - $this->new_img_url = $this->get_img_url($this->new_cap_id); - $this->new_code_key = $this->get_key_name(TIMENOW); - - return ' -
      pic
      - - - '; - } - - function get_code () - { - if ($this->cap_sid_val AND $code = CACHE('bb_cap_sid')->get('c_sid_'. $this->cap_sid_val)) - { - return strtolower(trim($code)); - } - else - { - return null; - } - } - - function del_sid () - { - if ($this->cap_sid_val) - { - CACHE('bb_cap_sid')->rm('c_sid_'. $this->cap_sid_val); - } - } - - function gen_cap_sid () - { - $row = DB('cap')->fetch_row("SELECT MIN(cap_id) AS min_id, MAX(cap_id) AS max_id FROM ". BB_CAPTCHA ." WHERE cap_id > 0"); - - $min_id = intval($row['min_id']) + $this->new_per_minute; - $max_id = intval($row['max_id']); - - $this->new_cap_id = ($min_id < $max_id) ? mt_rand($min_id, $max_id) : $max_id; - - $this->new_cap_code = (string) DB('cap')->fetch_row("SELECT cap_code FROM ". BB_CAPTCHA ." WHERE cap_id = {$this->new_cap_id}", 'cap_code'); - - $this->new_cap_sid = make_rand_str($this->cap_sid_len); - - CACHE('bb_cap_sid')->set('c_sid_'. $this->new_cap_sid, $this->new_cap_code, $this->key_ttl*2); - } - - function get_img_url ($id) - { - return $this->get_path($id, $this->cfg['img_url']); - } - - function get_img_path ($id) - { - return $this->get_path($id, $this->cfg['img_path']); - } - - function get_path ($id, $base) - { - $path = $base . ($id % 50) .'/'. $id .'.'. $this->img_ext; - return preg_replace("#/($id)(\.{$this->img_ext})\$#", '/'. md5($this->cfg['secret_key'] . md5($id)) .'$2', $path); - } - - /** - * Генерит валидное имя ключа для получения введенного кода капчи из $_POST - */ - function get_key_name ($tm) - { - return 'cap_code_'. md5($this->cfg['secret_key'] . md5($tm - ($tm % $this->key_ttl))); - } -} - -class captcha_kcaptcha extends captcha_common -{ - // generates keystring and image - function gen_img ($cap_id) - { - global $bb_cfg; - - // do not change without changing font files! - $alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; - - # symbols used to draw CAPTCHA - alphabet without similar symbols (o=0, 1=l, i=j, t=f) - $allowed_symbols = "23456789abcdeghkmnpqsuvxyz"; - - # folder with fonts - $fontsdir = INC_DIR .'captcha/kcaptcha/fonts/'; - - $fonts = array( - 'antiqua.png', - 'baskerville.png', - 'batang.png', - 'bookman.png', - 'calisto.png', - 'cambria.png', - 'centaur.png', - 'century.png', - 'chaparral.png', - 'constantia.png', - 'footlight.png', - 'garamond.png', - 'georgia.png', - 'goudy_old.png', - 'kozuka.png', - 'lucida.png', - 'minion.png', - 'palatino.png', - 'perpetua.png', - 'rockwell.png', - 'times.png', - 'warnock.png', - ); - - # CAPTCHA string length - $length = mt_rand($this->cap_min_chars, $this->cap_max_chars); - - # CAPTCHA image size (you do not need to change it, whis parameters is optimal) - $width = 120; - $height = 60; - - # symbol's vertical fluctuation amplitude divided by 2 - $fluctuation_amplitude = 5; - - # increase safety by prevention of spaces between symbols - $no_spaces = true; - - # show credits - $show_credits = true; # set to false to remove credits line. Credits adds 12 pixels to image height - $credits = $bb_cfg['server_name']; # if empty, HTTP_HOST will be shown - - # CAPTCHA image colors (RGB, 0-255) - $foreground_color = array(mt_rand(0,100), mt_rand(0,100), mt_rand(0,100)); - $background_color = array(mt_rand(200,255), mt_rand(200,255), mt_rand(200,255)); - - # JPEG quality of CAPTCHA image (bigger is better quality, but larger file size) - $jpeg_quality = 90; - - $alphabet_length=strlen($alphabet); - - do{ - // generating random keystring - while(true){ - $this->keystring=''; - for($i=0;$i<$length;$i++){ - $this->keystring.=$allowed_symbols[mt_rand(0,strlen($allowed_symbols)-1)]; - } - if(!preg_match('/cp|cb|ck|c6|c9|rn|rm|mm|co|do|cl|db|qp|qb|dp|ww/', $this->keystring)) break; - } - - $font_file = $fontsdir . $fonts[mt_rand(0, count($fonts)-1)]; - $font=imagecreatefrompng($font_file); - imagealphablending($font, true); - $fontfile_width=imagesx($font); - $fontfile_height=imagesy($font)-1; - $font_metrics=array(); - $symbol=0; - $reading_symbol=false; - - // loading font - for($i=0;$i<$fontfile_width && $symbol<$alphabet_length;$i++){ - $transparent = (imagecolorat($font, $i, 0) >> 24) == 127; - - if(!$reading_symbol && !$transparent){ - $font_metrics[$alphabet[$symbol]]=array('start'=>$i); - $reading_symbol=true; - continue; - } - - if($reading_symbol && $transparent){ - $font_metrics[$alphabet[$symbol]]['end']=$i; - $reading_symbol=false; - $symbol++; - continue; - } - } - - $img=imagecreatetruecolor($width, $height); - imagealphablending($img, true); - $white=imagecolorallocate($img, 255, 255, 255); - $black=imagecolorallocate($img, 0, 0, 0); - - imagefilledrectangle($img, 0, 0, $width-1, $height-1, $white); - - // draw text - $x=1; - for($i=0;$i<$length;$i++){ - $m=$font_metrics[$this->keystring[$i]]; - - $y=mt_rand(-$fluctuation_amplitude, $fluctuation_amplitude)+($height-$fontfile_height)/2+2; - - if($no_spaces){ - $shift=0; - if($i>0){ - $shift=10000; - for($sy=7;$sy<$fontfile_height-20;$sy+=1){ - for($sx=$m['start']-1;$sx<$m['end'];$sx+=1){ - $rgb=imagecolorat($font, $sx, $sy); - $opacity=$rgb>>24; - if($opacity<127){ - $left=$sx-$m['start']+$x; - $py=$sy+$y; - if($py>$height) break; - for($px=min($left,$width-1);$px>$left-12 && $px>=0;$px-=1){ - $color=imagecolorat($img, $px, $py) & 0xff; - if($color+$opacity<190){ - if($shift>$left-$px){ - $shift=$left-$px; - } - break; - } - } - break; - } - } - } - if($shift==10000){ - $shift=mt_rand(4,6); - } - - } - }else{ - $shift=1; - } - imagecopy($img, $font, $x-$shift, $y, $m['start'], 1, $m['end']-$m['start'], $fontfile_height); - $x+=$m['end']-$m['start']-$shift; - } - }while($x>=$width-10); // while not fit in canvas - - $center=$x/2; - - // credits - $img2=imagecreatetruecolor($width, $height+($show_credits?12:0)); - $foreground=imagecolorallocate($img2, $foreground_color[0], $foreground_color[1], $foreground_color[2]); - $background=imagecolorallocate($img2, $background_color[0], $background_color[1], $background_color[2]); - imagefilledrectangle($img2, 0, 0, $width-1, $height-1, $background); - imagefilledrectangle($img2, 0, $height, $width-1, $height+12, $foreground); - $credits=empty($credits)?$bb_cfg['server_name']:$credits; - imagestring($img2, 2, $width/2-imagefontwidth(2)*strlen($credits)/2, $height-2, $credits, $background); - - // periods - $rand1=mt_rand(750000,1200000)/10000000; - $rand2=mt_rand(750000,1200000)/10000000; - $rand3=mt_rand(750000,1200000)/10000000; - $rand4=mt_rand(750000,1200000)/10000000; - // phases - $rand5=mt_rand(0,31415926)/10000000; - $rand6=mt_rand(0,31415926)/10000000; - $rand7=mt_rand(0,31415926)/10000000; - $rand8=mt_rand(0,31415926)/10000000; - // amplitudes - $rand9=mt_rand(330,420)/110; - $rand10=mt_rand(330,450)/110; - - //wave distortion - - for($x=0;$x<$width;$x++){ - for($y=0;$y<$height;$y++){ - $sx=$x+(sin($x*$rand1+$rand5)+sin($y*$rand3+$rand6))*$rand9-$width/2+$center+1; - $sy=$y+(sin($x*$rand2+$rand7)+sin($y*$rand4+$rand8))*$rand10; - - if($sx<0 || $sy<0 || $sx>=$width-1 || $sy>=$height-1){ - continue; - }else{ - $color=imagecolorat($img, $sx, $sy) & 0xFF; - $color_x=imagecolorat($img, $sx+1, $sy) & 0xFF; - $color_y=imagecolorat($img, $sx, $sy+1) & 0xFF; - $color_xy=imagecolorat($img, $sx+1, $sy+1) & 0xFF; - } - - if($color==255 && $color_x==255 && $color_y==255 && $color_xy==255){ - continue; - }else if($color==0 && $color_x==0 && $color_y==0 && $color_xy==0){ - $newred=$foreground_color[0]; - $newgreen=$foreground_color[1]; - $newblue=$foreground_color[2]; - }else{ - $frsx=$sx-floor($sx); - $frsy=$sy-floor($sy); - $frsx1=1-$frsx; - $frsy1=1-$frsy; - - $newcolor=( - $color*$frsx1*$frsy1+ - $color_x*$frsx*$frsy1+ - $color_y*$frsx1*$frsy+ - $color_xy*$frsx*$frsy); - - if($newcolor>255) $newcolor=255; - $newcolor=$newcolor/255; - $newcolor0=1-$newcolor; - - $newred=$newcolor0*$foreground_color[0]+$newcolor*$background_color[0]; - $newgreen=$newcolor0*$foreground_color[1]+$newcolor*$background_color[1]; - $newblue=$newcolor0*$foreground_color[2]+$newcolor*$background_color[2]; - } - - imagesetpixel($img2, $x, $y, imagecolorallocate($img2, $newred, $newgreen, $newblue)); - } - } - - $img_path = $this->get_img_path($cap_id); - file_write('', $img_path, null, true, true); - - imagejpeg($img2, $img_path, $jpeg_quality); - - imagedestroy($img2); - - return $this->keystring; - } -} \ No newline at end of file diff --git a/library/includes/captcha/kcaptcha/fonts/antiqua.png b/library/includes/captcha/kcaptcha/fonts/antiqua.png deleted file mode 100644 index 78d93d597..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/antiqua.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/baskerville.png b/library/includes/captcha/kcaptcha/fonts/baskerville.png deleted file mode 100644 index 5a635287d..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/baskerville.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/batang.png b/library/includes/captcha/kcaptcha/fonts/batang.png deleted file mode 100644 index ba0075634..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/batang.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/bookman.png b/library/includes/captcha/kcaptcha/fonts/bookman.png deleted file mode 100644 index 1132a122a..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/bookman.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/calisto.png b/library/includes/captcha/kcaptcha/fonts/calisto.png deleted file mode 100644 index b3b0dd560..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/calisto.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/cambria.png b/library/includes/captcha/kcaptcha/fonts/cambria.png deleted file mode 100644 index 76ad92107..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/cambria.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/centaur.png b/library/includes/captcha/kcaptcha/fonts/centaur.png deleted file mode 100644 index 30a46cadd..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/centaur.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/century.png b/library/includes/captcha/kcaptcha/fonts/century.png deleted file mode 100644 index abf89d7e2..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/century.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/chaparral.png b/library/includes/captcha/kcaptcha/fonts/chaparral.png deleted file mode 100644 index 7395bacdb..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/chaparral.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/constantia.png b/library/includes/captcha/kcaptcha/fonts/constantia.png deleted file mode 100644 index d3abc6464..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/constantia.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/footlight.png b/library/includes/captcha/kcaptcha/fonts/footlight.png deleted file mode 100644 index cb2a634ec..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/footlight.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/garamond.png b/library/includes/captcha/kcaptcha/fonts/garamond.png deleted file mode 100644 index eb7222123..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/garamond.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/georgia.png b/library/includes/captcha/kcaptcha/fonts/georgia.png deleted file mode 100644 index d00bb75e4..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/georgia.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/goudy_old.png b/library/includes/captcha/kcaptcha/fonts/goudy_old.png deleted file mode 100644 index b4d236d9a..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/goudy_old.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/kozuka.png b/library/includes/captcha/kcaptcha/fonts/kozuka.png deleted file mode 100644 index ececa1104..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/kozuka.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/lucida.png b/library/includes/captcha/kcaptcha/fonts/lucida.png deleted file mode 100644 index 050732aa7..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/lucida.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/minion.png b/library/includes/captcha/kcaptcha/fonts/minion.png deleted file mode 100644 index 34384e51a..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/minion.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/palatino.png b/library/includes/captcha/kcaptcha/fonts/palatino.png deleted file mode 100644 index 3a9d37b24..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/palatino.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/perpetua.png b/library/includes/captcha/kcaptcha/fonts/perpetua.png deleted file mode 100644 index 8b4c0871a..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/perpetua.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/rockwell.png b/library/includes/captcha/kcaptcha/fonts/rockwell.png deleted file mode 100644 index da19566d1..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/rockwell.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/times.png b/library/includes/captcha/kcaptcha/fonts/times.png deleted file mode 100644 index 656e99d97..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/times.png and /dev/null differ diff --git a/library/includes/captcha/kcaptcha/fonts/warnock.png b/library/includes/captcha/kcaptcha/fonts/warnock.png deleted file mode 100644 index c114dbcb9..000000000 Binary files a/library/includes/captcha/kcaptcha/fonts/warnock.png and /dev/null differ diff --git a/library/includes/classes/.htaccess b/library/includes/classes/.htaccess deleted file mode 100644 index baa56e5a3..000000000 --- a/library/includes/classes/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -order allow,deny -deny from all \ No newline at end of file diff --git a/library/includes/classes/correct.php b/library/includes/classes/correct.php deleted file mode 100644 index 5d296fdf8..000000000 --- a/library/includes/classes/correct.php +++ /dev/null @@ -1,3107 +0,0 @@ - 'cosmo' (2 первых и последняя буква — ошибочные) - * "\x78\x70\x65н" => 'хрен' (первые 3 буквы — ошибочные) - * "вебvfcnth" => 'вебмастер' - * "webьфыеук" => 'webmaster' - * "цццюмуыеш.ru" => 'www.vesti.ru' - * "\x54.\x43.\x48\x61вка" => 'Т.С.Навка' - * - * Hints - * Типичный пример алгоритма работы для поля ввода с автодополнением: - * 1. Сделать выборку по исходному запросу; - * 2. Если есть результат, возвратить его и исходный запрос; - * 3. Иначе скорректировать исходный запрос через Text_LangCorrect; - * 4. Если исходный и скорректированный запрос совпадает, возвратить пустой результат и исходный запрос; - * 5. Иначе сделать выборку по скорректированному запросу; - * 6. Возвратить результат. Если результат не пустой, возвратить скорректированный запрос, иначе исходный. - * - * License - * Только для некоммерческого использования! - * - * @link http://code.google.com/p/php-lang-correct/ - * @license http://creativecommons.org/licenses/by-nc-sa/3.0/ - * @author Nasibullin Rinat - * @version 1.4.3 - */ -class Text_LangCorrect -{ - /** - * Флаг для исправления ошибочно набранных букв в словах, - * которые выглядят одинаково в разных раскладках клавиатуры. - * Алгоритм работает достаточно надёжно и быстро. - */ - const SIMILAR_CHARS = 1; - - /** - * Флаг для исправления ошибочно набранных слов в другой раскладке клавиатуры. - * Алгоритм может иногда ошибаться, работает в разы медленнее, чем SIMILAR_CHARS. - */ - const KEYBOARD_LAYOUT = 2; - - /** - * Флаг для добавления исправлений, если влючён флаг KEYBOARD_LAYOUT - * Синтаксис и пример: "(,.cn=>бюст)" - * ^ ^^ ^ - */ - const ADD_FIX = 4; - - #английский (all) - private $en = '[a-zA-Z]'; - - #английский (uppercase) - private $en_uc = '[A-Z]'; - - #английский + символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв (all) - private $en_sc = '[a-zA-Z\'`~<>,.:;{}\[\]"]'; - - #символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв - private $sc = '[\'`~<>,.:;{}\[\]"]'; - private $no_sc = '[^\'`~<>,.:;{}\[\]"]'; - - #русский + татарский (all) - private $tt = '[\xd0-\xd3][\x80-\xbf] - (?<=\xd0[\x90-\xbf\x81]|\xd1[\x80-\x8f\x91]|\xd2[\x96\x97\xa2\xa3\xae\xaf\xba\xbb]|\xd3[\x98\x99\xa8\xa9])'; - - #русский + татарский (uppercase) - private $tt_uc = '[\xd0\xd2\xd3][\x81-\xba] - (?<=\xd0[\x90-\xaf\x81]|\xd2[\x96\xa2\xae\xba]|\xd3[\x98\xa8])'; - - #русский + татарский (для фильтрованных текстов) (all) - private $tt_f = '[\xd0-\xd3][\x80-\xbf] - #комментируем для увеличения скорости, т.к. остальные символы отфильтрованы - #(?<=\xd0[\x90-\xbf\x81]|\xd1[\x80-\x8f\x91]|\xd2[\x96\x97\xa2\xa3\xae\xaf\xba\xbb]|\xd3[\x98\x99\xa8\xa9]) - '; - - #гласная (vowel) (lowercase) - private $vowel_lc = array( - 'tt' => '\xd0[\xb0\xb5\xb8\xbe]|\xd1[\x83\x8b\x8d\x8e\x8f\x91] #аеиоуыэюяё (гласные, 10 шт.) - #| \xd0[\x90\x95\x98\x9e\xa3\xab\xad\xae\xaf\x81] #АЕИОУЫЭЮЯЁ (гласные, 10 шт.) - ', - 'en' => '[aeiouy]', #латинских 6 шт. - ); - - #согласная (consonant) + графические знаки для русского языка (ъ, ь) (lowercase) - private $consonant_lc = array( - 'tt' => '\xd0[\xb1-\xb4\xb6\xb7\xb9\xba-\xbd\xbf]|\xd1[\x80\x81\x82\x84-\x89\x8a\x8c] #бвгджзйклмнпрстфхцчшщ ъь (согласные, 21+2 шт.) - #| \xd0[\x91-\x94\x96\x97\x99\x9a-\x9d\x9f-\xa2\xa4-\xa9\xaa\xac] #БВГДЖЗЙКЛМНПРСТФХЦЧШЩ ЪЬ (согласные, 21+2 шт.) - ', - 'en' => '[bcdfghjklmnpqrstvwxz]', #латинских 20 шт. - ); - - private $words_exceptions = array( - 'tt' => array( - 'трлн' => null, - 'ющенко' => null, - 'мебельград' => null, - 'дэнис' => null, - ), - 'en' => array( - 'heuer' => null, - ), - ); - - #русские буквы, похожие на англ. (uppercase) - private $ru_similar_uc = "\xd0[\x90\x92\x95\x9a\x9c\x9d\x9e\xa0-\xa3\xa5]"; - - #русские буквы, похожие на англ. (all) - private $ru_similar = "\xd0[\x90\x92\x95\x9a\x9c\x9d\x9e\xa0-\xa3\xa5\xb0\xb5\xbe]|\xd1[\x80\x81\x83\x85]"; - - #англ. буквы, похожие на русские (uppercase) - private $en_similar_uc = '[ABEKMHOPCTYX]'; - - /* - #$tt_fake = '\xd0[\xb0\xb5\xbe\x90\x92\x95\x9a\x9c\x9d\x9e\xa0\xa1\xa2\xa3\xa5]|\xd1[\x80\x81\x83\x85]'; - $tt_fake = '[\xd0\xd1][\x80-\xbe] - (?<=\xd0[\xb0\xb5\xbe\x90\x92\x95\x9a\x9c\x9d\x9e\xa0\xa1\xa2\xa3\xa5]|\xd1[\x80\x81\x83\x85])'; - $en_fake = '[aeopcyxABEKMHOPCTYX]'; - */ - - #уникальные русские буквы - /* - CASE_UPPER, case_lower - "\xd0\x81", "\xd1\x91", #Ё ё - "\xd0\x91", "\xd0\xb1", #Б б - "\xd0\x92", "\xd0\xb2", #В в - "\xd0\x93", "\xd0\xb3", #Г г - "\xd0\x94", "\xd0\xb4", #Д д - "\xd0\x96", "\xd0\xb6", #Ж ж - "\xd0\x97", "\xd0\xb7", #З з - "\xd0\x98", "\xd0\xb8", #И и - "\xd0\x99", "\xd0\xb9", #Й й - "\xd0\xba", #К к - "\xd0\x9b", "\xd0\xbb", #Л л - "\xd0\xbd", #Н н - "\xd0\x9f", "\xd0\xbf", #П п - "\xd1\x82", #Т т - "\xd0\xa4", "\xd1\x84", #Ф ф - "\xd0\xa6", "\xd1\x86", #Ц ц - "\xd0\xa7", "\xd1\x87", #Ч ч - "\xd0\xa8", "\xd1\x88", #Ш ш - "\xd0\xa9", "\xd1\x89", #Щ щ - "\xd0\xaa", "\xd1\x8a", #Ъ ъ - "\xd0\xab", "\xd1\x8b", #Ы ы - "\xd0\xac", "\xd1\x8c", #Ь ь - "\xd0\xad", "\xd1\x8d", #Э э - "\xd0\xae", "\xd1\x8e", #Ю ю - "\xd0\xaf", "\xd1\x8f", #Я я - */ - #$tt_uniq = "\xd0[\xb1-\xb4\xb6-\xbb\xbd\xbf\x81\x91-\x94\x96-\x99\x9b\x9f\xa4\xa6-\xaf]|\xd1[\x82\x84\x86-\x8f\x91]"; - private $tt_uniq = "[\xd0\xd1][\x82-\xbf] - (?<=\xd0[\xb1-\xb4\xb6-\xbb\xbd\xbf\x81\x91-\x94\x96-\x99\x9b\x9f\xa4\xa6-\xaf]|\xd1[\x82\x84\x86-\x8f\x91])"; - - #уникальные латинские буквы - /* - CASE_UPPER, case_lower - "\x42", "\x62", #B b - "\x44", "\x64", #D d - "\x46", "\x66", #F f - "\x68", #H h - "\x49", "\x69", #I i - "\x4a", "\x6a", #J j - "\x6b", #K k - "\x4c", "\x6c", #L l - "\x6d", #M m - "\x4e", "\x6e", #N n - "\x51", "\x71", #Q q - "\x52", "\x72", #R r - "\x53", "\x73", #S s - "\x74", #T t - "\x55", "\x75", #U u - "\x56", "\x76", #V v - "\x57", "\x77", #W w - "\x5a", "\x7a", #Z z - */ - private $en_uniq = "[\x42\x44\x46\x49\x4a\x4c\x4e\x51\x52\x53\x55\x57\x56\x5a\x62\x64\x66\x68\x69\x6a-\x6e\x71-\x77\x7a]"; - - private $table_flip; #array - private $words; #corrected words - private $en_correct; #string - private $tt_correct; #string - private $mode; #bool - - private $is_flip = false; - private $method = 0; - - private $table = array( - #метод 0: таблица исправления ошибочно набранных букв, которые выглядят одинаково (русский <--> английский) - 0 => array( - #lowercase #UPPERCASE - "\xd0\xb0" => 'a', "\xd0\x90" => 'A', - "\xd0\x92" => 'B', - "\xd0\xb5" => 'e', "\xd0\x95" => 'E', - "\xd0\x9a" => 'K', - "\xd0\x9c" => 'M', - "\xd0\x9d" => 'H', - "\xd0\xbe" => 'o', "\xd0\x9e" => 'O', - "\xd1\x80" => 'p', "\xd0\xa0" => 'P', - "\xd1\x81" => 'c', "\xd0\xa1" => 'C', - "\xd0\xa2" => 'T', - "\xd1\x83" => 'y', "\xd0\xa3" => 'Y', - "\xd1\x85" => 'x', "\xd0\xa5" => 'X', - ), - #метод 1: таблица исправления ошибочно набранных букв в другой раскладке клавиатуры (русский <--> английский) - 1 => array( - #CASE_UPPER #case_lower - "\xd0\x81" => '~', "\xd1\x91" => '`', #Ё ё - "\xd0\x90" => 'F', "\xd0\xb0" => 'f', #А а - "\xd0\x91" => '<', "\xd0\xb1" => ',', #Б б - "\xd0\x92" => 'D', "\xd0\xb2" => 'd', #В в - "\xd0\x93" => 'U', "\xd0\xb3" => 'u', #Г г - "\xd0\x94" => 'L', "\xd0\xb4" => 'l', #Д д - "\xd0\x95" => 'T', "\xd0\xb5" => 't', #Е е - "\xd0\x96" => ':', "\xd0\xb6" => ';', #Ж ж - "\xd0\x97" => 'P', "\xd0\xb7" => 'p', #З з - "\xd0\x98" => 'B', "\xd0\xb8" => 'b', #И и - "\xd0\x99" => 'Q', "\xd0\xb9" => 'q', #Й й - "\xd0\x9a" => 'R', "\xd0\xba" => 'r', #К к - "\xd0\x9b" => 'K', "\xd0\xbb" => 'k', #Л л - "\xd0\x9c" => 'V', "\xd0\xbc" => 'v', #М м - "\xd0\x9d" => 'Y', "\xd0\xbd" => 'y', #Н н - "\xd0\x9e" => 'J', "\xd0\xbe" => 'j', #О о - "\xd0\x9f" => 'G', "\xd0\xbf" => 'g', #П п - #CASE_UPPER #case_lower - "\xd0\xa0" => 'H', "\xd1\x80" => 'h', #Р р - "\xd0\xa1" => 'C', "\xd1\x81" => 'c', #С с - "\xd0\xa2" => 'N', "\xd1\x82" => 'n', #Т т - "\xd0\xa3" => 'E', "\xd1\x83" => 'e', #У у - "\xd0\xa4" => 'A', "\xd1\x84" => 'a', #Ф ф - "\xd0\xa5" => '{', "\xd1\x85" => '[', #Х х - "\xd0\xa6" => 'W', "\xd1\x86" => 'w', #Ц ц - "\xd0\xa7" => 'X', "\xd1\x87" => 'x', #Ч ч - "\xd0\xa8" => 'I', "\xd1\x88" => 'i', #Ш ш - "\xd0\xa9" => 'O', "\xd1\x89" => 'o', #Щ щ - "\xd0\xaa" => '}', "\xd1\x8a" => ']', #Ъ ъ - "\xd0\xab" => 'S', "\xd1\x8b" => 's', #Ы ы - "\xd0\xac" => 'M', "\xd1\x8c" => 'm', #Ь ь - "\xd0\xad" => '"', "\xd1\x8d" => "'", #Э э - "\xd0\xae" => '>', "\xd1\x8e" => '.', #Ю ю - "\xd0\xaf" => 'Z', "\xd1\x8f" => 'z', #Я я - ), - ); - - #несуществующие N-граммы для гласных букв - private $vowels3_lc = array( - 'en' => array( - 'aea' => 0, - 'aei' => 1, - 'aeo' => 2, - 'aeu' => 3, - 'aia' => 4, - 'aie' => 5, - 'aii' => 6, - 'aoi' => 7, - 'aou' => 8, - 'aue' => 9, - 'aya' => 10, - 'aye' => 11, - 'ayi' => 12, - 'ayo' => 13, - 'ayu' => 14, - 'eae' => 15, - 'eau' => 16, - 'eea' => 17, - 'eei' => 18, - 'eeu' => 19, - 'eia' => 20, - 'eiu' => 21, - 'eoi' => 22, - 'eou' => 23, - 'eya' => 24, - 'eye' => 25, - 'eyi' => 26, - 'eyo' => 27, - 'iae' => 28, - 'iai' => 29, - 'iao' => 30, - 'iau' => 31, - 'iei' => 32, - 'ieu' => 33, - 'ioa' => 34, - 'ioe' => 35, - 'iou' => 36, - 'iya' => 37, - 'oae' => 38, - 'oea' => 39, - 'oei' => 40, - 'oeo' => 41, - 'oeu' => 42, - 'oey' => 43, - 'oia' => 44, - 'oie' => 45, - 'ooe' => 46, - 'ooi' => 47, - 'oou' => 48, - 'oua' => 49, - 'oue' => 50, - 'oui' => 51, - 'oya' => 52, - 'oye' => 53, - 'oyi' => 54, - 'oyo' => 55, - 'uae' => 56, - 'uai' => 57, - 'uay' => 58, - 'uea' => 59, - 'uee' => 60, - 'uei' => 61, - 'ueo' => 62, - 'ueu' => 63, - 'uey' => 64, - 'uia' => 65, - 'uie' => 66, - 'uio' => 67, - 'uiu' => 68, - 'uoa' => 69, - 'uoi' => 70, - 'uou' => 71, - 'uoy' => 72, - 'uya' => 73, - 'uye' => 74, - 'uyi' => 75, - 'yae' => 76, - 'yao' => 77, - 'yau' => 78, - 'yea' => 79, - 'yei' => 80, - 'yeo' => 81, - 'yey' => 82, - 'yie' => 83, - 'yoi' => 84, - 'you' => 85, - 'yoy' => 86, - 'yua' => 87, - ), - 'tt' => array( - 'аау' => 0, - 'аео' => 1, - 'аеу' => 2, - 'аиа' => 3, - 'аио' => 4, - 'аиу' => 5, - 'аои' => 6, - 'ауэ' => 7, - 'аяя' => 8, - 'еаэ' => 9, - 'еее' => 10, - 'еео' => 11, - 'еоа' => 12, - 'еои' => 13, - 'еоо' => 14, - 'еую' => 15, - 'еуя' => 16, - 'еуё' => 17, - 'иау' => 18, - 'иео' => 19, - 'иие' => 20, - 'иоа' => 21, - 'иои' => 22, - 'иоу' => 23, - 'иоэ' => 24, - 'ияе' => 25, - 'ияи' => 26, - 'ияю' => 27, - 'оаэ' => 28, - 'оео' => 29, - 'оею' => 30, - 'оие' => 31, - 'оуе' => 32, - 'оуя' => 33, - 'оюе' => 34, - 'оюю' => 35, - 'ояе' => 36, - 'уео' => 37, - 'уюю' => 38, - ), - ); - - #несуществующие N-граммы для согласных букв - private $consonants4_lc = array( - 'en' => array( - 'bldg' => 0, - 'blvd' => 1, - 'bscr' => 2, - 'bstr' => 3, - 'cbcm' => 4, - 'cbft' => 5, - 'chfr' => 6, - 'chmn' => 7, - 'chsc' => 8, - 'chsh' => 9, - 'chst' => 10, - 'chth' => 11, - 'chts' => 12, - 'ckbr' => 13, - 'ckch' => 14, - 'ckcl' => 15, - 'ckdr' => 16, - 'ckgr' => 17, - 'cksc' => 18, - 'cksf' => 19, - 'cksh' => 20, - 'cksk' => 21, - 'cksl' => 22, - 'cksm' => 23, - 'cksn' => 24, - 'cksp' => 25, - 'ckst' => 26, - 'cksw' => 27, - 'ckth' => 28, - 'cktr' => 29, - 'ckwh' => 30, - 'cmps' => 31, - 'dspr' => 32, - 'dstr' => 33, - 'dthw' => 34, - 'ffsc' => 35, - 'ffsh' => 36, - 'ffsp' => 37, - 'fthl' => 38, - 'ftsm' => 39, - 'ftsp' => 40, - 'gdns' => 41, - 'ghbr' => 42, - 'ghfl' => 43, - 'ghsh' => 44, - 'ghtb' => 45, - 'ghtc' => 46, - 'ghtf' => 47, - 'ghth' => 48, - 'ghtj' => 49, - 'ghtl' => 50, - 'ghtm' => 51, - 'ghtn' => 52, - 'ghtr' => 53, - 'ghts' => 54, - 'ghtw' => 55, - 'hdbk' => 56, - 'hnst' => 57, - 'jctn' => 58, - 'khsh' => 59, - 'khst' => 60, - 'lchr' => 61, - 'ldpr' => 62, - 'ldsh' => 63, - 'ldsm' => 64, - 'ldsp' => 65, - 'ldst' => 66, - 'lfsk' => 67, - 'lfth' => 68, - 'lgth' => 69, - 'llfl' => 70, - 'llfr' => 71, - 'llph' => 72, - 'llpl' => 73, - 'llsh' => 74, - 'llsp' => 75, - 'llst' => 76, - 'lltr' => 77, - 'llwr' => 78, - 'lmcr' => 79, - 'lmsm' => 80, - 'lnrk' => 81, - 'lnsh' => 82, - 'lptr' => 83, - 'lsgr' => 84, - 'lshm' => 85, - 'lshw' => 86, - 'lstr' => 87, - 'lthf' => 88, - 'ltsf' => 89, - 'ltsh' => 90, - 'ltst' => 91, - 'mbsc' => 92, - 'mbsh' => 93, - 'mbsk' => 94, - 'mbst' => 95, - 'mddx' => 96, - 'mdnt' => 97, - 'mpbl' => 98, - 'mpgr' => 99, - 'mphl' => 100, - 'mphr' => 101, - 'mpsh' => 102, - 'mpst' => 103, - 'mptl' => 104, - 'mptn' => 105, - 'mptr' => 106, - 'mpts' => 107, - 'mscr' => 108, - 'mstr' => 109, - 'nchb' => 110, - 'nchl' => 111, - 'nchm' => 112, - 'nchn' => 113, - 'nchp' => 114, - 'nchr' => 115, - 'nchw' => 116, - 'nctl' => 117, - 'nctn' => 118, - 'ndbk' => 119, - 'ndbr' => 120, - 'ndch' => 121, - 'ndfl' => 122, - 'ndgl' => 123, - 'ndgr' => 124, - 'ndsc' => 125, - 'ndsh' => 126, - 'ndsl' => 127, - 'ndsm' => 128, - 'ndsp' => 129, - 'ndst' => 130, - 'ndsw' => 131, - 'ndth' => 132, - 'ndwr' => 133, - 'ngcr' => 134, - 'ngsg' => 135, - 'ngsh' => 136, - 'ngsm' => 137, - 'ngsp' => 138, - 'ngst' => 139, - 'ngth' => 140, - 'ngtz' => 141, - 'nksg' => 142, - 'nksh' => 143, - 'nksm' => 144, - 'nkst' => 145, - 'nsch' => 146, - 'nscr' => 147, - 'nsgr' => 148, - 'nshr' => 149, - 'nskr' => 150, - 'nspl' => 151, - 'nspr' => 152, - 'nssh' => 153, - 'nstr' => 154, - 'ntbr' => 155, - 'nthl' => 156, - 'nthr' => 157, - 'nths' => 158, - 'ntsh' => 159, - 'ntsm' => 160, - 'phth' => 161, - 'pstr' => 162, - 'pthr' => 163, - 'pths' => 164, - 'ptwr' => 165, - 'rbst' => 166, - 'rchb' => 167, - 'rchd' => 168, - 'rchl' => 169, - 'rchm' => 170, - 'rchn' => 171, - 'rchp' => 172, - 'rchw' => 173, - 'rdsh' => 174, - 'rdsm' => 175, - 'rdst' => 176, - 'rghs' => 177, - 'rkpl' => 178, - 'rksc' => 179, - 'rksh' => 180, - 'rksk' => 181, - 'rksm' => 182, - 'rksp' => 183, - 'rkst' => 184, - 'rldl' => 185, - 'rldw' => 186, - 'rlfr' => 187, - 'rmch' => 188, - 'rmst' => 189, - 'rmth' => 190, - 'rnbl' => 191, - 'rndl' => 192, - 'rnsk' => 193, - 'rnsp' => 194, - 'rnst' => 195, - 'rsch' => 196, - 'rscr' => 197, - 'rshl' => 198, - 'rshn' => 199, - 'rspr' => 200, - 'rstl' => 201, - 'rstr' => 202, - 'rsts' => 203, - 'rstw' => 204, - 'rtbr' => 205, - 'rtch' => 206, - 'rtcr' => 207, - 'rthb' => 208, - 'rthc' => 209, - 'rthd' => 210, - 'rthf' => 211, - 'rthl' => 212, - 'rthm' => 213, - 'rthq' => 214, - 'rthr' => 215, - 'rths' => 216, - 'rthw' => 217, - 'rtsh' => 218, - 'rtsm' => 219, - 'rtsp' => 220, - 'rtsw' => 221, - 'schl' => 222, - 'schm' => 223, - 'schn' => 224, - 'schw' => 225, - 'scrp' => 226, - 'sgmt' => 227, - 'shcl' => 228, - 'shkh' => 229, - 'shpr' => 230, - 'shpt' => 231, - 'shst' => 232, - 'shtr' => 233, - 'shwh' => 234, - 'smth' => 235, - 'ssrs' => 236, - 'ssst' => 237, - 'sstd' => 238, - 'sstr' => 239, - 'stcr' => 240, - 'sthm' => 241, - 'stpl' => 242, - 'stpr' => 243, - 'stsc' => 244, - 'stwr' => 245, - 'tblt' => 246, - 'tchb' => 247, - 'tchc' => 248, - 'tchd' => 249, - 'tchf' => 250, - 'tchl' => 251, - 'tchm' => 252, - 'tchp' => 253, - 'tchw' => 254, - 'thdr' => 255, - 'thsh' => 256, - 'thsk' => 257, - 'thsp' => 258, - 'thst' => 259, - 'tsch' => 260, - 'tspr' => 261, - 'tstr' => 262, - 'tthr' => 263, - 'ttsb' => 264, - 'tzkr' => 265, - 'whsl' => 266, - 'wnbr' => 267, - 'wnpl' => 268, - 'wnsf' => 269, - 'wnsh' => 270, - 'wnsm' => 271, - 'wnsp' => 272, - 'wnst' => 273, - 'wnsw' => 274, - 'wnth' => 275, - 'wntr' => 276, - 'wrnt' => 277, - 'wsfl' => 278, - 'wspr' => 279, - 'wstr' => 280, - 'xthl' => 281, - ), - 'tt' => array( - 'блзд' => 0, - 'бльд' => 1, - 'брьс' => 2, - 'бств' => 3, - 'бстр' => 4, - 'взбл' => 5, - 'взбр' => 6, - 'взгл' => 7, - 'взгр' => 8, - 'вздв' => 9, - 'вздр' => 10, - 'врвг' => 11, - 'врск' => 12, - 'вскл' => 13, - 'вскр' => 14, - 'вспл' => 15, - 'вспр' => 16, - 'вств' => 17, - 'встр' => 18, - 'всхл' => 19, - 'всхр' => 20, - 'втск' => 21, - 'вхск' => 22, - 'грск' => 23, - 'гств' => 24, - 'гтст' => 25, - 'гшпр' => 26, - 'двзд' => 27, - 'джск' => 28, - 'дрст' => 29, - 'дскр' => 30, - 'дств' => 31, - 'дстр' => 32, - 'дтск' => 33, - 'жств' => 34, - 'звзд' => 35, - 'знст' => 36, - 'зтьс' => 37, - 'йздр' => 38, - 'йкбр' => 39, - 'йльн' => 40, - 'йншт' => 41, - 'йпфр' => 42, - 'йств' => 43, - 'йстр' => 44, - 'йтск' => 45, - 'йфст' => 46, - 'йхсв' => 47, - 'йхск' => 48, - 'йхср' => 49, - 'йхст' => 50, - 'кскл' => 51, - 'кскр' => 52, - 'кспл' => 53, - 'кспр' => 54, - 'кств' => 55, - 'кстн' => 56, - 'кстр' => 57, - 'лвст' => 58, - 'лжск' => 59, - 'лльн' => 60, - 'лльс' => 61, - 'лстр' => 62, - 'лсть' => 63, - 'льгв' => 64, - 'льдж' => 65, - 'льдк' => 66, - 'льдм' => 67, - 'льдс' => 68, - 'льдф' => 69, - 'льдц' => 70, - 'льдш' => 71, - 'льдъ' => 72, - 'льдь' => 73, - 'льзк' => 74, - 'льзн' => 75, - 'льзь' => 76, - 'лькл' => 77, - 'лькн' => 78, - 'льпн' => 79, - 'льпт' => 80, - 'льск' => 81, - 'льсн' => 82, - 'льст' => 83, - 'льтк' => 84, - 'льтм' => 85, - 'льтн' => 86, - 'льтп' => 87, - 'льтр' => 88, - 'льтс' => 89, - 'льтт' => 90, - 'льтф' => 91, - 'льфр' => 92, - 'льцг' => 93, - 'льчс' => 94, - 'льшб' => 95, - 'льшк' => 96, - 'льшн' => 97, - 'льшп' => 98, - 'льшф' => 99, - 'льшь' => 100, - 'мбль' => 101, - 'мбрс' => 102, - 'мвзв' => 103, - 'мздр' => 104, - 'мств' => 105, - 'мтск' => 106, - 'нгль' => 107, - 'нгст' => 108, - 'ндгр' => 109, - 'ндск' => 110, - 'ндсп' => 111, - 'ндшп' => 112, - 'ндшт' => 113, - 'нкск' => 114, - 'нктн' => 115, - 'нктс' => 116, - 'нсгр' => 117, - 'нскм' => 118, - 'нскр' => 119, - 'нспл' => 120, - 'нств' => 121, - 'нстк' => 122, - 'нстр' => 123, - 'нтгл' => 124, - 'нтль' => 125, - 'нтрб' => 126, - 'нтрв' => 127, - 'нтрг' => 128, - 'нтрд' => 129, - 'нтрм' => 130, - 'нтрн' => 131, - 'нтрп' => 132, - 'нтрр' => 133, - 'нтрф' => 134, - 'нтск' => 135, - 'нтст' => 136, - 'нфск' => 137, - 'нцкл' => 138, - 'нцпл' => 139, - 'нькн' => 140, - 'ньск' => 141, - 'ньчж' => 142, - 'псск' => 143, - 'пств' => 144, - 'птск' => 145, - 'рбск' => 146, - 'ргпр' => 147, - 'ргск' => 148, - 'ргфл' => 149, - 'рдск' => 150, - 'рдсм' => 151, - 'рдст' => 152, - 'рздр' => 153, - 'рзть' => 154, - 'ркгр' => 155, - 'ркск' => 156, - 'рктн' => 157, - 'рльс' => 158, - 'рмск' => 159, - 'рмтр' => 160, - 'рнск' => 161, - 'рпск' => 162, - 'рсдр' => 163, - 'рсск' => 164, - 'рств' => 165, - 'рстк' => 166, - 'рстн' => 167, - 'рстр' => 168, - 'рстс' => 169, - 'рсть' => 170, - 'ртвл' => 171, - 'ртвр' => 172, - 'ртгр' => 173, - 'рткр' => 174, - 'ртпл' => 175, - 'ртпр' => 176, - 'ртск' => 177, - 'ртсм' => 178, - 'ртшк' => 179, - 'ртьф' => 180, - 'рхзв' => 181, - 'рхпл' => 182, - 'рхпр' => 183, - 'рхсв' => 184, - 'рхск' => 185, - 'рхсм' => 186, - 'рхср' => 187, - 'рхтв' => 188, - 'рхшт' => 189, - 'рщвл' => 190, - 'рьмл' => 191, - 'скск' => 192, - 'спрь' => 193, - 'сспр' => 194, - 'ссср' => 195, - 'сств' => 196, - 'сстр' => 197, - 'ссшп' => 198, - 'ствл' => 199, - 'стрс' => 200, - 'стрш' => 201, - 'стск' => 202, - 'стьб' => 203, - 'стьд' => 204, - 'стьс' => 205, - 'ськн' => 206, - 'сьмн' => 207, - 'тмст' => 208, - 'тпрр' => 209, - 'трст' => 210, - 'тскр' => 211, - 'тств' => 212, - 'тстр' => 213, - 'ттль' => 214, - 'ттск' => 215, - 'тхск' => 216, - 'фств' => 217, - 'фстр' => 218, - 'хств' => 219, - 'хстр' => 220, - 'хткл' => 221, - 'хтск' => 222, - 'хтсм' => 223, - 'цстр' => 224, - ), - ); - - #несуществующие биграммы в начале и конце слов - private $bigrams = array( - #ru - ' ёё' => 0, - ' ёа' => 0, - ' ёб' => 0, - ' ёв' => 0, - ' ёг' => 0, - ' ёд' => 0, - ' ёе' => 0, - ' ёз' => 0, - ' ёи' => 0, - ' ёй' => 0, - ' ён' => 0, - ' ёо' => 0, - ' ёп' => 0, - ' ёс' => 0, - ' ёт' => 0, - ' ёу' => 0, - ' ёф' => 0, - ' ёц' => 0, - ' ёч' => 0, - ' ёщ' => 0, - ' ёъ' => 0, - ' ёы' => 0, - ' ёь' => 0, - ' ёэ' => 0, - ' ёю' => 0, - ' ёя' => 0, - ' аё' => 0, - ' аа' => 0, - ' ае' => 0, - ' ач' => 0, - ' аъ' => 0, - ' аы' => 0, - ' аь' => 0, - ' аю' => 0, - ' ая' => 0, - ' бб' => 0, - ' бв' => 0, - ' бг' => 0, - ' бж' => 0, - ' бй' => 0, - ' бк' => 0, - ' бм' => 0, - ' бн' => 0, - ' бп' => 0, - ' бс' => 0, - ' бт' => 0, - ' бф' => 0, - ' бх' => 0, - ' бц' => 0, - ' бч' => 0, - ' бш' => 0, - ' бщ' => 0, - ' бъ' => 0, - ' вй' => 0, - ' вф' => 0, - ' вщ' => 0, - ' вэ' => 0, - ' вю' => 0, - ' гё' => 0, - ' гб' => 0, - ' гз' => 0, - ' гй' => 0, - ' гк' => 0, - ' гп' => 0, - ' гс' => 0, - ' гт' => 0, - ' гф' => 0, - ' гх' => 0, - ' гц' => 0, - ' гч' => 0, - ' гш' => 0, - ' гщ' => 0, - ' гъ' => 0, - ' гь' => 0, - ' гэ' => 0, - ' дб' => 0, - ' дг' => 0, - ' дд' => 0, - ' дй' => 0, - ' дк' => 0, - ' дп' => 0, - ' дс' => 0, - ' дт' => 0, - ' дф' => 0, - ' дх' => 0, - ' дц' => 0, - ' дч' => 0, - ' дш' => 0, - ' дъ' => 0, - ' дэ' => 0, - ' еа' => 0, - ' еб' => 0, - ' еи' => 0, - ' ео' => 0, - ' ет' => 0, - ' еу' => 0, - ' ец' => 0, - #' еш' => 0, - ' еъ' => 0, - ' еы' => 0, - ' еь' => 0, - ' еэ' => 0, - ' ея' => 0, - ' жз' => 0, - ' жй' => 0, - ' жк' => 0, - ' жл' => 0, - ' жп' => 0, - ' жс' => 0, - ' жт' => 0, - ' жф' => 0, - ' жх' => 0, - ' жц' => 0, - ' жч' => 0, - ' жш' => 0, - ' жщ' => 0, - ' жъ' => 0, - ' жы' => 0, - ' жь' => 0, - ' жэ' => 0, - #' жю' => 0, - ' жя' => 0, - ' зб' => 0, - ' зж' => 0, - ' зз' => 0, - ' зй' => 0, - ' зк' => 0, - ' зп' => 0, - ' зс' => 0, - ' зт' => 0, - ' зф' => 0, - ' зх' => 0, - ' зц' => 0, - ' зч' => 0, - ' зш' => 0, - ' зщ' => 0, - ' зъ' => 0, - ' зь' => 0, - ' зэ' => 0, - ' иё' => 0, - ' иа' => 0, - ' иф' => 0, - ' иц' => 0, - ' иъ' => 0, - ' иы' => 0, - ' иь' => 0, - ' иэ' => 0, - ' ия' => 0, - ' йё' => 0, - ' йа' => 0, - ' йб' => 0, - ' йв' => 0, - ' йг' => 0, - ' йд' => 0, - ' йж' => 0, - ' йз' => 0, - ' йи' => 0, - ' йй' => 0, - ' йк' => 0, - ' йл' => 0, - ' йм' => 0, - ' йн' => 0, - ' йп' => 0, - ' йр' => 0, - ' йс' => 0, - ' йт' => 0, - ' йу' => 0, - ' йф' => 0, - ' йх' => 0, - ' йц' => 0, - ' йч' => 0, - ' йш' => 0, - ' йщ' => 0, - ' йъ' => 0, - ' йы' => 0, - ' йь' => 0, - ' йэ' => 0, - ' йю' => 0, - ' йя' => 0, - ' кё' => 0, - ' кб' => 0, - ' кд' => 0, - ' кж' => 0, - ' кй' => 0, - ' кк' => 0, - ' кф' => 0, - ' кц' => 0, - ' кч' => 0, - ' кщ' => 0, - ' къ' => 0, - ' кя' => 0, - ' лв' => 0, - ' лд' => 0, - ' лз' => 0, - ' лй' => 0, - ' лк' => 0, - ' лл' => 0, - ' лм' => 0, - ' лн' => 0, - ' лп' => 0, - ' лр' => 0, - ' лс' => 0, - ' лт' => 0, - ' лф' => 0, - ' лх' => 0, - ' лц' => 0, - ' лч' => 0, - ' лш' => 0, - ' лщ' => 0, - ' лъ' => 0, - ' лэ' => 0, - ' мб' => 0, - ' мв' => 0, - ' мд' => 0, - ' мж' => 0, - ' мй' => 0, - ' мк' => 0, - ' мп' => 0, - ' мт' => 0, - ' мф' => 0, - ' мц' => 0, - ' мъ' => 0, - ' мь' => 0, - ' нб' => 0, - ' нв' => 0, - ' нг' => 0, - ' нд' => 0, - ' нж' => 0, - ' нз' => 0, - ' нй' => 0, - ' нк' => 0, - ' нл' => 0, - ' нм' => 0, - ' нн' => 0, - ' нп' => 0, - ' нс' => 0, - ' нт' => 0, - ' нф' => 0, - ' нх' => 0, - ' нц' => 0, - ' нч' => 0, - ' нш' => 0, - ' нщ' => 0, - ' нъ' => 0, - ' оё' => 0, - ' ои' => 0, - ' оу' => 0, - ' оъ' => 0, - ' оы' => 0, - ' оь' => 0, - ' оэ' => 0, - ' оя' => 0, - ' пб' => 0, - ' пв' => 0, - ' пг' => 0, - ' пд' => 0, - ' пж' => 0, - ' пз' => 0, - ' пй' => 0, - ' пк' => 0, - ' пм' => 0, - ' пп' => 0, - ' пц' => 0, - ' пщ' => 0, - ' пъ' => 0, - ' рб' => 0, - ' рг' => 0, - ' рз' => 0, - ' рй' => 0, - ' рк' => 0, - ' рл' => 0, - ' рм' => 0, - ' рн' => 0, - ' рп' => 0, - ' рр' => 0, - ' рф' => 0, - ' рх' => 0, - ' рч' => 0, - ' рш' => 0, - ' рщ' => 0, - ' ръ' => 0, - ' сй' => 0, - ' сщ' => 0, - ' тб' => 0, - ' тг' => 0, - ' тд' => 0, - ' тж' => 0, - ' тз' => 0, - ' тй' => 0, - ' тн' => 0, - ' тт' => 0, - ' тх' => 0, - ' тц' => 0, - ' тч' => 0, - ' тш' => 0, - ' тъ' => 0, - ' уу' => 0, - ' уъ' => 0, - ' уы' => 0, - ' уь' => 0, - ' фб' => 0, - ' фв' => 0, - ' фг' => 0, - ' фд' => 0, - ' фж' => 0, - ' фз' => 0, - ' фй' => 0, - ' фк' => 0, - ' фм' => 0, - ' фн' => 0, - ' фп' => 0, - ' фс' => 0, - ' фх' => 0, - ' фц' => 0, - ' фч' => 0, - ' фш' => 0, - ' фщ' => 0, - ' фъ' => 0, - ' фэ' => 0, - ' фя' => 0, - ' хё' => 0, - ' хб' => 0, - ' хг' => 0, - ' хд' => 0, - ' хж' => 0, - ' хз' => 0, - ' хй' => 0, - ' хк' => 0, - ' хп' => 0, - ' хс' => 0, - ' хт' => 0, - ' хф' => 0, - ' хц' => 0, - ' хч' => 0, - ' хш' => 0, - ' хщ' => 0, - ' хъ' => 0, - ' хы' => 0, - ' хь' => 0, - #' хэ' => 0, - ' хю' => 0, - ' хя' => 0, - ' цё' => 0, - ' цб' => 0, - ' цг' => 0, - ' цд' => 0, - ' цж' => 0, - ' цй' => 0, - ' цл' => 0, - ' цм' => 0, - ' цн' => 0, - ' цп' => 0, - ' цр' => 0, - ' цс' => 0, - ' цт' => 0, - ' цф' => 0, - ' цх' => 0, - ' цц' => 0, - ' цч' => 0, - ' цш' => 0, - ' цщ' => 0, - ' цъ' => 0, - ' ць' => 0, - ' цэ' => 0, - ' цю' => 0, - ' ця' => 0, - ' чб' => 0, - ' чг' => 0, - ' чд' => 0, - ' чж' => 0, - ' чз' => 0, - ' чй' => 0, - ' чн' => 0, - ' чп' => 0, - ' чс' => 0, - ' чф' => 0, - ' чц' => 0, - ' чч' => 0, - ' чщ' => 0, - ' чъ' => 0, - ' чы' => 0, - ' чэ' => 0, - ' чю' => 0, - ' чя' => 0, - ' шб' => 0, - ' шг' => 0, - ' шд' => 0, - ' шж' => 0, - ' шз' => 0, - ' шй' => 0, - ' шс' => 0, - ' шф' => 0, - ' шц' => 0, - ' шч' => 0, - ' шщ' => 0, - ' шъ' => 0, - ' шы' => 0, - ' шэ' => 0, - ' шю' => 0, - ' шя' => 0, - ' щб' => 0, - ' щв' => 0, - ' щг' => 0, - ' щд' => 0, - ' щж' => 0, - ' щз' => 0, - ' щй' => 0, - ' щк' => 0, - ' щл' => 0, - ' щм' => 0, - ' щн' => 0, - ' що' => 0, - ' щп' => 0, - ' щр' => 0, - ' щс' => 0, - ' щт' => 0, - ' щф' => 0, - ' щх' => 0, - ' щц' => 0, - ' щч' => 0, - ' щш' => 0, - ' щщ' => 0, - ' щъ' => 0, - ' щы' => 0, - ' щь' => 0, - ' щэ' => 0, - ' щю' => 0, - ' щя' => 0, - ' ъё' => 0, - ' ъа' => 0, - ' ъб' => 0, - ' ъв' => 0, - ' ъг' => 0, - ' ъд' => 0, - ' ъе' => 0, - ' ъж' => 0, - ' ъз' => 0, - ' ъи' => 0, - ' ъй' => 0, - ' ък' => 0, - ' ъл' => 0, - ' ъм' => 0, - ' ън' => 0, - ' ъо' => 0, - ' ъп' => 0, - ' ър' => 0, - ' ъс' => 0, - ' ът' => 0, - ' ъу' => 0, - ' ъф' => 0, - ' ъх' => 0, - ' ъц' => 0, - ' ъч' => 0, - ' ъш' => 0, - ' ъщ' => 0, - ' ъъ' => 0, - ' ъы' => 0, - ' ъь' => 0, - ' ъэ' => 0, - ' ъю' => 0, - ' ъя' => 0, - ' ыё' => 0, - ' ыа' => 0, - ' ыб' => 0, - ' ыв' => 0, - ' ыг' => 0, - ' ыд' => 0, - ' ые' => 0, - ' ыж' => 0, - ' ыз' => 0, - ' ыи' => 0, - ' ый' => 0, - ' ык' => 0, - ' ыл' => 0, - ' ын' => 0, - ' ыо' => 0, - ' ып' => 0, - ' ыр' => 0, - ' ыс' => 0, - ' ыт' => 0, - ' ыу' => 0, - ' ыф' => 0, - ' ых' => 0, - ' ыц' => 0, - ' ыч' => 0, - ' ыш' => 0, - ' ыщ' => 0, - ' ыъ' => 0, - ' ыы' => 0, - ' ыь' => 0, - ' ыэ' => 0, - ' ыю' => 0, - ' ыя' => 0, - ' ьё' => 0, - ' ьа' => 0, - ' ьб' => 0, - ' ьв' => 0, - ' ьг' => 0, - ' ьд' => 0, - ' ье' => 0, - ' ьж' => 0, - ' ьз' => 0, - ' ьи' => 0, - ' ьй' => 0, - ' ьк' => 0, - ' ьл' => 0, - ' ьм' => 0, - ' ьн' => 0, - ' ьо' => 0, - ' ьп' => 0, - ' ьр' => 0, - ' ьс' => 0, - ' ьт' => 0, - ' ьу' => 0, - ' ьф' => 0, - ' ьх' => 0, - ' ьц' => 0, - ' ьч' => 0, - ' ьш' => 0, - ' ьщ' => 0, - ' ьъ' => 0, - ' ьы' => 0, - ' ьь' => 0, - ' ьэ' => 0, - ' ью' => 0, - ' ья' => 0, - ' эё' => 0, - ' эа' => 0, - ' эе' => 0, - ' эи' => 0, - ' эц' => 0, - ' эч' => 0, - ' эщ' => 0, - ' эъ' => 0, - ' эы' => 0, - ' эь' => 0, - ' ээ' => 0, - ' эю' => 0, - ' юё' => 0, - ' юе' => 0, - ' юи' => 0, - ' юй' => 0, - ' юо' => 0, - ' юу' => 0, - ' юц' => 0, - ' юш' => 0, - ' ющ' => 0, - ' юъ' => 0, - ' юы' => 0, - ' юь' => 0, - ' юэ' => 0, - ' юя' => 0, - ' яё' => 0, - ' яа' => 0, - ' яе' => 0, - ' яж' => 0, - ' яо' => 0, - ' яу' => 0, - ' яф' => 0, - ' яц' => 0, - ' яъ' => 0, - ' яы' => 0, - ' яь' => 0, - ' яэ' => 0, - ' яю' => 0, - ' яя' => 0, - 'ёё' => 0, - 'ёё ' => 0, - 'ёа' => 0, - 'ёа ' => 0, - 'ёг ' => 0, - 'ёе' => 0, - 'ёе ' => 0, - 'ёи' => 0, - 'ёи ' => 0, - 'ёй' => 0, - 'ёо' => 0, - 'ёо ' => 0, - 'ёу' => 0, - 'ёу ' => 0, - 'ёф' => 0, - 'ёф ' => 0, - 'ёц ' => 0, - 'ёч ' => 0, - 'ёщ ' => 0, - 'ёъ' => 0, - 'ёъ ' => 0, - 'ёы' => 0, - 'ёы ' => 0, - 'ёь' => 0, - 'ёь ' => 0, - 'ёэ' => 0, - 'ёэ ' => 0, - 'ёю' => 0, - 'ёя' => 0, - 'ёя ' => 0, - 'аё ' => 0, - 'аа ' => 0, - 'аъ' => 0, - 'аъ ' => 0, - 'аы' => 0, - 'аы ' => 0, - 'аь' => 0, - 'аь ' => 0, - 'аэ ' => 0, - 'бё ' => 0, - 'бб ' => 0, - 'бв ' => 0, - 'бг ' => 0, - 'бд ' => 0, - 'бж ' => 0, - 'бз ' => 0, - 'бй' => 0, - 'бй ' => 0, - 'бк ' => 0, - 'бм ' => 0, - 'бн ' => 0, - 'бп ' => 0, - 'бт ' => 0, - 'бф ' => 0, - 'бх ' => 0, - 'бц ' => 0, - 'бч ' => 0, - 'бш ' => 0, - 'бщ ' => 0, - 'бъ ' => 0, - 'бэ ' => 0, - 'вё ' => 0, - 'вб ' => 0, - 'вв ' => 0, - 'вд ' => 0, - 'вж' => 0, - 'вж ' => 0, - 'вз ' => 0, - 'вй' => 0, - 'вй ' => 0, - 'вл ' => 0, - 'вп ' => 0, - 'вф ' => 0, - 'вц ' => 0, - 'вч ' => 0, - 'вщ ' => 0, - 'въ' => 0, - 'въ ' => 0, - 'вэ ' => 0, - 'гё' => 0, - 'гё ' => 0, - 'гб ' => 0, - 'гг ' => 0, - 'гж' => 0, - 'гж ' => 0, - 'гз ' => 0, - 'гй' => 0, - 'гй ' => 0, - 'гк ' => 0, - 'гн ' => 0, - 'гп ' => 0, - 'гф ' => 0, - 'гх' => 0, - 'гх ' => 0, - 'гц' => 0, - 'гц ' => 0, - 'гч ' => 0, - 'гш ' => 0, - 'гщ ' => 0, - 'гъ' => 0, - 'гъ ' => 0, - 'гы ' => 0, - 'гь' => 0, - 'гь ' => 0, - 'гэ ' => 0, - 'гю' => 0, - 'гю ' => 0, - 'гя' => 0, - 'гя ' => 0, - 'дё ' => 0, - 'дб ' => 0, - 'дг ' => 0, - 'дд ' => 0, - 'дй' => 0, - 'дй ' => 0, - 'дк ' => 0, - 'дм ' => 0, - 'дн ' => 0, - 'дп ' => 0, - 'дс ' => 0, - 'дф ' => 0, - 'дх ' => 0, - 'дц ' => 0, - 'дч ' => 0, - 'дш ' => 0, - 'дщ ' => 0, - 'дъ ' => 0, - 'еа ' => 0, - 'еу ' => 0, - 'еъ' => 0, - 'еъ ' => 0, - 'еы' => 0, - 'еы ' => 0, - 'еь' => 0, - 'еь ' => 0, - 'еэ ' => 0, - 'жё ' => 0, - 'жв ' => 0, - 'жг ' => 0, - 'жж ' => 0, - 'жз ' => 0, - 'жй' => 0, - 'жй ' => 0, - 'жк ' => 0, - 'жл ' => 0, - 'жн ' => 0, - 'жп ' => 0, - 'жр ' => 0, - 'жс ' => 0, - 'жт ' => 0, - 'жф ' => 0, - 'жх ' => 0, - 'жц ' => 0, - 'жч ' => 0, - 'жш' => 0, - 'жш ' => 0, - 'жщ' => 0, - 'жщ ' => 0, - 'жъ' => 0, - 'жъ ' => 0, - 'жы ' => 0, - 'жэ ' => 0, - 'жю' => 0, - 'жю ' => 0, - 'жя' => 0, - 'жя ' => 0, - 'зё ' => 0, - 'зж ' => 0, - 'зз ' => 0, - 'зй' => 0, - 'зй ' => 0, - 'зк ' => 0, - 'зп ' => 0, - 'зр ' => 0, - 'зс ' => 0, - 'зт ' => 0, - 'зф' => 0, - 'зф ' => 0, - 'зх' => 0, - 'зх ' => 0, - 'зц ' => 0, - 'зч ' => 0, - 'зш ' => 0, - 'зщ' => 0, - 'зщ ' => 0, - 'зъ ' => 0, - 'зэ ' => 0, - 'иъ' => 0, - 'иъ ' => 0, - 'иы' => 0, - 'иы ' => 0, - 'иь' => 0, - 'иь ' => 0, - 'иэ ' => 0, - 'йё' => 0, - 'йё ' => 0, - 'йа ' => 0, - 'йв ' => 0, - 'йг ' => 0, - 'йж' => 0, - 'йж ' => 0, - 'йз ' => 0, - 'йи ' => 0, - 'йй' => 0, - 'йй ' => 0, - 'йо ' => 0, - 'йу' => 0, - 'йу ' => 0, - 'йч ' => 0, - 'йш ' => 0, - 'йщ ' => 0, - 'йъ' => 0, - 'йъ ' => 0, - 'йы' => 0, - 'йы ' => 0, - 'йь' => 0, - 'йь ' => 0, - 'йэ' => 0, - 'йэ ' => 0, - 'йю' => 0, - 'йю ' => 0, - 'йя' => 0, - 'кё ' => 0, - 'кб ' => 0, - 'кг ' => 0, - 'кд ' => 0, - 'кж ' => 0, - 'кз ' => 0, - 'кй' => 0, - 'кй ' => 0, - 'км ' => 0, - 'кн ' => 0, - 'кф ' => 0, - 'кц ' => 0, - 'кч ' => 0, - 'кш ' => 0, - 'кщ' => 0, - 'кщ ' => 0, - 'къ' => 0, - 'къ ' => 0, - 'кы ' => 0, - 'кь ' => 0, - 'кэ' => 0, - 'кэ ' => 0, - 'кя' => 0, - 'кя ' => 0, - 'лв ' => 0, - 'лж ' => 0, - 'лз ' => 0, - 'лй' => 0, - 'лй ' => 0, - 'лр ' => 0, - 'лф ' => 0, - 'лх ' => 0, - 'лц ' => 0, - 'лч ' => 0, - 'лш ' => 0, - 'лщ ' => 0, - 'лъ' => 0, - 'лъ ' => 0, - 'лэ' => 0, - 'лэ ' => 0, - 'мё ' => 0, - 'мв ' => 0, - 'мг ' => 0, - 'мд ' => 0, - 'мз ' => 0, - 'мй' => 0, - 'мк ' => 0, - 'мл ' => 0, - 'мр ' => 0, - 'мх ' => 0, - 'мц ' => 0, - 'мч ' => 0, - 'мш ' => 0, - 'мщ ' => 0, - 'мъ' => 0, - 'мъ ' => 0, - 'мэ ' => 0, - 'мю ' => 0, - 'нё ' => 0, - 'нб ' => 0, - 'нв ' => 0, - 'нй' => 0, - 'нл ' => 0, - 'нп ' => 0, - 'нщ ' => 0, - 'нъ ' => 0, - 'нэ ' => 0, - 'оъ' => 0, - 'оъ ' => 0, - 'оы' => 0, - 'оы ' => 0, - 'оь' => 0, - 'оь ' => 0, - 'пё ' => 0, - 'пб ' => 0, - 'пв' => 0, - 'пв ' => 0, - 'пг' => 0, - 'пг ' => 0, - 'пд ' => 0, - 'пж' => 0, - 'пж ' => 0, - 'пз' => 0, - 'пз ' => 0, - 'пй' => 0, - 'пй ' => 0, - 'пк ' => 0, - 'пл ' => 0, - 'пм ' => 0, - 'пн ' => 0, - 'пф ' => 0, - 'пх ' => 0, - 'пц ' => 0, - 'пч ' => 0, - 'пш ' => 0, - 'пщ ' => 0, - 'пъ' => 0, - 'пъ ' => 0, - 'пэ' => 0, - 'пэ ' => 0, - 'пю ' => 0, - 'рё ' => 0, - 'рй' => 0, - 'рй ' => 0, - 'ръ' => 0, - 'ръ ' => 0, - 'рэ ' => 0, - 'сб ' => 0, - 'св ' => 0, - 'сг ' => 0, - 'сд ' => 0, - 'сж ' => 0, - 'сз' => 0, - 'сз ' => 0, - 'сй' => 0, - 'сй ' => 0, - 'сн ' => 0, - 'сп ' => 0, - 'сф ' => 0, - 'сц ' => 0, - 'сч ' => 0, - 'сш ' => 0, - 'сщ ' => 0, - 'съ ' => 0, - 'сэ ' => 0, - 'тб ' => 0, - 'тг ' => 0, - 'тд ' => 0, - 'тж ' => 0, - 'тз ' => 0, - 'тй' => 0, - 'тй ' => 0, - 'тк ' => 0, - 'тл ' => 0, - 'тп ' => 0, - 'тф ' => 0, - 'тх ' => 0, - 'тц ' => 0, - 'тш ' => 0, - 'тщ ' => 0, - 'тъ ' => 0, - 'уё ' => 0, - 'уо ' => 0, - 'уу ' => 0, - 'уц ' => 0, - 'уъ' => 0, - 'уъ ' => 0, - 'уы' => 0, - 'уы ' => 0, - 'уь' => 0, - 'уь ' => 0, - 'уэ ' => 0, - 'фё ' => 0, - 'фб ' => 0, - 'фв ' => 0, - 'фг ' => 0, - 'фд ' => 0, - 'фж' => 0, - 'фж ' => 0, - 'фз' => 0, - 'фз ' => 0, - 'фй' => 0, - 'фй ' => 0, - 'фк ' => 0, - 'фл ' => 0, - 'фн ' => 0, - 'фп' => 0, - 'фп ' => 0, - 'фс ' => 0, - 'фх' => 0, - 'фх ' => 0, - 'фц' => 0, - 'фц ' => 0, - 'фч ' => 0, - 'фш ' => 0, - 'фщ ' => 0, - 'фъ' => 0, - 'фъ ' => 0, - 'фэ' => 0, - 'фэ ' => 0, - 'фю ' => 0, - 'хё' => 0, - 'хё ' => 0, - 'хб ' => 0, - 'хг ' => 0, - 'хд ' => 0, - 'хж ' => 0, - 'хз ' => 0, - 'хй' => 0, - 'хй ' => 0, - 'хк ' => 0, - 'хн ' => 0, - 'хп ' => 0, - 'хр ' => 0, - 'хс ' => 0, - 'хф ' => 0, - 'хх ' => 0, - 'хц ' => 0, - 'хч ' => 0, - 'хш ' => 0, - 'хщ' => 0, - 'хщ ' => 0, - 'хъ ' => 0, - 'хы' => 0, - 'хы ' => 0, - 'хь' => 0, - 'хь ' => 0, - 'хэ ' => 0, - 'хю' => 0, - 'хю ' => 0, - 'хя' => 0, - 'хя ' => 0, - 'цё' => 0, - 'цё ' => 0, - 'цб' => 0, - 'цб ' => 0, - 'цв ' => 0, - 'цг ' => 0, - 'цд ' => 0, - 'цж' => 0, - 'цж ' => 0, - 'цз ' => 0, - 'цй' => 0, - 'цй ' => 0, - 'цк ' => 0, - 'цл ' => 0, - 'цм ' => 0, - 'цн ' => 0, - 'цп ' => 0, - 'цр ' => 0, - 'цс ' => 0, - 'цт ' => 0, - 'цф' => 0, - 'цф ' => 0, - 'цх' => 0, - 'цх ' => 0, - 'цц ' => 0, - 'цч' => 0, - 'цч ' => 0, - 'цш ' => 0, - 'цщ' => 0, - 'цщ ' => 0, - 'цъ' => 0, - 'цъ ' => 0, - 'ць' => 0, - 'ць ' => 0, - 'цэ' => 0, - 'цэ ' => 0, - 'цю' => 0, - 'цю ' => 0, - 'ця' => 0, - 'ця ' => 0, - 'чё ' => 0, - 'чб ' => 0, - 'чг' => 0, - 'чг ' => 0, - 'чд' => 0, - 'чд ' => 0, - 'чж ' => 0, - 'чз' => 0, - 'чз ' => 0, - 'чй' => 0, - 'чй ' => 0, - 'чк ' => 0, - 'чл ' => 0, - 'чм ' => 0, - 'чн ' => 0, - 'чп' => 0, - 'чп ' => 0, - 'чр ' => 0, - 'чс ' => 0, - 'чф' => 0, - 'чф ' => 0, - 'чх ' => 0, - 'чц ' => 0, - 'чч ' => 0, - 'чш ' => 0, - 'чщ' => 0, - 'чщ ' => 0, - 'чъ' => 0, - 'чъ ' => 0, - 'чы' => 0, - 'чы ' => 0, - 'чэ' => 0, - 'чэ ' => 0, - 'чю' => 0, - 'чю ' => 0, - 'чя' => 0, - 'чя ' => 0, - 'шё ' => 0, - 'шб ' => 0, - 'шг ' => 0, - 'шд' => 0, - 'шд ' => 0, - 'шж' => 0, - 'шж ' => 0, - 'шз' => 0, - 'шз ' => 0, - 'шй' => 0, - 'шй ' => 0, - 'шк ' => 0, - 'шл ' => 0, - 'шм ' => 0, - 'шн ' => 0, - 'шп ' => 0, - 'шр ' => 0, - 'шс ' => 0, - 'шф ' => 0, - 'шх' => 0, - 'шх ' => 0, - 'шч ' => 0, - 'шш' => 0, - 'шш ' => 0, - 'шщ' => 0, - 'шщ ' => 0, - 'шъ' => 0, - 'шъ ' => 0, - 'шы' => 0, - 'шы ' => 0, - 'шэ' => 0, - 'шэ ' => 0, - 'шя' => 0, - 'шя ' => 0, - 'щб' => 0, - 'щб ' => 0, - 'щв ' => 0, - 'щг' => 0, - 'щг ' => 0, - 'щд' => 0, - 'щд ' => 0, - 'щж' => 0, - 'щж ' => 0, - 'щз' => 0, - 'щз ' => 0, - 'щй' => 0, - 'щй ' => 0, - 'щк' => 0, - 'щк ' => 0, - 'щл' => 0, - 'щл ' => 0, - 'щм ' => 0, - 'щн ' => 0, - 'щп' => 0, - 'щп ' => 0, - 'щр ' => 0, - 'щс' => 0, - 'щс ' => 0, - 'щт' => 0, - 'щт ' => 0, - 'щф' => 0, - 'щф ' => 0, - 'щх' => 0, - 'щх ' => 0, - 'щц' => 0, - 'щц ' => 0, - 'щч' => 0, - 'щч ' => 0, - 'щш' => 0, - 'щш ' => 0, - 'щщ' => 0, - 'щщ ' => 0, - 'щъ' => 0, - 'щъ ' => 0, - 'щы' => 0, - 'щы ' => 0, - 'щэ' => 0, - 'щэ ' => 0, - 'щю' => 0, - 'щю ' => 0, - 'щя' => 0, - 'щя ' => 0, - 'ъё ' => 0, - 'ъа' => 0, - 'ъа ' => 0, - 'ъб' => 0, - 'ъб ' => 0, - 'ъв' => 0, - 'ъв ' => 0, - 'ъг' => 0, - 'ъг ' => 0, - 'ъд' => 0, - 'ъд ' => 0, - 'ъе ' => 0, - 'ъж' => 0, - 'ъж ' => 0, - 'ъз' => 0, - 'ъз ' => 0, - 'ъи' => 0, - 'ъи ' => 0, - 'ъй' => 0, - 'ъй ' => 0, - 'ък' => 0, - 'ък ' => 0, - 'ъл' => 0, - 'ъл ' => 0, - 'ъм' => 0, - 'ъм ' => 0, - 'ън' => 0, - 'ън ' => 0, - 'ъо' => 0, - 'ъо ' => 0, - 'ъп' => 0, - 'ъп ' => 0, - 'ър' => 0, - 'ър ' => 0, - 'ъс' => 0, - 'ъс ' => 0, - 'ът' => 0, - 'ът ' => 0, - 'ъу' => 0, - 'ъу ' => 0, - 'ъф' => 0, - 'ъф ' => 0, - 'ъх' => 0, - 'ъх ' => 0, - 'ъц' => 0, - 'ъц ' => 0, - 'ъч' => 0, - 'ъч ' => 0, - 'ъш' => 0, - 'ъш ' => 0, - 'ъщ' => 0, - 'ъщ ' => 0, - 'ъъ' => 0, - 'ъъ ' => 0, - 'ъы' => 0, - 'ъы ' => 0, - 'ъь' => 0, - 'ъь ' => 0, - 'ъэ' => 0, - 'ъэ ' => 0, - 'ъю ' => 0, - 'ъя ' => 0, - 'ыё' => 0, - 'ыё ' => 0, - 'ыа' => 0, - 'ыа ' => 0, - 'ыи ' => 0, - 'ыо ' => 0, - 'ыу ' => 0, - 'ыф ' => 0, - 'ыъ' => 0, - 'ыъ ' => 0, - 'ыы' => 0, - 'ыы ' => 0, - 'ыь' => 0, - 'ыь ' => 0, - 'ыэ' => 0, - 'ыэ ' => 0, - 'ыю ' => 0, - 'ьа' => 0, - 'ьа ' => 0, - 'ьв ' => 0, - 'ьг ' => 0, - 'ьж ' => 0, - 'ьз ' => 0, - 'ьй' => 0, - 'ьй ' => 0, - 'ьл ' => 0, - 'ьн ' => 0, - 'ьр ' => 0, - 'ьу' => 0, - 'ьу ' => 0, - 'ьх ' => 0, - 'ьщ ' => 0, - 'ьъ' => 0, - 'ьъ ' => 0, - 'ьы ' => 0, - 'ьь' => 0, - 'ьь ' => 0, - 'ьэ ' => 0, - 'эё' => 0, - 'эё ' => 0, - 'эа' => 0, - 'эа ' => 0, - 'эб' => 0, - 'эб ' => 0, - 'эв ' => 0, - 'эг ' => 0, - 'эд ' => 0, - 'эе' => 0, - 'эе ' => 0, - 'эж' => 0, - 'эж ' => 0, - 'эз ' => 0, - 'эи ' => 0, - 'эй ' => 0, - 'эл ' => 0, - 'эм ' => 0, - 'эн ' => 0, - 'эо' => 0, - 'эо ' => 0, - 'эу' => 0, - 'эу ' => 0, - 'эф ' => 0, - 'эх ' => 0, - 'эц' => 0, - 'эц ' => 0, - 'эч' => 0, - 'эч ' => 0, - 'эш ' => 0, - 'эщ' => 0, - 'эщ ' => 0, - 'эъ' => 0, - 'эъ ' => 0, - 'эы' => 0, - 'эы ' => 0, - 'эь' => 0, - 'эь ' => 0, - 'ээ ' => 0, - 'эю' => 0, - 'эю ' => 0, - 'эя' => 0, - 'эя ' => 0, - 'юё' => 0, - 'юё ' => 0, - 'юа ' => 0, - 'юе ' => 0, - 'юж ' => 0, - 'юи ' => 0, - 'юл ' => 0, - 'юо ' => 0, - 'юу' => 0, - 'юу ' => 0, - 'юц ' => 0, - 'юъ' => 0, - 'юъ ' => 0, - 'юы' => 0, - 'юы ' => 0, - 'юь' => 0, - 'юь ' => 0, - 'юэ ' => 0, - 'юя' => 0, - 'яё' => 0, - 'яё ' => 0, - 'яа' => 0, - 'яа ' => 0, - 'яе ' => 0, - 'яо ' => 0, - 'яф' => 0, - 'яф ' => 0, - 'яъ' => 0, - 'яъ ' => 0, - 'яы' => 0, - 'яы ' => 0, - 'яь' => 0, - 'яь ' => 0, - 'яэ' => 0, - 'яэ ' => 0, - #en - ' \'f' => 0, - ' \'p' => 0, - ' \'q' => 0, - ' \'r' => 0, - ' \'x' => 0, - ' \'y' => 0, - ' \'z' => 0, - ' bj' => 0, - ' bq' => 0, - ' bz' => 0, - ' c\'' => 0, - ' cq' => 0, - ' cv' => 0, - ' cx' => 0, - ' dq' => 0, - ' dx' => 0, - ' ez' => 0, - ' f\'' => 0, - ' fh' => 0, - ' fk' => 0, - ' fq' => 0, - ' fv' => 0, - ' fw' => 0, - ' fz' => 0, - ' g\'' => 0, - ' gf' => 0, - ' gg' => 0, - ' gj' => 0, - ' gv' => 0, - ' gx' => 0, - ' gz' => 0, - ' h\'' => 0, - ' hj' => 0, - ' hk' => 0, - ' hn' => 0, - ' hq' => 0, - ' hx' => 0, - ' iq' => 0, - ' iw' => 0, - ' iy' => 0, - ' jb' => 0, - ' jf' => 0, - ' jh' => 0, - ' jj' => 0, - ' jk' => 0, - ' jl' => 0, - ' jm' => 0, - ' jq' => 0, - ' jw' => 0, - ' jx' => 0, - ' jy' => 0, - ' jz' => 0, - ' k\'' => 0, - ' kf' => 0, - ' kj' => 0, - ' kq' => 0, - ' kt' => 0, - ' kx' => 0, - ' kz' => 0, - ' lj' => 0, - ' lk' => 0, - ' lq' => 0, - ' lv' => 0, - ' mj' => 0, - ' mq' => 0, - ' mz' => 0, - ' nj' => 0, - ' nk' => 0, - ' nq' => 0, - ' nz' => 0, - ' oq' => 0, - ' pj' => 0, - ' pz' => 0, - ' qb' => 0, - ' qe' => 0, - ' qf' => 0, - ' qg' => 0, - ' qh' => 0, - ' qj' => 0, - ' qk' => 0, - ' qo' => 0, - ' qp' => 0, - ' qs' => 0, - ' qv' => 0, - ' qx' => 0, - ' qy' => 0, - ' qz' => 0, - ' rb' => 0, - ' rk' => 0, - ' rq' => 0, - ' rv' => 0, - ' rx' => 0, - ' rz' => 0, - ' sz' => 0, - ' tf' => 0, - ' tg' => 0, - ' tj' => 0, - ' tq' => 0, - ' u\'' => 0, - ' ue' => 0, - ' uj' => 0, - ' uo' => 0, - ' uq' => 0, - ' uu' => 0, - ' uy' => 0, - ' vb' => 0, - ' vj' => 0, - ' vk' => 0, - ' vn' => 0, - ' vq' => 0, - ' vr' => 0, - ' vv' => 0, - ' vw' => 0, - ' vx' => 0, - ' vy' => 0, - ' vz' => 0, - ' wj' => 0, - ' wl' => 0, - ' wn' => 0, - ' wq' => 0, - ' wx' => 0, - ' wz' => 0, - ' xb' => 0, - ' xf' => 0, - ' xg' => 0, - ' xh' => 0, - ' xj' => 0, - ' xk' => 0, - ' xq' => 0, - ' xt' => 0, - ' xu' => 0, - ' xz' => 0, - ' yf' => 0, - ' yg' => 0, - ' yh' => 0, - ' yj' => 0, - ' yk' => 0, - ' yl' => 0, - ' yn' => 0, - ' yq' => 0, - ' yv' => 0, - ' yx' => 0, - ' yy' => 0, - ' yz' => 0, - ' z\'' => 0, - ' zb' => 0, - ' zc' => 0, - ' zd' => 0, - ' zf' => 0, - ' zg' => 0, - ' zh' => 0, - ' zj' => 0, - ' zk' => 0, - ' zl' => 0, - ' zm' => 0, - ' zq' => 0, - ' zr' => 0, - ' zv' => 0, - ' zw' => 0, - ' zx' => 0, - ' zz' => 0, - '\'a ' => 0, - '\'b' => 0, - '\'b ' => 0, - '\'c ' => 0, - '\'f' => 0, - '\'f ' => 0, - '\'g' => 0, - '\'g ' => 0, - '\'h ' => 0, - '\'i ' => 0, - '\'j' => 0, - '\'j ' => 0, - '\'k' => 0, - '\'k ' => 0, - '\'l ' => 0, - '\'n ' => 0, - '\'o ' => 0, - '\'p ' => 0, - '\'q' => 0, - '\'q ' => 0, - '\'r ' => 0, - '\'u' => 0, - '\'u ' => 0, - '\'v ' => 0, - '\'w ' => 0, - '\'x' => 0, - '\'x ' => 0, - '\'z' => 0, - '\'z ' => 0, - 'b\' ' => 0, - 'bg ' => 0, - 'bh ' => 0, - 'bp ' => 0, - 'bq' => 0, - 'bq ' => 0, - 'bv ' => 0, - 'bx' => 0, - 'bz' => 0, - 'bz ' => 0, - 'c\' ' => 0, - 'cf ' => 0, - 'cj' => 0, - 'cn ' => 0, - 'cq ' => 0, - 'cv' => 0, - 'cw' => 0, - 'cx' => 0, - 'cx ' => 0, - 'cz ' => 0, - 'db ' => 0, - 'dj ' => 0, - 'dk ' => 0, - 'dw ' => 0, - 'dx' => 0, - 'eh ' => 0, - 'ej ' => 0, - 'f\' ' => 0, - 'fg ' => 0, - 'fh ' => 0, - 'fj' => 0, - 'fj ' => 0, - 'fk' => 0, - 'fk ' => 0, - 'fq' => 0, - 'fq ' => 0, - 'fv ' => 0, - 'fw ' => 0, - 'fx' => 0, - 'fx ' => 0, - 'fz' => 0, - 'fz ' => 0, - 'g\' ' => 0, - 'gc ' => 0, - 'gf ' => 0, - 'gj ' => 0, - 'gk ' => 0, - 'gl ' => 0, - 'gq' => 0, - 'gq ' => 0, - 'gv' => 0, - 'gv ' => 0, - 'gw ' => 0, - 'gx' => 0, - 'gx ' => 0, - 'gz ' => 0, - 'hb ' => 0, - 'hc ' => 0, - 'hg ' => 0, - 'hh ' => 0, - 'hj' => 0, - 'hj ' => 0, - 'hk ' => 0, - 'hv' => 0, - 'hv ' => 0, - 'hw ' => 0, - 'hx' => 0, - 'hx ' => 0, - 'hz' => 0, - 'i\' ' => 0, - 'ih ' => 0, - 'iq ' => 0, - 'iw ' => 0, - 'j\'' => 0, - 'j\' ' => 0, - 'jb' => 0, - 'jb ' => 0, - 'jc' => 0, - 'jc ' => 0, - 'jd' => 0, - 'jf' => 0, - 'jg' => 0, - 'jg ' => 0, - 'jh' => 0, - 'jh ' => 0, - 'jj' => 0, - 'jj ' => 0, - 'jk ' => 0, - 'jl ' => 0, - 'jm' => 0, - 'jm ' => 0, - 'jn' => 0, - 'jn ' => 0, - 'jp ' => 0, - 'jq' => 0, - 'jq ' => 0, - 'jr' => 0, - 'jr ' => 0, - 'js' => 0, - 'js ' => 0, - 'jt' => 0, - 'ju ' => 0, - 'jv' => 0, - 'jv ' => 0, - 'jw' => 0, - 'jw ' => 0, - 'jx' => 0, - 'jx ' => 0, - 'jy' => 0, - 'jy ' => 0, - 'jz' => 0, - 'jz ' => 0, - 'kb ' => 0, - 'kc ' => 0, - 'kd ' => 0, - 'kj ' => 0, - 'km ' => 0, - 'kp ' => 0, - 'kq' => 0, - 'kq ' => 0, - 'kv' => 0, - 'kv ' => 0, - 'kx' => 0, - 'kx ' => 0, - 'kz' => 0, - 'kz ' => 0, - 'lg ' => 0, - 'lh ' => 0, - 'lj ' => 0, - 'lq ' => 0, - 'lr ' => 0, - 'lv ' => 0, - 'lw ' => 0, - 'lx' => 0, - 'lz ' => 0, - 'm\' ' => 0, - 'mg ' => 0, - 'mh ' => 0, - 'mj ' => 0, - 'mk ' => 0, - 'mq' => 0, - 'mq ' => 0, - 'mx' => 0, - 'mx ' => 0, - 'mz' => 0, - 'nb ' => 0, - 'nm ' => 0, - 'pj ' => 0, - 'pk ' => 0, - 'pq' => 0, - 'pq ' => 0, - 'pv' => 0, - 'pw ' => 0, - 'px' => 0, - 'px ' => 0, - 'pz ' => 0, - 'q\'' => 0, - 'q\' ' => 0, - 'qa ' => 0, - 'qb' => 0, - 'qb ' => 0, - 'qc' => 0, - 'qc ' => 0, - 'qd' => 0, - 'qd ' => 0, - 'qe' => 0, - 'qe ' => 0, - 'qf' => 0, - 'qf ' => 0, - 'qg' => 0, - 'qg ' => 0, - 'qh' => 0, - 'qh ' => 0, - 'qi' => 0, - 'qj' => 0, - 'qj ' => 0, - 'qk' => 0, - 'qk ' => 0, - 'ql' => 0, - 'ql ' => 0, - 'qm' => 0, - 'qm ' => 0, - 'qn' => 0, - 'qn ' => 0, - 'qo' => 0, - 'qo ' => 0, - 'qp' => 0, - 'qp ' => 0, - 'qq' => 0, - 'qq ' => 0, - 'qr' => 0, - 'qs' => 0, - 'qs ' => 0, - 'qt' => 0, - 'qt ' => 0, - 'qu ' => 0, - 'qv' => 0, - 'qv ' => 0, - 'qw' => 0, - 'qw ' => 0, - 'qx' => 0, - 'qx ' => 0, - 'qy' => 0, - 'qy ' => 0, - 'qz' => 0, - 'qz ' => 0, - 'rq ' => 0, - 'rz ' => 0, - 'sg ' => 0, - 'sj ' => 0, - 'sx' => 0, - 'sx ' => 0, - 'sz' => 0, - 'sz ' => 0, - 'tg ' => 0, - 'tj ' => 0, - 'tq' => 0, - 'tq ' => 0, - 'tx' => 0, - 'tx ' => 0, - 'uj ' => 0, - 'uq ' => 0, - 'uu ' => 0, - 'uw ' => 0, - 'v\' ' => 0, - 'vb' => 0, - 'vb ' => 0, - 'vc' => 0, - 'vf' => 0, - 'vf ' => 0, - 'vg' => 0, - 'vh' => 0, - 'vh ' => 0, - 'vj' => 0, - 'vj ' => 0, - 'vk' => 0, - 'vk ' => 0, - 'vl ' => 0, - 'vm' => 0, - 'vn ' => 0, - 'vp' => 0, - 'vp ' => 0, - 'vq' => 0, - 'vq ' => 0, - 'vr ' => 0, - 'vv ' => 0, - 'vw' => 0, - 'vw ' => 0, - 'vx' => 0, - 'vz' => 0, - 'vz ' => 0, - 'w\' ' => 0, - 'wb ' => 0, - 'wc ' => 0, - 'wf ' => 0, - 'wg ' => 0, - 'wj' => 0, - 'wj ' => 0, - 'wq' => 0, - 'wq ' => 0, - 'wr ' => 0, - 'wv' => 0, - 'wv ' => 0, - 'wx' => 0, - 'wz ' => 0, - 'x\'' => 0, - 'x\' ' => 0, - 'xa ' => 0, - 'xb ' => 0, - 'xc ' => 0, - 'xd' => 0, - 'xd ' => 0, - 'xf ' => 0, - 'xg ' => 0, - 'xh ' => 0, - 'xj' => 0, - 'xj ' => 0, - 'xk' => 0, - 'xk ' => 0, - 'xl ' => 0, - 'xm ' => 0, - 'xn' => 0, - 'xn ' => 0, - 'xp ' => 0, - 'xq ' => 0, - 'xr' => 0, - 'xr ' => 0, - 'xs ' => 0, - 'xu ' => 0, - 'xv' => 0, - 'xv ' => 0, - 'xw ' => 0, - 'xx' => 0, - 'xz' => 0, - 'xz ' => 0, - 'yb ' => 0, - 'yc ' => 0, - 'yd ' => 0, - 'yf ' => 0, - 'yg ' => 0, - 'yh ' => 0, - 'yj ' => 0, - 'yq' => 0, - 'yq ' => 0, - 'yu ' => 0, - 'yv ' => 0, - 'yw ' => 0, - 'yy' => 0, - 'yy ' => 0, - 'yz ' => 0, - 'z\'' => 0, - 'z\' ' => 0, - 'zb ' => 0, - 'zc' => 0, - 'zc ' => 0, - 'zd' => 0, - 'zd ' => 0, - 'zf' => 0, - 'zf ' => 0, - 'zg ' => 0, - 'zh' => 0, - 'zh ' => 0, - 'zj' => 0, - 'zj ' => 0, - 'zk ' => 0, - 'zl ' => 0, - 'zn' => 0, - 'zn ' => 0, - 'zp ' => 0, - 'zq' => 0, - 'zq ' => 0, - 'zr' => 0, - 'zr ' => 0, - 'zs' => 0, - 'zs ' => 0, - 'zt' => 0, - 'zt ' => 0, - 'zu ' => 0, - 'zv ' => 0, - 'zw ' => 0, - 'zx' => 0, - 'zx ' => 0, - ); - - /** - * - * @param array|null $words_exceptions - */ - public function __construct(array $words_exceptions = null) - { - if (! ReflectionTypeHint::isValid()) return false; - #русский --> английский: - $this->en_correct = '/(?: (?:' . $this->tt_f . ') - (?: (?:' . $this->en_uniq . ') | (?:' . $this->en_sc . '){2} ) - | (?:' . $this->en_sc . ') - (?:' . $this->tt_f . ') - (?:' . $this->en_sc . ') - | (?: (?:' . $this->en_uniq . ') | (?:' . $this->en_sc . '){2} ) - (?:' . $this->tt_f . ') - ) - /sxSX'; - #английский --> русский: - $this->tt_correct = '/(?: (?:' . $this->en_sc . ') - (?: (?:' . $this->tt_uniq . ') | (?:' . $this->tt_f . '){2} ) - | (?:' . $this->tt_f . ') - (?:' . $this->en_sc . ') - (?:' . $this->tt_f . ') - | (?: (?:' . $this->tt_uniq . ') | (?:' . $this->tt_f . '){2} ) - (?:' . $this->en_sc . ') - ) - /sxSX'; - $this->table_flip = array( - 0 => array_flip($this->table[0]), - 1 => array_flip($this->table[1]), - ); - if (is_array($words_exceptions)) $this->words_exceptions += $words_exceptions; - } - - /** - * Исправляет клавиатурные опечатки в тексте. - * - * @param scalar|null $s Текст в кодировке UTF-8. - * @param int $mode Константы self::SIMILAR_CHARS и/или self::KEYBOARD_LAYOUT, - * (их можно комбинировать). Описание констант см. выше. - * При использовании self::KEYBOARD_LAYOUT время работы увеличивается примерно в 10 раз. - * @param array &$words Ассоц. массив со словами, которые были исправлены: - * в ключах оригиналы, в значениях исправленные слова. - * @return string|bool Returns FALSE if error occured - */ - public function parse($s, $mode = self::SIMILAR_CHARS, array &$words = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_string($s)) return $s; - - if ($mode < self::SIMILAR_CHARS || $mode > (self::SIMILAR_CHARS | self::KEYBOARD_LAYOUT | self::ADD_FIX)) - { - trigger_error('Unknown mode', E_USER_WARNING); - return false; - } - - $this->mode = $mode; - - #вырезаем и заменяем некоторые символы - $additional_chars = array( - "\xc2\xad", #"мягкие" переносы строк (­) - ); - #http://ru.wikipedia.org/wiki/Диакритические_знаки - $s = UTF8::diactrical_remove($s, $additional_chars, $is_can_restored = true, $restore_table); - - $this->words = array(); - $s = $this->_parse1($s); - $s = $this->_parse2($s); - $s = UTF8::diactrical_restore($s, $restore_table); - $words = $this->words; - return $s; - } - - private function _parse1($s) - { - #заменяем слова из текста, минимальная длина -- 3 символа, меньше нельзя - return preg_replace_callback('/(?> (' . $this->en . ') #1 латинские буквы - | (' . $this->tt . ') #2 русские буквы - | (' . $this->sc . ') #3 символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв - ){3,}+ - /sxSX', array($this, '_word'), $s); - } - - private function _parse2($s) - { - #исправляем русские буквы (похожие на латинские) с рядом стоящими цифрами на латинские - #например, это м. б. каталожные номера автозапчастей, в которых есть русские буквы: 1500A023, 52511-60900-H0, K2305, XA527672 - #корректно обрабатываем вхождения '1-ое', 'Ту-134', 'А19-3107/06-43-Ф02-4227/06-С1' - if (version_compare(PHP_VERSION, '5.2.0', '<')) return $s; - return preg_replace_callback('~(?: (?<=[^-_/]|^) - (?:' . $this->ru_similar . ')++ - (?= (?:' . $this->en . '|[-_/])*+ (?<=[^-_/]|' . $this->en . '[-_/]) - \d [\d-_/]*+ (?!' . $this->tt_uniq . ') - ) - | (?<=[^-_/]|^) - \d (?:' . $this->en . '|[-_/])*+ (?<=[^-_/]|' . $this->en . '[-_/]) - \K - (?:' . $this->ru_similar . ')++ - (?= [\d-_/]*+ (?!' . $this->tt_uniq . ') ) - ) - ~sxSX', array($this, '_entry'), $s); - } - - private function _entry(array &$a) - { - $entry =& $a[0]; - $s = strtr($entry, $this->table[0]); - if ($s !== $entry) $this->words[$entry] = $s; - return $s; - } - - private function _word(array &$a) - { - $word = $a[0]; - #var_export($a); - - $suggestions = array(); - - #если найдено слово из мешанины русских и латинских букв - if (! empty($a[1]) && ! empty($a[2])) - { - if (($this->mode & self::SIMILAR_CHARS) === 0) return $word; - #ВНИМАНИЕ! порядок следования правил преобразования имеет значение! - - /* - Исправляем ошибочно набранные буквы, которые выглядят одинаково - в инициалах перед фамилиями (русский <--> английский), например: Т.С.Навка - */ - - #0a. английский --> русский: - if (substr($word, 1, 1) === '.' #оптимизация - && preg_match('/^ ( ' . $this->en_similar_uc . '\. #первый инициал - (?:' . $this->en_similar_uc . '\.)? #второй инициал (необязательно) - ) #1 инициалы - (' . $this->no_sc . '{2,}+) #2 фамилия (английские и русские буквы) - $/sxSX', $word, $m)) - { - $m[2] = $this->_parse1($m[2]); - #фамилия по-русски? - if (preg_match('/^ (?:' . $this->tt_uc . ') #первая буква д.б. большая - (?:' . $this->tt_f . ')+ #минимальное кол-во букв в фамилии = 2 - $/sxSX', $m[2])) return strtr($m[1], $this->table_flip[0]) . $m[2]; - } - - #0b. русский --> английский: - if (substr($word, 2, 1) === '.' #оптимизация - && preg_match('/^ ( ' . $this->ru_similar_uc . '\. #первый инициал - (?:' . $this->ru_similar_uc . '\.)? #второй инициал (необязательно) - ) #1 инициалы - (' . $this->no_sc . '{2,}+) #2 фамилия (английские и русские буквы) - $/sxSX', $word, $m)) - { - $m[2] = $this->_parse1($m[2]); - #фамилия по-англ.? - if (preg_match('/^ ' . $this->en_uc . ' #первая буква д.б. большая - ' . $this->en . '++ #минимальное кол-во букв в фамилии = 2 - $/sxSX', $m[2])) return strtr($m[1], $this->table[0]) . $m[2]; - } - - #1. английский --> русский: - $this->method = 0; #буквы, которые выглядят одинаково - $this->is_flip = true; - $s = $this->_replace($word, $this->tt_correct); - if ($word !== $s && ! $this->_is_mixed($s)) $suggestions['tt0'] = $s; - - #2. английский --> русский: - $this->method = 1; #буквы в другой раскладке клавиатуры - $this->is_flip = true; - $s = $this->_replace($word, $this->tt_correct); - if ($word !== $s) $suggestions['tt1'] = $s; - - #3. русский --> английский: - $this->method = 0; #буквы, которые выглядят одинаково - $this->is_flip = false; - $s = $this->_replace($word, $this->en_correct); - if ($word !== $s && ! $this->_is_mixed($s)) $suggestions['en0'] = $s; - - #4. русский --> английский: - $this->method = 1; #буквы в другой раскладке клавиатуры - $this->is_flip = false; - $s = $this->_replace($word, $this->en_correct); - if ($word !== $s) $suggestions['en1'] = $s; - - } - #если найдено слово только из латинских букв; минимальная длина -- 4 буквы! - elseif (! empty($a[1]) && strlen($word) >= 4) - { - if (($this->mode & self::KEYBOARD_LAYOUT) === 0) return $word; - - #не обрабатываем аббревиатуры, пример: AMPAS - if (preg_match('/^(?:' . $this->en_uc . '|' . $this->sc . '){1,6}+$/sxSX', $word)) return $word; - - #английский --> русский: - $suggestions['en1'] = $word; - $suggestions['tt1'] = strtr($word, $this->table_flip[1]); - } - #если найдено слово только из русских букв; минимальная длина -- 4 буквы! - elseif (! empty($a[2]) && strlen($word) >= 8) - { - if (($this->mode & self::KEYBOARD_LAYOUT) === 0) return $word; - - #не обрабатываем аббревиатуры, пример: ДОСААФ - if (preg_match('/^(?:' . $this->tt_uc . '|' . $this->sc . '){1,6}+$/sxSX', $word)) return $word; - - #русский --> английский: - $suggestions['tt1'] = $word; - $suggestions['en1'] = strtr($word, $this->table[1]); - } - #найдены спецсимволы или длина слова слишком мала - else return $word; - - $suggestions = array_unique($suggestions); - #var_export($suggestions); - - $c = count($suggestions); - if ($c === 0) $s = $word; - else $s = $this->_detect($word, $suggestions, ! empty($a[3])); - if ($s !== $word) - { - $this->words[$word] = $s; - if ($this->mode >= (self::KEYBOARD_LAYOUT | self::ADD_FIX)) $s = '(' . $word . '=>' . $s . ')'; - } - return $s; - } - - private function _replace($word, $regexp) - { - do $word = preg_replace_callback($regexp, array(&$this, '_strtr'), $w = $word); - while ($w !== $word); - return $word; - } - - private function _strtr(array $a) - { - $word =& $a[0]; - return strtr($word, $this->is_flip ? $this->table_flip[$this->method] : $this->table[$this->method]); - } - - private function _is_mixed($word) - { - return preg_match('/(?:' . $this->en . ')/sxSX', $word) && - preg_match('/(?:' . $this->tt_f . ')/sxSX', $word); - } - - #выбираем из нескольких вариантов один - private function _detect($word, array $suggestions, $is_sc) - { - if (0) #DEBUG - { - //$suggestions['?'] = $word; - var_export($suggestions); - } - #не д. б. несуществующих N-грамм - foreach ($suggestions as $type => $w) - { - $lang = substr($type, 0, 2); - if ($this->_bigram_exists($w, $lang)) unset($suggestions[$type]); - } - if (0) #DEBUG - { - //$suggestions['?'] = $word; - var_export($suggestions); - } - if (count($suggestions) === 0) return $word; - - $s = end($suggestions); - - #если в $word были спецсимволы, а в $s их уже нет, возвращаем $s - if ($is_sc && ! preg_match('/' . $this->sc . '/sSX', $s)) return $s; - - #если в $s спецсимволов больше чем букв, возвращаем $word - $sc_count = 0; - $s = preg_replace('/' . $this->sc . '/sSX', '', $s, -1, $sc_count); - if ($sc_count > 0 && $sc_count > UTF8::strlen($s)) return $word; - - return reset($suggestions); - } - - #анализ на основе N-грамм русского и английского языка - private function _bigram_exists($word, $lang) - { - $word = ($lang === 'en') ? strtolower($word) : UTF8::lowercase($word); - - #шаг 0. - #проверяем слова в списке слов-исключений - if (array_key_exists($word, $this->words_exceptions[$lang])) return false; - - #шаг 1. - #проверка на 4 согласные буквы подряд; пример: больши{нств}о, юрисконсу{льтс}тво - if (preg_match('/(?:' . $this->consonant_lc[$lang] . '){4}/sxSX', $word, $m) - #проверяем список исключений - && ! array_key_exists($m[0], $this->consonants4_lc[$lang])) return true; - - #шаг 2. - #проверка на 3 гласные буквы подряд; пример: длиннош{еее}, зм{еео}бразный - if (preg_match('/(?:' . $this->vowel_lc[$lang] . '){3}/sxSX', $word, $m) - #проверяем список исключений - && ! array_key_exists($m[0], $this->vowels3_lc[$lang])) return true; - - #шаг 3. - $length = UTF8::strlen($word); - for ($pos = 0, $limit = $length - 1; $pos < $limit; $pos++) - { - /* - TODO Качество проверки по несуществующим биграммам можно немного повысить, - если учитывать не только начало и конец слова, но и все позиции биграмм в слове. - */ - $ss = UTF8::substr($word, $pos, 2); - if ($pos === 0) $ss = ' ' . $ss; #beginning of word - elseif ($pos === $limit - 1) $ss = $ss . ' '; #ending of word - if (array_key_exists($ss, $this->bigrams)) return true; - } - - return false; - } -} \ No newline at end of file diff --git a/library/includes/classes/emailer.php b/library/includes/classes/emailer.php deleted file mode 100644 index 3c94a0e89..000000000 --- a/library/includes/classes/emailer.php +++ /dev/null @@ -1,244 +0,0 @@ -reset(); - $this->from = $bb_cfg['board_email']; - $this->reply_to = $bb_cfg['board_email']; - $this->use_smtp = $use_smtp; /*!empty($bb_cfg['smtp_host']); - - $this->use_template($tpl_name); - $this->set_subject($sbj); - $this->email_address($to_address);*/ - } - - function set_default_vars () - { - global $bb_cfg; - - $this->vars = array( - 'BOARD_EMAIL' => $bb_cfg['board_email'], - 'SITENAME' => $bb_cfg['board_email_sitename'], - 'EMAIL_SIG' => !empty($bb_cfg['board_email_sig']) ? "-- \n{$bb_cfg['board_email_sig']}" : '', - ); - } - - // Resets all the data (address, template file, etc etc to default - function reset () - { - $this->addresses = array(); - $this->msg = $this->extra_headers = ''; - $this->set_default_vars(); - } - - // Sets an email address to send to - function email_address ($address) - { - $this->addresses['to'] = trim($address); - } - - function cc ($address) - { - $this->addresses['cc'][] = trim($address); - } - - function bcc ($address) - { - $this->addresses['bcc'][] = trim($address); - } - - function replyto ($address) - { - $this->reply_to = trim($address); - } - - function from ($address) - { - $this->from = trim($address); - } - - // set up subject for mail - function set_subject ($subject = '') - { - $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); - } - - // set up extra mail headers - function extra_headers ($headers) - { - $this->extra_headers .= trim($headers) . "\n"; - } - - function use_template ($template_file, $template_lang = '') - { - global $bb_cfg; - - if (trim($template_file) == '') - { - bb_die('No template file set'); - } - - if (trim($template_lang) == '') - { - $template_lang = $bb_cfg['default_lang']; - } - - if (empty($this->tpl_msg[$template_lang . $template_file])) - { - $tpl_file = LANG_ROOT_DIR ."$template_lang/email/$template_file.tpl"; - - if (!@file_exists(@bb_realpath($tpl_file))) - { - $tpl_file = LANG_ROOT_DIR ."{$bb_cfg['default_lang']}/email/$template_file.tpl"; - - if (!@file_exists(@bb_realpath($tpl_file))) - { - bb_die('Could not find email template file :: ' . $template_file); - } - } - - if (!($fd = @fopen($tpl_file, 'r'))) - { - bb_die('Failed opening template file :: ' . $tpl_file); - } - - $this->tpl_msg[$template_lang . $template_file] = fread($fd, filesize($tpl_file)); - fclose($fd); - } - - $this->msg = $this->tpl_msg[$template_lang . $template_file]; - - return true; - } - - // assign variables - function assign_vars ($vars) - { - $this->vars = array_merge($this->vars, $vars); - } - - // Send the mail out to the recipients set previously in var $this->address - function send ($email_format = 'text') - { - global $bb_cfg, $lang; - - if ($bb_cfg['emailer_disabled']) - { - return; - } - - // Escape all quotes - $this->msg = str_replace ("'", "\'", $this->msg); - $this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->msg); - - // Set vars - reset ($this->vars); - while (list($key, $val) = each($this->vars)) - { - $$key = $val; - } - - eval("\$this->msg = '$this->msg';"); - - // Clear vars - reset ($this->vars); - while (list($key, $val) = each($this->vars)) - { - unset($$key); - } - - // We now try and pull a subject from the email body ... if it exists, - // do this here because the subject may contain a variable - $drop_header = ''; - $match = array(); - if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match)) - { - $this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : 'No Subject'); - $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); - } - else - { - $this->subject = (($this->subject != '') ? $this->subject : 'No Subject'); - } - - if (preg_match('#^(Charset:(.*?))$#m', $this->msg, $match)) - { - $this->encoding = (trim($match[2]) != '') ? trim($match[2]) : trim($lang['CONTENT_ENCODING']); - $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); - } - else - { - $this->encoding = trim($lang['CONTENT_ENCODING']); - } - $this->subject = $this->encode($this->subject); - - if ($drop_header != '') - { - $this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg)); - } - - $to = @$this->addresses['to']; - - $cc = (@count($this->addresses['cc'])) ? implode(', ', $this->addresses['cc']) : ''; - $bcc = (@count($this->addresses['bcc'])) ? implode(', ', $this->addresses['bcc']) : ''; - - // Build header - $type = ($email_format == 'html') ? 'html' : 'plain'; - $this->extra_headers = (($this->reply_to != '') ? "Reply-to: $this->reply_to\n" : '') . (($this->from != '') ? "From: $this->from\n" : "From: " . $bb_cfg['board_email'] . "\n") . "Return-Path: " . $bb_cfg['board_email'] . "\nMessage-ID: <" . md5(uniqid(TIMENOW)) . "@" . $bb_cfg['server_name'] . ">\nMIME-Version: 1.0\nContent-type: text/$type; charset=" . $this->encoding . "\nContent-transfer-encoding: 8bit\nDate: " . date('r', TIMENOW) . "\nX-Priority: 0\nX-MSMail-Priority: Normal\nX-Mailer: Microsoft Office Outlook, Build 11.0.5510\nX-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441\nX-Sender: " . $bb_cfg['board_email'] . "\n" . $this->extra_headers . (($cc != '') ? "Cc: $cc\n" : '') . (($bcc != '') ? "Bcc: $bcc\n" : ''); - - // Send message - if ($this->use_smtp) - { - if (!defined('SMTP_INCLUDED')) - { - include(INC_DIR .'smtp.php'); - } - - $result = smtpmail($to, $this->subject, $this->msg, $this->extra_headers); - } - else - { - $to = ($to == '') ? ' ' : $to; - - $result = @mail($to, $this->subject, preg_replace("#(?msg), $this->extra_headers); - } - - // Did it work? - if (!$result) - { - bb_die('Failed sending email :: ' . (($this->use_smtp) ? 'SMTP' : 'PHP') . ' :: ' . $result); - } - - return true; - } - - function encode ($str) - { - if ($this->encoding == '') - { - return $str; - } - - // define start delimimter, end delimiter and spacer - $start = "=?$this->encoding?B?"; - $end = "?="; - - // encode the string and split it into chunks with spacers after each chunk - $str = base64_encode($str); - - return $start . $str . $end; - } -} \ No newline at end of file diff --git a/library/includes/classes/reflection.php b/library/includes/classes/reflection.php deleted file mode 100644 index d7023ad97..000000000 --- a/library/includes/classes/reflection.php +++ /dev/null @@ -1,186 +0,0 @@ - 'is_int', - 'integer' => 'is_int', - 'digit' => 'ctype_digit', - 'number' => 'ctype_digit', - 'float' => 'is_float', - 'double' => 'is_float', - 'real' => 'is_float', - 'numeric' => 'is_numeric', - 'str' => 'is_string', - 'string' => 'is_string', - 'char' => 'is_string', - 'bool' => 'is_bool', - 'boolean' => 'is_bool', - 'null' => 'is_null', - 'array' => 'is_array', - 'obj' => 'is_object', - 'object' => 'is_object', - 'res' => 'is_resource', - 'resource' => 'is_resource', - 'scalar' => 'is_scalar', #integer, float, string or boolean - 'cb' => 'is_callable', - 'callback' => 'is_callable', - ); - - #calling the methods of this class only statically! - private function __construct() {} - - public static function isValid() - { - if (! assert_options(ASSERT_ACTIVE)) return true; - $bt = self::debugBacktrace(null, 1); - extract($bt); //to $file, $line, $function, $class, $object, $type, $args - if (! $args) return true; #speed improve - $r = new ReflectionMethod($class, $function); - $doc = $r->getDocComment(); - $cache_id = $class. $type. $function; - preg_match_all('~ [\r\n]++ [\x20\t]++ \* [\x20\t]++ - @param - [\x20\t]++ - \K #memory reduce - ( [_a-z]++[_a-z\d]*+ - (?>[|/,][_a-z]+[_a-z\d]*)*+ - ) #1 types - [\x20\t]++ - &?+\$([_a-z]++[_a-z\d]*+) #2 name - ~sixSX', $doc, $params, PREG_SET_ORDER); - $parameters = $r->getParameters(); - //d($args, $params, $parameters); - if (count($parameters) > count($params)) - { - $message = 'phpDoc %d piece(s) @param description expected in %s%s%s(), %s given, ' . PHP_EOL - . 'called in %s on line %d ' . PHP_EOL - . 'and defined in %s on line %d'; - $message = sprintf($message, count($parameters), $class, $type, $function, count($params), $file, $line, $r->getFileName(), $r->getStartLine()); - trigger_error($message, E_USER_NOTICE); - } - foreach ($args as $i => $value) - { - if (! isset($params[$i])) return true; - if ($parameters[$i]->name !== $params[$i][2]) - { - $param_num = $i + 1; - $message = 'phpDoc @param %d in %s%s%s() must be named as $%s, $%s given, ' . PHP_EOL - . 'called in %s on line %d ' . PHP_EOL - . 'and defined in %s on line %d'; - $message = sprintf($message, $param_num, $class, $type, $function, $parameters[$i]->name, $params[$i][2], $file, $line, $r->getFileName(), $r->getStartLine()); - trigger_error($message, E_USER_NOTICE); - } - - $hints = preg_split('~[|/,]~sSX', $params[$i][1]); - if (! self::checkValueTypes($hints, $value)) - { - $param_num = $i + 1; - $message = 'Argument %d passed to %s%s%s() must be an %s, %s given, ' . PHP_EOL - . 'called in %s on line %d ' . PHP_EOL - . 'and defined in %s on line %d'; - $message = sprintf($message, $param_num, $class, $type, $function, implode('|', $hints), (is_object($value) ? get_class($value) . ' ' : '') . gettype($value), $file, $line, $r->getFileName(), $r->getStartLine()); - trigger_error($message, E_USER_WARNING); - return false; - } - } - return true; - } - - /** - * Return stacktrace. Correctly work with call_user_func*() - * (totally skip them correcting caller references). - * If $return_frame is present, return only $return_frame matched caller, not all stacktrace. - * - * @param string|null $re_ignore example: '~^' . preg_quote(__CLASS__, '~') . '(?![a-zA-Z\d])~sSX' - * @param int|null $return_frame - * @return array - */ - public static function debugBacktrace($re_ignore = null, $return_frame = null) - { - $trace = debug_backtrace(); - - $a = array(); - $frames = 0; - for ($i = 0, $n = count($trace); $i < $n; $i++) - { - $t = $trace[$i]; - if (! $t) continue; - - // Next frame. - $next = isset($trace[$i+1])? $trace[$i+1] : null; - - // Dummy frame before call_user_func*() frames. - if (! isset($t['file']) && $next) - { - $t['over_function'] = $trace[$i+1]['function']; - $t = $t + $trace[$i+1]; - $trace[$i+1] = null; // skip call_user_func on next iteration - } - - // Skip myself frame. - if (++$frames < 2) continue; - - // 'class' and 'function' field of next frame define where this frame function situated. - // Skip frames for functions situated in ignored places. - if ($re_ignore && $next) - { - // Name of function "inside which" frame was generated. - $frame_caller = (isset($next['class']) ? $next['class'] . $next['type'] : '') - . (isset($next['function']) ? $next['function'] : ''); - if (preg_match($re_ignore, $frame_caller)) continue; - } - - // On each iteration we consider ability to add PREVIOUS frame to $a stack. - if (count($a) === $return_frame) return $t; - $a[] = $t; - } - return $a; - } - - /** - * Checks a value to the allowed types - * - * @param array $types - * @param mixed $value - * @return bool - */ - public static function checkValueTypes(array $types, $value) - { - foreach ($types as $type) - { - $type = strtolower($type); - if (array_key_exists($type, self::$hints) && call_user_func(self::$hints[$type], $value)) return true; - if (is_object($value) && @is_a($value, $type)) return true; - if ($type === 'mixed') return true; - } - return false; - } -} \ No newline at end of file diff --git a/library/includes/classes/sitemap.php b/library/includes/classes/sitemap.php deleted file mode 100644 index c4632de9c..000000000 --- a/library/includes/classes/sitemap.php +++ /dev/null @@ -1,217 +0,0 @@ -home = make_url(); - } - - function build_map () { - $map = "\n\n"; - $map .= $this->get_static(); - $map .= $this->get_forum(); - $map .= $this->get_topic(); - $map .= ""; - - return $map; - } - - function build_index ($count) { - $lm = date('c'); - $map = "\n\n"; - $map .= "\n{$this->home}internal_data/sitemap/sitemap1.xml\n{$lm}\n\n"; - for ($i = 0; $i < $count; $i++) { - $t = $i + 2; - $map .= "\n{$this->home}internal_data/sitemap/sitemap{$t}.xml\n{$lm}\n\n"; - } - $map .= ""; - - return $map; - } - - function build_stat () { - $map = "\n\n"; - $map .= $this->get_static(); - $map .= $this->get_forum(); - $map .= ""; - - return $map; - } - - function build_map_topic ($n) { - $map = "\n\n"; - $map .= $this->get_topic($n); - $map .= ""; - - return $map; - } - - function get_forum () { - global $datastore; - - $this->priority = $this->cat_priority; - $xml = ''; - $lm = date('c'); - - if (!$forums = $datastore->get('cat_forums')) { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } - - $not_forums_id = $forums['not_auth_forums']['guest_view']; - $ignore_forum_sql = ($not_forums_id) ? "WHERE forum_id NOT IN($not_forums_id)" : ''; - - $sql = DB()->sql_query("SELECT forum_id, forum_topics, forum_parent, forum_name FROM " . BB_FORUMS . " " . $ignore_forum_sql . " ORDER BY forum_id ASC"); - - while ($row = DB()->sql_fetchrow($sql)) { - if (function_exists('seo_url')) $loc = $this->home . seo_url(FORUM_URL . $row['forum_id'], $row['forum_name']); - else $loc = $this->home . FORUM_URL . $row['forum_id']; - $xml .= $this->get_xml($loc, $lm); - } - - return $xml; - } - - function get_topic ($page = false) { - global $datastore; - - $xml = ''; - $this->priority = $this->topic_priority; - - if ($page) { - $page = $page - 1; - $page = $page * 40000; - $this->limit = " LIMIT {$page},40000"; - } else { - if ($this->limit < 1) $this->limit = false; - if ($this->limit) { - $this->limit = " LIMIT 0," . $this->limit; - } else { - $this->limit = ''; - } - } - - if (!$forums = $datastore->get('cat_forums')) { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } - - $not_forums_id = $forums['not_auth_forums']['guest_view']; - $ignore_forum_sql = ($not_forums_id) ? "WHERE forum_id NOT IN($not_forums_id)" : ''; - - $sql = DB()->sql_query("SELECT topic_id, topic_title, topic_time FROM " . BB_TOPICS . " " . $ignore_forum_sql . " ORDER BY topic_time ASC" . $this->limit); - - while ($row = DB()->sql_fetchrow($sql)) { - if (function_exists('seo_url')) $loc = $this->home . seo_url(TOPIC_URL . $row['topic_id'], $row['topic_title']); - else $loc = $this->home . TOPIC_URL . $row['topic_id']; - $xml .= $this->get_xml($loc, date('c', $row['topic_time'])); - } - - return $xml; - } - - function get_static () { - global $bb_cfg; - - $xml = ''; - $lm = date('c'); - $this->priority = $this->stat_priority; - - if (isset($bb_cfg['static_sitemap'])) { - $static_url = preg_replace("/\s/", '', $bb_cfg['static_sitemap']); //вырезаем переносы строк - preg_match_all('#(https?://[\w-]+[\.\w-]+/((?!https?://)[\w- ./?%&=])+)#', $static_url, $out); - - $static_url = count($out['0']); - if ($static_url > 0) { - foreach ($out['0'] as $url) { - $loc = $url; - $xml .= $this->get_xml($loc, $lm); - } - } - } - - return $xml; - } - - function get_xml ($loc, $lm) { - $xml = "\t\n"; - $xml .= "\t\t$loc\n"; - $xml .= "\t\t$lm\n"; - $xml .= "\t\t" . $this->priority . "\n"; - $xml .= "\t\n"; - - return $xml; - } - - function send_url ($url, $map) { - $data = false; - $file = $url.urlencode($map); - - if (function_exists('curl_init')) { - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $file); - curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); - - $data = curl_exec($ch); - curl_close($ch); - - return $data; - } else { - return @file_get_contents($file); - } - } - - function create () { - $row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS); - - if (!$this->limit) $this->limit = $row['count']; - if ($this->limit > 40000) { - $pages_count = @ceil($row['count'] / 40000); - - $sitemap = $this->build_index($pages_count); - $handler = fopen(SITEMAP_DIR. "sitemap.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap.xml", 0666); - - $sitemap = $this->build_stat(); - $handler = fopen(SITEMAP_DIR. "sitemap1.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap.xml", 0666); - - for ($i = 0; $i < $pages_count; $i++) { - $t = $i + 2; - $n = $i + 1; - - $sitemap = $this->build_map_topic($n); - $handler = fopen(SITEMAP_DIR. "sitemap{$t}.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap{$t}.xml", 0666); - } - } else { - $sitemap = $this->build_map(); - $handler = fopen(SITEMAP_DIR. "sitemap.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap.xml", 0666); - } - - $params['sitemap_time'] = TIMENOW; - bb_update_config($params); - } -} \ No newline at end of file diff --git a/library/includes/classes/utf8.php b/library/includes/classes/utf8.php deleted file mode 100644 index af5bfb2ae..000000000 --- a/library/includes/classes/utf8.php +++ /dev/null @@ -1,4074 +0,0 @@ - = 5.3.x - * - * In Russian: - * - * Поддержка UTF-8 в PHP 5. - * - * Возможности и преимущества использования этого класса - * * Совместимость с интерфейсом стандартных PHP функций, работающих с однобайтовыми кодировками - * * Возможность работы без PHP расширений ICONV и MBSTRING, если они есть, то активно используются! - * * Полезные функции, отсутствующие в ICONV и MBSTRING - * * Методы, которые принимают и возвращают строку, умеют принимать и возвращать null (удобно при выборках значений из базы данных) - * * Несколько методов умеют обрабатывать массивы рекурсивно - * * Единый интерфейс и инкапсуляция (можно унаследоваться и переопределить методы) - * * Высокая производительность, надёжность и качественный код - * * PHP >= 5.3.x - * - * Example: - * $s = 'Hello, Привет'; - * if (UTF8::is_utf8($s)) echo UTF8::strlen($s); - * - * UTF-8 encoding scheme: - * 2^7 0x00000000 — 0x0000007F 0xxxxxxx - * 2^11 0x00000080 — 0x000007FF 110xxxxx 10xxxxxx - * 2^16 0x00000800 — 0x0000FFFF 1110xxxx 10xxxxxx 10xxxxxx - * 2^21 0x00010000 — 0x001FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - * 1-4 bytes length: 2^7 + 2^11 + 2^16 + 2^21 = 2 164 864 - * - * If I was a owner of the world, I would leave only 2 encoding: UTF-8 and UTF-32 ;-) - * - * Useful links - * http://ru.wikipedia.org/wiki/UTF8 - * http://www.madore.org/~david/misc/unitest/ A Unicode Test Page - * http://www.unicode.org/ - * http://www.unicode.org/reports/ - * http://www.unicode.org/reports/tr10/ Unicode Collation Algorithm - * http://www.unicode.org/Public/UCA/6.0.0/ Unicode Collation Algorithm - * http://www.unicode.org/reports/tr6/ A Standard Compression Scheme for Unicode - * http://www.fileformat.info/info/unicode/char/search.htm Unicode Character Search - * - * @link http://code.google.com/p/php5-utf8/ - * @license http://creativecommons.org/licenses/by-sa/3.0/ - * @author Nasibullin Rinat - * @version 2.2.2 - */ -class UTF8 -{ - #REPLACEMENT CHARACTER (for broken char) - const REPLACEMENT_CHAR = "\xEF\xBF\xBD"; #U+FFFD - - /** - * Regular expression for a character in UTF-8 without the use of a flag /u - * @deprecated Instead, use a dot (".") and the flag /u, it works faster! - * @var string - */ - public static $char_re = ' [\x09\x0A\x0D\x20-\x7E] # ASCII strict - # [\x00-\x7F] # ASCII non-strict (including control chars) - | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte - | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs - | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte - | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates - | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 - | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 - | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 - '; - - /** - * Combining diactrical marks (Unicode 5.1). - * - * For example, russian letters in composed form: "Ё" (U+0401), "Й" (U+0419), - * decomposed form: (U+0415 U+0308), (U+0418 U+0306) - * - * @link http://www.unicode.org/charts/PDF/U0300.pdf - * @link http://www.unicode.org/charts/PDF/U1DC0.pdf - * @link http://www.unicode.org/charts/PDF/UFE20.pdf - * @var string - */ - #public static $diactrical_re = '\p{M}'; #alternative, but only with /u flag - public static $diactrical_re = ' \xcc[\x80-\xb9]|\xcd[\x80-\xaf] #UNICODE range: U+0300 — U+036F (for letters) - | \xe2\x83[\x90-\xbf] #UNICODE range: U+20D0 — U+20FF (for symbols) - | \xe1\xb7[\x80-\xbf] #UNICODE range: U+1DC0 — U+1DFF (supplement) - | \xef\xb8[\xa0-\xaf] #UNICODE range: U+FE20 — U+FE2F (combining half marks) - '; - - /** - * @var array - */ - public static $html_special_chars_table = array( - '"' => "\x22", #U+0022 ["] " quotation mark = APL quote - '&' => "\x26", #U+0026 [&] & ampersand - '<' => "\x3c", #U+003C [<] < less-than sign - '>' => "\x3e", #U+003E [>] > greater-than sign - ); - - /** - * @link http://www.fileformat.info/format/w3c/entitytest.htm?sort=Unicode%20Character HTML Entity Browser Test Page - * @var array - */ - public static $html_entity_table = array( - #Latin-1 Entities: - ' ' => "\xc2\xa0", #U+00A0 [ ] no-break space = non-breaking space - '¡' => "\xc2\xa1", #U+00A1 [¡] inverted exclamation mark - '¢' => "\xc2\xa2", #U+00A2 [¢] cent sign - '£' => "\xc2\xa3", #U+00A3 [£] pound sign - '¤' => "\xc2\xa4", #U+00A4 [¤] currency sign - '¥' => "\xc2\xa5", #U+00A5 [¥] yen sign = yuan sign - '¦' => "\xc2\xa6", #U+00A6 [¦] broken bar = broken vertical bar - '§' => "\xc2\xa7", #U+00A7 [§] section sign - '¨' => "\xc2\xa8", #U+00A8 [¨] diaeresis = spacing diaeresis - '©' => "\xc2\xa9", #U+00A9 [©] copyright sign - 'ª' => "\xc2\xaa", #U+00AA [ª] feminine ordinal indicator - '«' => "\xc2\xab", #U+00AB [«] left-pointing double angle quotation mark = left pointing guillemet - '¬' => "\xc2\xac", #U+00AC [¬] not sign - '­' => "\xc2\xad", #U+00AD [ ] soft hyphen = discretionary hyphen - '®' => "\xc2\xae", #U+00AE [®] registered sign = registered trade mark sign - '¯' => "\xc2\xaf", #U+00AF [¯] macron = spacing macron = overline = APL overbar - '°' => "\xc2\xb0", #U+00B0 [°] degree sign - '±' => "\xc2\xb1", #U+00B1 [±] plus-minus sign = plus-or-minus sign - '²' => "\xc2\xb2", #U+00B2 [²] superscript two = superscript digit two = squared - '³' => "\xc2\xb3", #U+00B3 [³] superscript three = superscript digit three = cubed - '´' => "\xc2\xb4", #U+00B4 [´] acute accent = spacing acute - 'µ' => "\xc2\xb5", #U+00B5 [µ] micro sign - '¶' => "\xc2\xb6", #U+00B6 [¶] pilcrow sign = paragraph sign - '·' => "\xc2\xb7", #U+00B7 [·] middle dot = Georgian comma = Greek middle dot - '¸' => "\xc2\xb8", #U+00B8 [¸] cedilla = spacing cedilla - '¹' => "\xc2\xb9", #U+00B9 [¹] superscript one = superscript digit one - 'º' => "\xc2\xba", #U+00BA [º] masculine ordinal indicator - '»' => "\xc2\xbb", #U+00BB [»] right-pointing double angle quotation mark = right pointing guillemet - '¼' => "\xc2\xbc", #U+00BC [¼] vulgar fraction one quarter = fraction one quarter - '½' => "\xc2\xbd", #U+00BD [½] vulgar fraction one half = fraction one half - '¾' => "\xc2\xbe", #U+00BE [¾] vulgar fraction three quarters = fraction three quarters - '¿' => "\xc2\xbf", #U+00BF [¿] inverted question mark = turned question mark - #Latin capital letter - 'À' => "\xc3\x80", #Latin capital letter A with grave = Latin capital letter A grave - 'Á' => "\xc3\x81", #Latin capital letter A with acute - 'Â' => "\xc3\x82", #Latin capital letter A with circumflex - 'Ã' => "\xc3\x83", #Latin capital letter A with tilde - 'Ä' => "\xc3\x84", #Latin capital letter A with diaeresis - 'Å' => "\xc3\x85", #Latin capital letter A with ring above = Latin capital letter A ring - 'Æ' => "\xc3\x86", #Latin capital letter AE = Latin capital ligature AE - 'Ç' => "\xc3\x87", #Latin capital letter C with cedilla - 'È' => "\xc3\x88", #Latin capital letter E with grave - 'É' => "\xc3\x89", #Latin capital letter E with acute - 'Ê' => "\xc3\x8a", #Latin capital letter E with circumflex - 'Ë' => "\xc3\x8b", #Latin capital letter E with diaeresis - 'Ì' => "\xc3\x8c", #Latin capital letter I with grave - 'Í' => "\xc3\x8d", #Latin capital letter I with acute - 'Î' => "\xc3\x8e", #Latin capital letter I with circumflex - 'Ï' => "\xc3\x8f", #Latin capital letter I with diaeresis - 'Ð' => "\xc3\x90", #Latin capital letter ETH - 'Ñ' => "\xc3\x91", #Latin capital letter N with tilde - 'Ò' => "\xc3\x92", #Latin capital letter O with grave - 'Ó' => "\xc3\x93", #Latin capital letter O with acute - 'Ô' => "\xc3\x94", #Latin capital letter O with circumflex - 'Õ' => "\xc3\x95", #Latin capital letter O with tilde - 'Ö' => "\xc3\x96", #Latin capital letter O with diaeresis - '×' => "\xc3\x97", #U+00D7 [×] multiplication sign - 'Ø' => "\xc3\x98", #Latin capital letter O with stroke = Latin capital letter O slash - 'Ù' => "\xc3\x99", #Latin capital letter U with grave - 'Ú' => "\xc3\x9a", #Latin capital letter U with acute - 'Û' => "\xc3\x9b", #Latin capital letter U with circumflex - 'Ü' => "\xc3\x9c", #Latin capital letter U with diaeresis - 'Ý' => "\xc3\x9d", #Latin capital letter Y with acute - 'Þ' => "\xc3\x9e", #Latin capital letter THORN - #Latin small letter - 'ß' => "\xc3\x9f", #Latin small letter sharp s = ess-zed - 'à' => "\xc3\xa0", #Latin small letter a with grave = Latin small letter a grave - 'á' => "\xc3\xa1", #Latin small letter a with acute - 'â' => "\xc3\xa2", #Latin small letter a with circumflex - 'ã' => "\xc3\xa3", #Latin small letter a with tilde - 'ä' => "\xc3\xa4", #Latin small letter a with diaeresis - 'å' => "\xc3\xa5", #Latin small letter a with ring above = Latin small letter a ring - 'æ' => "\xc3\xa6", #Latin small letter ae = Latin small ligature ae - 'ç' => "\xc3\xa7", #Latin small letter c with cedilla - 'è' => "\xc3\xa8", #Latin small letter e with grave - 'é' => "\xc3\xa9", #Latin small letter e with acute - 'ê' => "\xc3\xaa", #Latin small letter e with circumflex - 'ë' => "\xc3\xab", #Latin small letter e with diaeresis - 'ì' => "\xc3\xac", #Latin small letter i with grave - 'í' => "\xc3\xad", #Latin small letter i with acute - 'î' => "\xc3\xae", #Latin small letter i with circumflex - 'ï' => "\xc3\xaf", #Latin small letter i with diaeresis - 'ð' => "\xc3\xb0", #Latin small letter eth - 'ñ' => "\xc3\xb1", #Latin small letter n with tilde - 'ò' => "\xc3\xb2", #Latin small letter o with grave - 'ó' => "\xc3\xb3", #Latin small letter o with acute - 'ô' => "\xc3\xb4", #Latin small letter o with circumflex - 'õ' => "\xc3\xb5", #Latin small letter o with tilde - 'ö' => "\xc3\xb6", #Latin small letter o with diaeresis - '÷' => "\xc3\xb7", #U+00F7 [÷] division sign - 'ø' => "\xc3\xb8", #Latin small letter o with stroke = Latin small letter o slash - 'ù' => "\xc3\xb9", #Latin small letter u with grave - 'ú' => "\xc3\xba", #Latin small letter u with acute - 'û' => "\xc3\xbb", #Latin small letter u with circumflex - 'ü' => "\xc3\xbc", #Latin small letter u with diaeresis - 'ý' => "\xc3\xbd", #Latin small letter y with acute - 'þ' => "\xc3\xbe", #Latin small letter thorn - 'ÿ' => "\xc3\xbf", #Latin small letter y with diaeresis - #Symbols and Greek Letters: - 'ƒ' => "\xc6\x92", #U+0192 [ƒ] Latin small f with hook = function = florin - 'Α' => "\xce\x91", #Greek capital letter alpha - 'Β' => "\xce\x92", #Greek capital letter beta - 'Γ' => "\xce\x93", #Greek capital letter gamma - 'Δ' => "\xce\x94", #Greek capital letter delta - 'Ε' => "\xce\x95", #Greek capital letter epsilon - 'Ζ' => "\xce\x96", #Greek capital letter zeta - 'Η' => "\xce\x97", #Greek capital letter eta - 'Θ' => "\xce\x98", #Greek capital letter theta - 'Ι' => "\xce\x99", #Greek capital letter iota - 'Κ' => "\xce\x9a", #Greek capital letter kappa - 'Λ' => "\xce\x9b", #Greek capital letter lambda - 'Μ' => "\xce\x9c", #Greek capital letter mu - 'Ν' => "\xce\x9d", #Greek capital letter nu - 'Ξ' => "\xce\x9e", #Greek capital letter xi - 'Ο' => "\xce\x9f", #Greek capital letter omicron - 'Π' => "\xce\xa0", #Greek capital letter pi - 'Ρ' => "\xce\xa1", #Greek capital letter rho - 'Σ' => "\xce\xa3", #Greek capital letter sigma - 'Τ' => "\xce\xa4", #Greek capital letter tau - 'Υ' => "\xce\xa5", #Greek capital letter upsilon - 'Φ' => "\xce\xa6", #Greek capital letter phi - 'Χ' => "\xce\xa7", #Greek capital letter chi - 'Ψ' => "\xce\xa8", #Greek capital letter psi - 'Ω' => "\xce\xa9", #Greek capital letter omega - 'α' => "\xce\xb1", #Greek small letter alpha - 'β' => "\xce\xb2", #Greek small letter beta - 'γ' => "\xce\xb3", #Greek small letter gamma - 'δ' => "\xce\xb4", #Greek small letter delta - 'ε' => "\xce\xb5", #Greek small letter epsilon - 'ζ' => "\xce\xb6", #Greek small letter zeta - 'η' => "\xce\xb7", #Greek small letter eta - 'θ' => "\xce\xb8", #Greek small letter theta - 'ι' => "\xce\xb9", #Greek small letter iota - 'κ' => "\xce\xba", #Greek small letter kappa - 'λ' => "\xce\xbb", #Greek small letter lambda - 'μ' => "\xce\xbc", #Greek small letter mu - 'ν' => "\xce\xbd", #Greek small letter nu - 'ξ' => "\xce\xbe", #Greek small letter xi - 'ο' => "\xce\xbf", #Greek small letter omicron - 'π' => "\xcf\x80", #Greek small letter pi - 'ρ' => "\xcf\x81", #Greek small letter rho - 'ς' => "\xcf\x82", #Greek small letter final sigma - 'σ' => "\xcf\x83", #Greek small letter sigma - 'τ' => "\xcf\x84", #Greek small letter tau - 'υ' => "\xcf\x85", #Greek small letter upsilon - 'φ' => "\xcf\x86", #Greek small letter phi - 'χ' => "\xcf\x87", #Greek small letter chi - 'ψ' => "\xcf\x88", #Greek small letter psi - 'ω' => "\xcf\x89", #Greek small letter omega - 'ϑ'=> "\xcf\x91", #Greek small letter theta symbol - 'ϒ' => "\xcf\x92", #Greek upsilon with hook symbol - 'ϖ' => "\xcf\x96", #U+03D6 [ϖ] Greek pi symbol - - '•' => "\xe2\x80\xa2", #U+2022 [•] bullet = black small circle - '…' => "\xe2\x80\xa6", #U+2026 […] horizontal ellipsis = three dot leader - '′' => "\xe2\x80\xb2", #U+2032 [′] prime = minutes = feet (для обозначения минут и футов) - '″' => "\xe2\x80\xb3", #U+2033 [″] double prime = seconds = inches (для обозначения секунд и дюймов). - '‾' => "\xe2\x80\xbe", #U+203E [‾] overline = spacing overscore - '⁄' => "\xe2\x81\x84", #U+2044 [⁄] fraction slash - '℘' => "\xe2\x84\x98", #U+2118 [℘] script capital P = power set = Weierstrass p - 'ℑ' => "\xe2\x84\x91", #U+2111 [ℑ] blackletter capital I = imaginary part - 'ℜ' => "\xe2\x84\x9c", #U+211C [ℜ] blackletter capital R = real part symbol - '™' => "\xe2\x84\xa2", #U+2122 [™] trade mark sign - 'ℵ' => "\xe2\x84\xb5", #U+2135 [ℵ] alef symbol = first transfinite cardinal - '←' => "\xe2\x86\x90", #U+2190 [←] leftwards arrow - '↑' => "\xe2\x86\x91", #U+2191 [↑] upwards arrow - '→' => "\xe2\x86\x92", #U+2192 [→] rightwards arrow - '↓' => "\xe2\x86\x93", #U+2193 [↓] downwards arrow - '↔' => "\xe2\x86\x94", #U+2194 [↔] left right arrow - '↵' => "\xe2\x86\xb5", #U+21B5 [↵] downwards arrow with corner leftwards = carriage return - '⇐' => "\xe2\x87\x90", #U+21D0 [⇐] leftwards double arrow - '⇑' => "\xe2\x87\x91", #U+21D1 [⇑] upwards double arrow - '⇒' => "\xe2\x87\x92", #U+21D2 [⇒] rightwards double arrow - '⇓' => "\xe2\x87\x93", #U+21D3 [⇓] downwards double arrow - '⇔' => "\xe2\x87\x94", #U+21D4 [⇔] left right double arrow - '∀' => "\xe2\x88\x80", #U+2200 [∀] for all - '∂' => "\xe2\x88\x82", #U+2202 [∂] partial differential - '∃' => "\xe2\x88\x83", #U+2203 [∃] there exists - '∅' => "\xe2\x88\x85", #U+2205 [∅] empty set = null set = diameter - '∇' => "\xe2\x88\x87", #U+2207 [∇] nabla = backward difference - '∈' => "\xe2\x88\x88", #U+2208 [∈] element of - '∉' => "\xe2\x88\x89", #U+2209 [∉] not an element of - '∋' => "\xe2\x88\x8b", #U+220B [∋] contains as member - '∏' => "\xe2\x88\x8f", #U+220F [∏] n-ary product = product sign - '∑' => "\xe2\x88\x91", #U+2211 [∑] n-ary sumation - '−' => "\xe2\x88\x92", #U+2212 [−] minus sign - '∗' => "\xe2\x88\x97", #U+2217 [∗] asterisk operator - '√' => "\xe2\x88\x9a", #U+221A [√] square root = radical sign - '∝' => "\xe2\x88\x9d", #U+221D [∝] proportional to - '∞' => "\xe2\x88\x9e", #U+221E [∞] infinity - '∠' => "\xe2\x88\xa0", #U+2220 [∠] angle - '∧' => "\xe2\x88\xa7", #U+2227 [∧] logical and = wedge - '∨' => "\xe2\x88\xa8", #U+2228 [∨] logical or = vee - '∩' => "\xe2\x88\xa9", #U+2229 [∩] intersection = cap - '∪' => "\xe2\x88\xaa", #U+222A [∪] union = cup - '∫' => "\xe2\x88\xab", #U+222B [∫] integral - '∴' => "\xe2\x88\xb4", #U+2234 [∴] therefore - '∼' => "\xe2\x88\xbc", #U+223C [∼] tilde operator = varies with = similar to - '≅' => "\xe2\x89\x85", #U+2245 [≅] approximately equal to - '≈' => "\xe2\x89\x88", #U+2248 [≈] almost equal to = asymptotic to - '≠' => "\xe2\x89\xa0", #U+2260 [≠] not equal to - '≡' => "\xe2\x89\xa1", #U+2261 [≡] identical to - '≤' => "\xe2\x89\xa4", #U+2264 [≤] less-than or equal to - '≥' => "\xe2\x89\xa5", #U+2265 [≥] greater-than or equal to - '⊂' => "\xe2\x8a\x82", #U+2282 [⊂] subset of - '⊃' => "\xe2\x8a\x83", #U+2283 [⊃] superset of - '⊄' => "\xe2\x8a\x84", #U+2284 [⊄] not a subset of - '⊆' => "\xe2\x8a\x86", #U+2286 [⊆] subset of or equal to - '⊇' => "\xe2\x8a\x87", #U+2287 [⊇] superset of or equal to - '⊕' => "\xe2\x8a\x95", #U+2295 [⊕] circled plus = direct sum - '⊗' => "\xe2\x8a\x97", #U+2297 [⊗] circled times = vector product - '⊥' => "\xe2\x8a\xa5", #U+22A5 [⊥] up tack = orthogonal to = perpendicular - '⋅' => "\xe2\x8b\x85", #U+22C5 [⋅] dot operator - '⌈' => "\xe2\x8c\x88", #U+2308 [⌈] left ceiling = APL upstile - '⌉' => "\xe2\x8c\x89", #U+2309 [⌉] right ceiling - '⌊' => "\xe2\x8c\x8a", #U+230A [⌊] left floor = APL downstile - '⌋' => "\xe2\x8c\x8b", #U+230B [⌋] right floor - '⟨' => "\xe2\x8c\xa9", #U+2329 [〈] left-pointing angle bracket = bra - '⟩' => "\xe2\x8c\xaa", #U+232A [〉] right-pointing angle bracket = ket - '◊' => "\xe2\x97\x8a", #U+25CA [◊] lozenge - '♠' => "\xe2\x99\xa0", #U+2660 [♠] black spade suit - '♣' => "\xe2\x99\xa3", #U+2663 [♣] black club suit = shamrock - '♥' => "\xe2\x99\xa5", #U+2665 [♥] black heart suit = valentine - '♦' => "\xe2\x99\xa6", #U+2666 [♦] black diamond suit - #Other Special Characters: - 'Œ' => "\xc5\x92", #U+0152 [Œ] Latin capital ligature OE - 'œ' => "\xc5\x93", #U+0153 [œ] Latin small ligature oe - 'Š' => "\xc5\xa0", #U+0160 [Š] Latin capital letter S with caron - 'š' => "\xc5\xa1", #U+0161 [š] Latin small letter s with caron - 'Ÿ' => "\xc5\xb8", #U+0178 [Ÿ] Latin capital letter Y with diaeresis - 'ˆ' => "\xcb\x86", #U+02C6 [ˆ] modifier letter circumflex accent - '˜' => "\xcb\x9c", #U+02DC [˜] small tilde - ' ' => "\xe2\x80\x82", #U+2002 [ ] en space - ' ' => "\xe2\x80\x83", #U+2003 [ ] em space - ' ' => "\xe2\x80\x89", #U+2009 [ ] thin space - '‌' => "\xe2\x80\x8c", #U+200C [‌] zero width non-joiner - '‍' => "\xe2\x80\x8d", #U+200D [‍] zero width joiner - '‎' => "\xe2\x80\x8e", #U+200E [‎] left-to-right mark - '‏' => "\xe2\x80\x8f", #U+200F [‏] right-to-left mark - '–' => "\xe2\x80\x93", #U+2013 [–] en dash - '—' => "\xe2\x80\x94", #U+2014 [—] em dash - '‘' => "\xe2\x80\x98", #U+2018 [‘] left single quotation mark - '’' => "\xe2\x80\x99", #U+2019 [’] right single quotation mark (and apostrophe!) - '‚' => "\xe2\x80\x9a", #U+201A [‚] single low-9 quotation mark - '“' => "\xe2\x80\x9c", #U+201C [“] left double quotation mark - '”' => "\xe2\x80\x9d", #U+201D [”] right double quotation mark - '„' => "\xe2\x80\x9e", #U+201E [„] double low-9 quotation mark - '†' => "\xe2\x80\xa0", #U+2020 [†] dagger - '‡' => "\xe2\x80\xa1", #U+2021 [‡] double dagger - '‰' => "\xe2\x80\xb0", #U+2030 [‰] per mille sign - '‹' => "\xe2\x80\xb9", #U+2039 [‹] single left-pointing angle quotation mark - '›' => "\xe2\x80\xba", #U+203A [›] single right-pointing angle quotation mark - '€' => "\xe2\x82\xac", #U+20AC [€] euro sign - ); - - /** - * This table contains the data on how cp1259 characters map into Unicode (UTF-8). - * The cp1259 map describes standart tatarish cyrillic charset and based on the cp1251 table. - * cp1259 -- this is an outdated one byte encoding of the Tatar language, - * which includes all the Russian letters from cp1251. - * - * @link http://search.cpan.org/CPAN/authors/id/A/AM/AMICHAUER/Lingua-TT-Yanalif-0.08.tar.gz - * @link http://www.unicode.org/charts/PDF/U0400.pdf - */ - public static $cp1259_table = array( - #bytes from 0x00 to 0x7F (ASCII) saved as is - "\x80" => "\xd3\x98", #U+04d8 CYRILLIC CAPITAL LETTER SCHWA - "\x81" => "\xd0\x83", #U+0403 CYRILLIC CAPITAL LETTER GJE - "\x82" => "\xe2\x80\x9a", #U+201a SINGLE LOW-9 QUOTATION MARK - "\x83" => "\xd1\x93", #U+0453 CYRILLIC SMALL LETTER GJE - "\x84" => "\xe2\x80\x9e", #U+201e DOUBLE LOW-9 QUOTATION MARK - "\x85" => "\xe2\x80\xa6", #U+2026 HORIZONTAL ELLIPSIS - "\x86" => "\xe2\x80\xa0", #U+2020 DAGGER - "\x87" => "\xe2\x80\xa1", #U+2021 DOUBLE DAGGER - "\x88" => "\xe2\x82\xac", #U+20ac EURO SIGN - "\x89" => "\xe2\x80\xb0", #U+2030 PER MILLE SIGN - "\x8a" => "\xd3\xa8", #U+04e8 CYRILLIC CAPITAL LETTER BARRED O - "\x8b" => "\xe2\x80\xb9", #U+2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK - "\x8c" => "\xd2\xae", #U+04ae CYRILLIC CAPITAL LETTER STRAIGHT U - "\x8d" => "\xd2\x96", #U+0496 CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER - "\x8e" => "\xd2\xa2", #U+04a2 CYRILLIC CAPITAL LETTER EN WITH HOOK - "\x8f" => "\xd2\xba", #U+04ba CYRILLIC CAPITAL LETTER SHHA - "\x90" => "\xd3\x99", #U+04d9 CYRILLIC SMALL LETTER SCHWA - "\x91" => "\xe2\x80\x98", #U+2018 LEFT SINGLE QUOTATION MARK - "\x92" => "\xe2\x80\x99", #U+2019 RIGHT SINGLE QUOTATION MARK - "\x93" => "\xe2\x80\x9c", #U+201c LEFT DOUBLE QUOTATION MARK - "\x94" => "\xe2\x80\x9d", #U+201d RIGHT DOUBLE QUOTATION MARK - "\x95" => "\xe2\x80\xa2", #U+2022 BULLET - "\x96" => "\xe2\x80\x93", #U+2013 EN DASH - "\x97" => "\xe2\x80\x94", #U+2014 EM DASH - #"\x98" #UNDEFINED - "\x99" => "\xe2\x84\xa2", #U+2122 TRADE MARK SIGN - "\x9a" => "\xd3\xa9", #U+04e9 CYRILLIC SMALL LETTER BARRED O - "\x9b" => "\xe2\x80\xba", #U+203a SINGLE RIGHT-POINTING ANGLE QUOTATION MARK - "\x9c" => "\xd2\xaf", #U+04af CYRILLIC SMALL LETTER STRAIGHT U - "\x9d" => "\xd2\x97", #U+0497 CYRILLIC SMALL LETTER ZHE WITH DESCENDER - "\x9e" => "\xd2\xa3", #U+04a3 CYRILLIC SMALL LETTER EN WITH HOOK - "\x9f" => "\xd2\xbb", #U+04bb CYRILLIC SMALL LETTER SHHA - "\xa0" => "\xc2\xa0", #U+00a0 NO-BREAK SPACE - "\xa1" => "\xd0\x8e", #U+040e CYRILLIC CAPITAL LETTER SHORT U - "\xa2" => "\xd1\x9e", #U+045e CYRILLIC SMALL LETTER SHORT U - "\xa3" => "\xd0\x88", #U+0408 CYRILLIC CAPITAL LETTER JE - "\xa4" => "\xc2\xa4", #U+00a4 CURRENCY SIGN - "\xa5" => "\xd2\x90", #U+0490 CYRILLIC CAPITAL LETTER GHE WITH UPTURN - "\xa6" => "\xc2\xa6", #U+00a6 BROKEN BAR - "\xa7" => "\xc2\xa7", #U+00a7 SECTION SIGN - "\xa8" => "\xd0\x81", #U+0401 CYRILLIC CAPITAL LETTER IO - "\xa9" => "\xc2\xa9", #U+00a9 COPYRIGHT SIGN - "\xaa" => "\xd0\x84", #U+0404 CYRILLIC CAPITAL LETTER UKRAINIAN IE - "\xab" => "\xc2\xab", #U+00ab LEFT-POINTING DOUBLE ANGLE QUOTATION MARK - "\xac" => "\xc2\xac", #U+00ac NOT SIGN - "\xad" => "\xc2\xad", #U+00ad SOFT HYPHEN - "\xae" => "\xc2\xae", #U+00ae REGISTERED SIGN - "\xaf" => "\xd0\x87", #U+0407 CYRILLIC CAPITAL LETTER YI - "\xb0" => "\xc2\xb0", #U+00b0 DEGREE SIGN - "\xb1" => "\xc2\xb1", #U+00b1 PLUS-MINUS SIGN - "\xb2" => "\xd0\x86", #U+0406 CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I - "\xb3" => "\xd1\x96", #U+0456 CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I - "\xb4" => "\xd2\x91", #U+0491 CYRILLIC SMALL LETTER GHE WITH UPTURN - "\xb5" => "\xc2\xb5", #U+00b5 MICRO SIGN - "\xb6" => "\xc2\xb6", #U+00b6 PILCROW SIGN - "\xb7" => "\xc2\xb7", #U+00b7 MIDDLE DOT - "\xb8" => "\xd1\x91", #U+0451 CYRILLIC SMALL LETTER IO - "\xb9" => "\xe2\x84\x96", #U+2116 NUMERO SIGN - "\xba" => "\xd1\x94", #U+0454 CYRILLIC SMALL LETTER UKRAINIAN IE - "\xbb" => "\xc2\xbb", #U+00bb RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK - "\xbc" => "\xd1\x98", #U+0458 CYRILLIC SMALL LETTER JE - "\xbd" => "\xd0\x85", #U+0405 CYRILLIC CAPITAL LETTER DZE - "\xbe" => "\xd1\x95", #U+0455 CYRILLIC SMALL LETTER DZE - "\xbf" => "\xd1\x97", #U+0457 CYRILLIC SMALL LETTER YI - "\xc0" => "\xd0\x90", #U+0410 CYRILLIC CAPITAL LETTER A - "\xc1" => "\xd0\x91", #U+0411 CYRILLIC CAPITAL LETTER BE - "\xc2" => "\xd0\x92", #U+0412 CYRILLIC CAPITAL LETTER VE - "\xc3" => "\xd0\x93", #U+0413 CYRILLIC CAPITAL LETTER GHE - "\xc4" => "\xd0\x94", #U+0414 CYRILLIC CAPITAL LETTER DE - "\xc5" => "\xd0\x95", #U+0415 CYRILLIC CAPITAL LETTER IE - "\xc6" => "\xd0\x96", #U+0416 CYRILLIC CAPITAL LETTER ZHE - "\xc7" => "\xd0\x97", #U+0417 CYRILLIC CAPITAL LETTER ZE - "\xc8" => "\xd0\x98", #U+0418 CYRILLIC CAPITAL LETTER I - "\xc9" => "\xd0\x99", #U+0419 CYRILLIC CAPITAL LETTER SHORT I - "\xca" => "\xd0\x9a", #U+041a CYRILLIC CAPITAL LETTER KA - "\xcb" => "\xd0\x9b", #U+041b CYRILLIC CAPITAL LETTER EL - "\xcc" => "\xd0\x9c", #U+041c CYRILLIC CAPITAL LETTER EM - "\xcd" => "\xd0\x9d", #U+041d CYRILLIC CAPITAL LETTER EN - "\xce" => "\xd0\x9e", #U+041e CYRILLIC CAPITAL LETTER O - "\xcf" => "\xd0\x9f", #U+041f CYRILLIC CAPITAL LETTER PE - "\xd0" => "\xd0\xa0", #U+0420 CYRILLIC CAPITAL LETTER ER - "\xd1" => "\xd0\xa1", #U+0421 CYRILLIC CAPITAL LETTER ES - "\xd2" => "\xd0\xa2", #U+0422 CYRILLIC CAPITAL LETTER TE - "\xd3" => "\xd0\xa3", #U+0423 CYRILLIC CAPITAL LETTER U - "\xd4" => "\xd0\xa4", #U+0424 CYRILLIC CAPITAL LETTER EF - "\xd5" => "\xd0\xa5", #U+0425 CYRILLIC CAPITAL LETTER HA - "\xd6" => "\xd0\xa6", #U+0426 CYRILLIC CAPITAL LETTER TSE - "\xd7" => "\xd0\xa7", #U+0427 CYRILLIC CAPITAL LETTER CHE - "\xd8" => "\xd0\xa8", #U+0428 CYRILLIC CAPITAL LETTER SHA - "\xd9" => "\xd0\xa9", #U+0429 CYRILLIC CAPITAL LETTER SHCHA - "\xda" => "\xd0\xaa", #U+042a CYRILLIC CAPITAL LETTER HARD SIGN - "\xdb" => "\xd0\xab", #U+042b CYRILLIC CAPITAL LETTER YERU - "\xdc" => "\xd0\xac", #U+042c CYRILLIC CAPITAL LETTER SOFT SIGN - "\xdd" => "\xd0\xad", #U+042d CYRILLIC CAPITAL LETTER E - "\xde" => "\xd0\xae", #U+042e CYRILLIC CAPITAL LETTER YU - "\xdf" => "\xd0\xaf", #U+042f CYRILLIC CAPITAL LETTER YA - "\xe0" => "\xd0\xb0", #U+0430 CYRILLIC SMALL LETTER A - "\xe1" => "\xd0\xb1", #U+0431 CYRILLIC SMALL LETTER BE - "\xe2" => "\xd0\xb2", #U+0432 CYRILLIC SMALL LETTER VE - "\xe3" => "\xd0\xb3", #U+0433 CYRILLIC SMALL LETTER GHE - "\xe4" => "\xd0\xb4", #U+0434 CYRILLIC SMALL LETTER DE - "\xe5" => "\xd0\xb5", #U+0435 CYRILLIC SMALL LETTER IE - "\xe6" => "\xd0\xb6", #U+0436 CYRILLIC SMALL LETTER ZHE - "\xe7" => "\xd0\xb7", #U+0437 CYRILLIC SMALL LETTER ZE - "\xe8" => "\xd0\xb8", #U+0438 CYRILLIC SMALL LETTER I - "\xe9" => "\xd0\xb9", #U+0439 CYRILLIC SMALL LETTER SHORT I - "\xea" => "\xd0\xba", #U+043a CYRILLIC SMALL LETTER KA - "\xeb" => "\xd0\xbb", #U+043b CYRILLIC SMALL LETTER EL - "\xec" => "\xd0\xbc", #U+043c CYRILLIC SMALL LETTER EM - "\xed" => "\xd0\xbd", #U+043d CYRILLIC SMALL LETTER EN - "\xee" => "\xd0\xbe", #U+043e CYRILLIC SMALL LETTER O - "\xef" => "\xd0\xbf", #U+043f CYRILLIC SMALL LETTER PE - "\xf0" => "\xd1\x80", #U+0440 CYRILLIC SMALL LETTER ER - "\xf1" => "\xd1\x81", #U+0441 CYRILLIC SMALL LETTER ES - "\xf2" => "\xd1\x82", #U+0442 CYRILLIC SMALL LETTER TE - "\xf3" => "\xd1\x83", #U+0443 CYRILLIC SMALL LETTER U - "\xf4" => "\xd1\x84", #U+0444 CYRILLIC SMALL LETTER EF - "\xf5" => "\xd1\x85", #U+0445 CYRILLIC SMALL LETTER HA - "\xf6" => "\xd1\x86", #U+0446 CYRILLIC SMALL LETTER TSE - "\xf7" => "\xd1\x87", #U+0447 CYRILLIC SMALL LETTER CHE - "\xf8" => "\xd1\x88", #U+0448 CYRILLIC SMALL LETTER SHA - "\xf9" => "\xd1\x89", #U+0449 CYRILLIC SMALL LETTER SHCHA - "\xfa" => "\xd1\x8a", #U+044a CYRILLIC SMALL LETTER HARD SIGN - "\xfb" => "\xd1\x8b", #U+044b CYRILLIC SMALL LETTER YERU - "\xfc" => "\xd1\x8c", #U+044c CYRILLIC SMALL LETTER SOFT SIGN - "\xfd" => "\xd1\x8d", #U+044d CYRILLIC SMALL LETTER E - "\xfe" => "\xd1\x8e", #U+044e CYRILLIC SMALL LETTER YU - "\xff" => "\xd1\x8f", #U+044f CYRILLIC SMALL LETTER YA - ); - - /** - * UTF-8 Case lookup table - * - * This lookuptable defines the upper case letters to their correspponding - * lower case letter in UTF-8 - * - * @author Andreas Gohr - */ - public static $convert_case_table = array( - #CASE_UPPER => case_lower - "\x41" => "\x61", #A a - "\x42" => "\x62", #B b - "\x43" => "\x63", #C c - "\x44" => "\x64", #D d - "\x45" => "\x65", #E e - "\x46" => "\x66", #F f - "\x47" => "\x67", #G g - "\x48" => "\x68", #H h - "\x49" => "\x69", #I i - "\x4a" => "\x6a", #J j - "\x4b" => "\x6b", #K k - "\x4c" => "\x6c", #L l - "\x4d" => "\x6d", #M m - "\x4e" => "\x6e", #N n - "\x4f" => "\x6f", #O o - "\x50" => "\x70", #P p - "\x51" => "\x71", #Q q - "\x52" => "\x72", #R r - "\x53" => "\x73", #S s - "\x54" => "\x74", #T t - "\x55" => "\x75", #U u - "\x56" => "\x76", #V v - "\x57" => "\x77", #W w - "\x58" => "\x78", #X x - "\x59" => "\x79", #Y y - "\x5a" => "\x7a", #Z z - "\xc3\x80" => "\xc3\xa0", - "\xc3\x81" => "\xc3\xa1", - "\xc3\x82" => "\xc3\xa2", - "\xc3\x83" => "\xc3\xa3", - "\xc3\x84" => "\xc3\xa4", - "\xc3\x85" => "\xc3\xa5", - "\xc3\x86" => "\xc3\xa6", - "\xc3\x87" => "\xc3\xa7", - "\xc3\x88" => "\xc3\xa8", - "\xc3\x89" => "\xc3\xa9", - "\xc3\x8a" => "\xc3\xaa", - "\xc3\x8b" => "\xc3\xab", - "\xc3\x8c" => "\xc3\xac", - "\xc3\x8d" => "\xc3\xad", - "\xc3\x8e" => "\xc3\xae", - "\xc3\x8f" => "\xc3\xaf", - "\xc3\x90" => "\xc3\xb0", - "\xc3\x91" => "\xc3\xb1", - "\xc3\x92" => "\xc3\xb2", - "\xc3\x93" => "\xc3\xb3", - "\xc3\x94" => "\xc3\xb4", - "\xc3\x95" => "\xc3\xb5", - "\xc3\x96" => "\xc3\xb6", - "\xc3\x98" => "\xc3\xb8", - "\xc3\x99" => "\xc3\xb9", - "\xc3\x9a" => "\xc3\xba", - "\xc3\x9b" => "\xc3\xbb", - "\xc3\x9c" => "\xc3\xbc", - "\xc3\x9d" => "\xc3\xbd", - "\xc3\x9e" => "\xc3\xbe", - "\xc4\x80" => "\xc4\x81", - "\xc4\x82" => "\xc4\x83", - "\xc4\x84" => "\xc4\x85", - "\xc4\x86" => "\xc4\x87", - "\xc4\x88" => "\xc4\x89", - "\xc4\x8a" => "\xc4\x8b", - "\xc4\x8c" => "\xc4\x8d", - "\xc4\x8e" => "\xc4\x8f", - "\xc4\x90" => "\xc4\x91", - "\xc4\x92" => "\xc4\x93", - "\xc4\x94" => "\xc4\x95", - "\xc4\x96" => "\xc4\x97", - "\xc4\x98" => "\xc4\x99", - "\xc4\x9a" => "\xc4\x9b", - "\xc4\x9c" => "\xc4\x9d", - "\xc4\x9e" => "\xc4\x9f", - "\xc4\xa0" => "\xc4\xa1", - "\xc4\xa2" => "\xc4\xa3", - "\xc4\xa4" => "\xc4\xa5", - "\xc4\xa6" => "\xc4\xa7", - "\xc4\xa8" => "\xc4\xa9", - "\xc4\xaa" => "\xc4\xab", - "\xc4\xac" => "\xc4\xad", - "\xc4\xae" => "\xc4\xaf", - "\xc4\xb2" => "\xc4\xb3", - "\xc4\xb4" => "\xc4\xb5", - "\xc4\xb6" => "\xc4\xb7", - "\xc4\xb9" => "\xc4\xba", - "\xc4\xbb" => "\xc4\xbc", - "\xc4\xbd" => "\xc4\xbe", - "\xc4\xbf" => "\xc5\x80", - "\xc5\x81" => "\xc5\x82", - "\xc5\x83" => "\xc5\x84", - "\xc5\x85" => "\xc5\x86", - "\xc5\x87" => "\xc5\x88", - "\xc5\x8a" => "\xc5\x8b", - "\xc5\x8c" => "\xc5\x8d", - "\xc5\x8e" => "\xc5\x8f", - "\xc5\x90" => "\xc5\x91", - "\xc5\x92" => "\xc5\x93", - "\xc5\x94" => "\xc5\x95", - "\xc5\x96" => "\xc5\x97", - "\xc5\x98" => "\xc5\x99", - "\xc5\x9a" => "\xc5\x9b", - "\xc5\x9c" => "\xc5\x9d", - "\xc5\x9e" => "\xc5\x9f", - "\xc5\xa0" => "\xc5\xa1", - "\xc5\xa2" => "\xc5\xa3", - "\xc5\xa4" => "\xc5\xa5", - "\xc5\xa6" => "\xc5\xa7", - "\xc5\xa8" => "\xc5\xa9", - "\xc5\xaa" => "\xc5\xab", - "\xc5\xac" => "\xc5\xad", - "\xc5\xae" => "\xc5\xaf", - "\xc5\xb0" => "\xc5\xb1", - "\xc5\xb2" => "\xc5\xb3", - "\xc5\xb4" => "\xc5\xb5", - "\xc5\xb6" => "\xc5\xb7", - "\xc5\xb8" => "\xc3\xbf", - "\xc5\xb9" => "\xc5\xba", - "\xc5\xbb" => "\xc5\xbc", - "\xc5\xbd" => "\xc5\xbe", - "\xc6\x81" => "\xc9\x93", - "\xc6\x82" => "\xc6\x83", - "\xc6\x84" => "\xc6\x85", - "\xc6\x86" => "\xc9\x94", - "\xc6\x87" => "\xc6\x88", - "\xc6\x89" => "\xc9\x96", - "\xc6\x8a" => "\xc9\x97", - "\xc6\x8b" => "\xc6\x8c", - "\xc6\x8e" => "\xc7\x9d", - "\xc6\x8f" => "\xc9\x99", - "\xc6\x90" => "\xc9\x9b", - "\xc6\x91" => "\xc6\x92", - "\xc6\x94" => "\xc9\xa3", - "\xc6\x96" => "\xc9\xa9", - "\xc6\x97" => "\xc9\xa8", - "\xc6\x98" => "\xc6\x99", - "\xc6\x9c" => "\xc9\xaf", - "\xc6\x9d" => "\xc9\xb2", - "\xc6\x9f" => "\xc9\xb5", - "\xc6\xa0" => "\xc6\xa1", - "\xc6\xa2" => "\xc6\xa3", - "\xc6\xa4" => "\xc6\xa5", - "\xc6\xa6" => "\xca\x80", - "\xc6\xa7" => "\xc6\xa8", - "\xc6\xa9" => "\xca\x83", - "\xc6\xac" => "\xc6\xad", - "\xc6\xae" => "\xca\x88", - "\xc6\xaf" => "\xc6\xb0", - "\xc6\xb1" => "\xca\x8a", - "\xc6\xb2" => "\xca\x8b", - "\xc6\xb3" => "\xc6\xb4", - "\xc6\xb5" => "\xc6\xb6", - "\xc6\xb7" => "\xca\x92", - "\xc6\xb8" => "\xc6\xb9", - "\xc6\xbc" => "\xc6\xbd", - "\xc7\x85" => "\xc7\x86", - "\xc7\x88" => "\xc7\x89", - "\xc7\x8b" => "\xc7\x8c", - "\xc7\x8d" => "\xc7\x8e", - "\xc7\x8f" => "\xc7\x90", - "\xc7\x91" => "\xc7\x92", - "\xc7\x93" => "\xc7\x94", - "\xc7\x95" => "\xc7\x96", - "\xc7\x97" => "\xc7\x98", - "\xc7\x99" => "\xc7\x9a", - "\xc7\x9b" => "\xc7\x9c", - "\xc7\x9e" => "\xc7\x9f", - "\xc7\xa0" => "\xc7\xa1", - "\xc7\xa2" => "\xc7\xa3", - "\xc7\xa4" => "\xc7\xa5", - "\xc7\xa6" => "\xc7\xa7", - "\xc7\xa8" => "\xc7\xa9", - "\xc7\xaa" => "\xc7\xab", - "\xc7\xac" => "\xc7\xad", - "\xc7\xae" => "\xc7\xaf", - "\xc7\xb2" => "\xc7\xb3", - "\xc7\xb4" => "\xc7\xb5", - "\xc7\xb6" => "\xc6\x95", - "\xc7\xb7" => "\xc6\xbf", - "\xc7\xb8" => "\xc7\xb9", - "\xc7\xba" => "\xc7\xbb", - "\xc7\xbc" => "\xc7\xbd", - "\xc7\xbe" => "\xc7\xbf", - "\xc8\x80" => "\xc8\x81", - "\xc8\x82" => "\xc8\x83", - "\xc8\x84" => "\xc8\x85", - "\xc8\x86" => "\xc8\x87", - "\xc8\x88" => "\xc8\x89", - "\xc8\x8a" => "\xc8\x8b", - "\xc8\x8c" => "\xc8\x8d", - "\xc8\x8e" => "\xc8\x8f", - "\xc8\x90" => "\xc8\x91", - "\xc8\x92" => "\xc8\x93", - "\xc8\x94" => "\xc8\x95", - "\xc8\x96" => "\xc8\x97", - "\xc8\x98" => "\xc8\x99", - "\xc8\x9a" => "\xc8\x9b", - "\xc8\x9c" => "\xc8\x9d", - "\xc8\x9e" => "\xc8\x9f", - "\xc8\xa0" => "\xc6\x9e", - "\xc8\xa2" => "\xc8\xa3", - "\xc8\xa4" => "\xc8\xa5", - "\xc8\xa6" => "\xc8\xa7", - "\xc8\xa8" => "\xc8\xa9", - "\xc8\xaa" => "\xc8\xab", - "\xc8\xac" => "\xc8\xad", - "\xc8\xae" => "\xc8\xaf", - "\xc8\xb0" => "\xc8\xb1", - "\xc8\xb2" => "\xc8\xb3", - "\xce\x86" => "\xce\xac", - "\xce\x88" => "\xce\xad", - "\xce\x89" => "\xce\xae", - "\xce\x8a" => "\xce\xaf", - "\xce\x8c" => "\xcf\x8c", - "\xce\x8e" => "\xcf\x8d", - "\xce\x8f" => "\xcf\x8e", - "\xce\x91" => "\xce\xb1", - "\xce\x92" => "\xce\xb2", - "\xce\x93" => "\xce\xb3", - "\xce\x94" => "\xce\xb4", - "\xce\x95" => "\xce\xb5", - "\xce\x96" => "\xce\xb6", - "\xce\x97" => "\xce\xb7", - "\xce\x98" => "\xce\xb8", - "\xce\x99" => "\xce\xb9", - "\xce\x9a" => "\xce\xba", - "\xce\x9b" => "\xce\xbb", - "\xce\x9c" => "\xc2\xb5", - "\xce\x9d" => "\xce\xbd", - "\xce\x9e" => "\xce\xbe", - "\xce\x9f" => "\xce\xbf", - "\xce\xa0" => "\xcf\x80", - "\xce\xa1" => "\xcf\x81", - "\xce\xa3" => "\xcf\x82", - "\xce\xa4" => "\xcf\x84", - "\xce\xa5" => "\xcf\x85", - "\xce\xa6" => "\xcf\x86", - "\xce\xa7" => "\xcf\x87", - "\xce\xa8" => "\xcf\x88", - "\xce\xa9" => "\xcf\x89", - "\xce\xaa" => "\xcf\x8a", - "\xce\xab" => "\xcf\x8b", - "\xcf\x98" => "\xcf\x99", - "\xcf\x9a" => "\xcf\x9b", - "\xcf\x9c" => "\xcf\x9d", - "\xcf\x9e" => "\xcf\x9f", - "\xcf\xa0" => "\xcf\xa1", - "\xcf\xa2" => "\xcf\xa3", - "\xcf\xa4" => "\xcf\xa5", - "\xcf\xa6" => "\xcf\xa7", - "\xcf\xa8" => "\xcf\xa9", - "\xcf\xaa" => "\xcf\xab", - "\xcf\xac" => "\xcf\xad", - "\xcf\xae" => "\xcf\xaf", - "\xd0\x80" => "\xd1\x90", - "\xd0\x81" => "\xd1\x91", - "\xd0\x82" => "\xd1\x92", - "\xd0\x83" => "\xd1\x93", - "\xd0\x84" => "\xd1\x94", - "\xd0\x85" => "\xd1\x95", - "\xd0\x86" => "\xd1\x96", - "\xd0\x87" => "\xd1\x97", - "\xd0\x88" => "\xd1\x98", - "\xd0\x89" => "\xd1\x99", - "\xd0\x8a" => "\xd1\x9a", - "\xd0\x8b" => "\xd1\x9b", - "\xd0\x8c" => "\xd1\x9c", - "\xd0\x8d" => "\xd1\x9d", - "\xd0\x8e" => "\xd1\x9e", - "\xd0\x8f" => "\xd1\x9f", - "\xd0\x90" => "\xd0\xb0", - "\xd0\x91" => "\xd0\xb1", - "\xd0\x92" => "\xd0\xb2", - "\xd0\x93" => "\xd0\xb3", - "\xd0\x94" => "\xd0\xb4", - "\xd0\x95" => "\xd0\xb5", - "\xd0\x96" => "\xd0\xb6", - "\xd0\x97" => "\xd0\xb7", - "\xd0\x98" => "\xd0\xb8", - "\xd0\x99" => "\xd0\xb9", - "\xd0\x9a" => "\xd0\xba", - "\xd0\x9b" => "\xd0\xbb", - "\xd0\x9c" => "\xd0\xbc", - "\xd0\x9d" => "\xd0\xbd", - "\xd0\x9e" => "\xd0\xbe", - "\xd0\x9f" => "\xd0\xbf", - "\xd0\xa0" => "\xd1\x80", - "\xd0\xa1" => "\xd1\x81", - "\xd0\xa2" => "\xd1\x82", - "\xd0\xa3" => "\xd1\x83", - "\xd0\xa4" => "\xd1\x84", - "\xd0\xa5" => "\xd1\x85", - "\xd0\xa6" => "\xd1\x86", - "\xd0\xa7" => "\xd1\x87", - "\xd0\xa8" => "\xd1\x88", - "\xd0\xa9" => "\xd1\x89", - "\xd0\xaa" => "\xd1\x8a", - "\xd0\xab" => "\xd1\x8b", - "\xd0\xac" => "\xd1\x8c", - "\xd0\xad" => "\xd1\x8d", - "\xd0\xae" => "\xd1\x8e", - "\xd0\xaf" => "\xd1\x8f", - "\xd1\xa0" => "\xd1\xa1", - "\xd1\xa2" => "\xd1\xa3", - "\xd1\xa4" => "\xd1\xa5", - "\xd1\xa6" => "\xd1\xa7", - "\xd1\xa8" => "\xd1\xa9", - "\xd1\xaa" => "\xd1\xab", - "\xd1\xac" => "\xd1\xad", - "\xd1\xae" => "\xd1\xaf", - "\xd1\xb0" => "\xd1\xb1", - "\xd1\xb2" => "\xd1\xb3", - "\xd1\xb4" => "\xd1\xb5", - "\xd1\xb6" => "\xd1\xb7", - "\xd1\xb8" => "\xd1\xb9", - "\xd1\xba" => "\xd1\xbb", - "\xd1\xbc" => "\xd1\xbd", - "\xd1\xbe" => "\xd1\xbf", - "\xd2\x80" => "\xd2\x81", - "\xd2\x8a" => "\xd2\x8b", - "\xd2\x8c" => "\xd2\x8d", - "\xd2\x8e" => "\xd2\x8f", - "\xd2\x90" => "\xd2\x91", - "\xd2\x92" => "\xd2\x93", - "\xd2\x94" => "\xd2\x95", - "\xd2\x96" => "\xd2\x97", - "\xd2\x98" => "\xd2\x99", - "\xd2\x9a" => "\xd2\x9b", - "\xd2\x9c" => "\xd2\x9d", - "\xd2\x9e" => "\xd2\x9f", - "\xd2\xa0" => "\xd2\xa1", - "\xd2\xa2" => "\xd2\xa3", - "\xd2\xa4" => "\xd2\xa5", - "\xd2\xa6" => "\xd2\xa7", - "\xd2\xa8" => "\xd2\xa9", - "\xd2\xaa" => "\xd2\xab", - "\xd2\xac" => "\xd2\xad", - "\xd2\xae" => "\xd2\xaf", - "\xd2\xb0" => "\xd2\xb1", - "\xd2\xb2" => "\xd2\xb3", - "\xd2\xb4" => "\xd2\xb5", - "\xd2\xb6" => "\xd2\xb7", - "\xd2\xb8" => "\xd2\xb9", - "\xd2\xba" => "\xd2\xbb", - "\xd2\xbc" => "\xd2\xbd", - "\xd2\xbe" => "\xd2\xbf", - "\xd3\x81" => "\xd3\x82", - "\xd3\x83" => "\xd3\x84", - "\xd3\x85" => "\xd3\x86", - "\xd3\x87" => "\xd3\x88", - "\xd3\x89" => "\xd3\x8a", - "\xd3\x8b" => "\xd3\x8c", - "\xd3\x8d" => "\xd3\x8e", - "\xd3\x90" => "\xd3\x91", - "\xd3\x92" => "\xd3\x93", - "\xd3\x94" => "\xd3\x95", - "\xd3\x96" => "\xd3\x97", - "\xd3\x98" => "\xd3\x99", - "\xd3\x9a" => "\xd3\x9b", - "\xd3\x9c" => "\xd3\x9d", - "\xd3\x9e" => "\xd3\x9f", - "\xd3\xa0" => "\xd3\xa1", - "\xd3\xa2" => "\xd3\xa3", - "\xd3\xa4" => "\xd3\xa5", - "\xd3\xa6" => "\xd3\xa7", - "\xd3\xa8" => "\xd3\xa9", - "\xd3\xaa" => "\xd3\xab", - "\xd3\xac" => "\xd3\xad", - "\xd3\xae" => "\xd3\xaf", - "\xd3\xb0" => "\xd3\xb1", - "\xd3\xb2" => "\xd3\xb3", - "\xd3\xb4" => "\xd3\xb5", - "\xd3\xb8" => "\xd3\xb9", - "\xd4\x80" => "\xd4\x81", - "\xd4\x82" => "\xd4\x83", - "\xd4\x84" => "\xd4\x85", - "\xd4\x86" => "\xd4\x87", - "\xd4\x88" => "\xd4\x89", - "\xd4\x8a" => "\xd4\x8b", - "\xd4\x8c" => "\xd4\x8d", - "\xd4\x8e" => "\xd4\x8f", - "\xd4\xb1" => "\xd5\xa1", - "\xd4\xb2" => "\xd5\xa2", - "\xd4\xb3" => "\xd5\xa3", - "\xd4\xb4" => "\xd5\xa4", - "\xd4\xb5" => "\xd5\xa5", - "\xd4\xb6" => "\xd5\xa6", - "\xd4\xb7" => "\xd5\xa7", - "\xd4\xb8" => "\xd5\xa8", - "\xd4\xb9" => "\xd5\xa9", - "\xd4\xba" => "\xd5\xaa", - "\xd4\xbb" => "\xd5\xab", - "\xd4\xbc" => "\xd5\xac", - "\xd4\xbd" => "\xd5\xad", - "\xd4\xbe" => "\xd5\xae", - "\xd4\xbf" => "\xd5\xaf", - "\xd5\x80" => "\xd5\xb0", - "\xd5\x81" => "\xd5\xb1", - "\xd5\x82" => "\xd5\xb2", - "\xd5\x83" => "\xd5\xb3", - "\xd5\x84" => "\xd5\xb4", - "\xd5\x85" => "\xd5\xb5", - "\xd5\x86" => "\xd5\xb6", - "\xd5\x87" => "\xd5\xb7", - "\xd5\x88" => "\xd5\xb8", - "\xd5\x89" => "\xd5\xb9", - "\xd5\x8a" => "\xd5\xba", - "\xd5\x8b" => "\xd5\xbb", - "\xd5\x8c" => "\xd5\xbc", - "\xd5\x8d" => "\xd5\xbd", - "\xd5\x8e" => "\xd5\xbe", - "\xd5\x8f" => "\xd5\xbf", - "\xd5\x90" => "\xd6\x80", - "\xd5\x91" => "\xd6\x81", - "\xd5\x92" => "\xd6\x82", - "\xd5\x93" => "\xd6\x83", - "\xd5\x94" => "\xd6\x84", - "\xd5\x95" => "\xd6\x85", - "\xd5\x96" => "\xd6\x86", - "\xe1\xb8\x80" => "\xe1\xb8\x81", - "\xe1\xb8\x82" => "\xe1\xb8\x83", - "\xe1\xb8\x84" => "\xe1\xb8\x85", - "\xe1\xb8\x86" => "\xe1\xb8\x87", - "\xe1\xb8\x88" => "\xe1\xb8\x89", - "\xe1\xb8\x8a" => "\xe1\xb8\x8b", - "\xe1\xb8\x8c" => "\xe1\xb8\x8d", - "\xe1\xb8\x8e" => "\xe1\xb8\x8f", - "\xe1\xb8\x90" => "\xe1\xb8\x91", - "\xe1\xb8\x92" => "\xe1\xb8\x93", - "\xe1\xb8\x94" => "\xe1\xb8\x95", - "\xe1\xb8\x96" => "\xe1\xb8\x97", - "\xe1\xb8\x98" => "\xe1\xb8\x99", - "\xe1\xb8\x9a" => "\xe1\xb8\x9b", - "\xe1\xb8\x9c" => "\xe1\xb8\x9d", - "\xe1\xb8\x9e" => "\xe1\xb8\x9f", - "\xe1\xb8\xa0" => "\xe1\xb8\xa1", - "\xe1\xb8\xa2" => "\xe1\xb8\xa3", - "\xe1\xb8\xa4" => "\xe1\xb8\xa5", - "\xe1\xb8\xa6" => "\xe1\xb8\xa7", - "\xe1\xb8\xa8" => "\xe1\xb8\xa9", - "\xe1\xb8\xaa" => "\xe1\xb8\xab", - "\xe1\xb8\xac" => "\xe1\xb8\xad", - "\xe1\xb8\xae" => "\xe1\xb8\xaf", - "\xe1\xb8\xb0" => "\xe1\xb8\xb1", - "\xe1\xb8\xb2" => "\xe1\xb8\xb3", - "\xe1\xb8\xb4" => "\xe1\xb8\xb5", - "\xe1\xb8\xb6" => "\xe1\xb8\xb7", - "\xe1\xb8\xb8" => "\xe1\xb8\xb9", - "\xe1\xb8\xba" => "\xe1\xb8\xbb", - "\xe1\xb8\xbc" => "\xe1\xb8\xbd", - "\xe1\xb8\xbe" => "\xe1\xb8\xbf", - "\xe1\xb9\x80" => "\xe1\xb9\x81", - "\xe1\xb9\x82" => "\xe1\xb9\x83", - "\xe1\xb9\x84" => "\xe1\xb9\x85", - "\xe1\xb9\x86" => "\xe1\xb9\x87", - "\xe1\xb9\x88" => "\xe1\xb9\x89", - "\xe1\xb9\x8a" => "\xe1\xb9\x8b", - "\xe1\xb9\x8c" => "\xe1\xb9\x8d", - "\xe1\xb9\x8e" => "\xe1\xb9\x8f", - "\xe1\xb9\x90" => "\xe1\xb9\x91", - "\xe1\xb9\x92" => "\xe1\xb9\x93", - "\xe1\xb9\x94" => "\xe1\xb9\x95", - "\xe1\xb9\x96" => "\xe1\xb9\x97", - "\xe1\xb9\x98" => "\xe1\xb9\x99", - "\xe1\xb9\x9a" => "\xe1\xb9\x9b", - "\xe1\xb9\x9c" => "\xe1\xb9\x9d", - "\xe1\xb9\x9e" => "\xe1\xb9\x9f", - "\xe1\xb9\xa0" => "\xe1\xb9\xa1", - "\xe1\xb9\xa2" => "\xe1\xb9\xa3", - "\xe1\xb9\xa4" => "\xe1\xb9\xa5", - "\xe1\xb9\xa6" => "\xe1\xb9\xa7", - "\xe1\xb9\xa8" => "\xe1\xb9\xa9", - "\xe1\xb9\xaa" => "\xe1\xb9\xab", - "\xe1\xb9\xac" => "\xe1\xb9\xad", - "\xe1\xb9\xae" => "\xe1\xb9\xaf", - "\xe1\xb9\xb0" => "\xe1\xb9\xb1", - "\xe1\xb9\xb2" => "\xe1\xb9\xb3", - "\xe1\xb9\xb4" => "\xe1\xb9\xb5", - "\xe1\xb9\xb6" => "\xe1\xb9\xb7", - "\xe1\xb9\xb8" => "\xe1\xb9\xb9", - "\xe1\xb9\xba" => "\xe1\xb9\xbb", - "\xe1\xb9\xbc" => "\xe1\xb9\xbd", - "\xe1\xb9\xbe" => "\xe1\xb9\xbf", - "\xe1\xba\x80" => "\xe1\xba\x81", - "\xe1\xba\x82" => "\xe1\xba\x83", - "\xe1\xba\x84" => "\xe1\xba\x85", - "\xe1\xba\x86" => "\xe1\xba\x87", - "\xe1\xba\x88" => "\xe1\xba\x89", - "\xe1\xba\x8a" => "\xe1\xba\x8b", - "\xe1\xba\x8c" => "\xe1\xba\x8d", - "\xe1\xba\x8e" => "\xe1\xba\x8f", - "\xe1\xba\x90" => "\xe1\xba\x91", - "\xe1\xba\x92" => "\xe1\xba\x93", - "\xe1\xba\x94" => "\xe1\xba\x95", - "\xe1\xba\xa0" => "\xe1\xba\xa1", - "\xe1\xba\xa2" => "\xe1\xba\xa3", - "\xe1\xba\xa4" => "\xe1\xba\xa5", - "\xe1\xba\xa6" => "\xe1\xba\xa7", - "\xe1\xba\xa8" => "\xe1\xba\xa9", - "\xe1\xba\xaa" => "\xe1\xba\xab", - "\xe1\xba\xac" => "\xe1\xba\xad", - "\xe1\xba\xae" => "\xe1\xba\xaf", - "\xe1\xba\xb0" => "\xe1\xba\xb1", - "\xe1\xba\xb2" => "\xe1\xba\xb3", - "\xe1\xba\xb4" => "\xe1\xba\xb5", - "\xe1\xba\xb6" => "\xe1\xba\xb7", - "\xe1\xba\xb8" => "\xe1\xba\xb9", - "\xe1\xba\xba" => "\xe1\xba\xbb", - "\xe1\xba\xbc" => "\xe1\xba\xbd", - "\xe1\xba\xbe" => "\xe1\xba\xbf", - "\xe1\xbb\x80" => "\xe1\xbb\x81", - "\xe1\xbb\x82" => "\xe1\xbb\x83", - "\xe1\xbb\x84" => "\xe1\xbb\x85", - "\xe1\xbb\x86" => "\xe1\xbb\x87", - "\xe1\xbb\x88" => "\xe1\xbb\x89", - "\xe1\xbb\x8a" => "\xe1\xbb\x8b", - "\xe1\xbb\x8c" => "\xe1\xbb\x8d", - "\xe1\xbb\x8e" => "\xe1\xbb\x8f", - "\xe1\xbb\x90" => "\xe1\xbb\x91", - "\xe1\xbb\x92" => "\xe1\xbb\x93", - "\xe1\xbb\x94" => "\xe1\xbb\x95", - "\xe1\xbb\x96" => "\xe1\xbb\x97", - "\xe1\xbb\x98" => "\xe1\xbb\x99", - "\xe1\xbb\x9a" => "\xe1\xbb\x9b", - "\xe1\xbb\x9c" => "\xe1\xbb\x9d", - "\xe1\xbb\x9e" => "\xe1\xbb\x9f", - "\xe1\xbb\xa0" => "\xe1\xbb\xa1", - "\xe1\xbb\xa2" => "\xe1\xbb\xa3", - "\xe1\xbb\xa4" => "\xe1\xbb\xa5", - "\xe1\xbb\xa6" => "\xe1\xbb\xa7", - "\xe1\xbb\xa8" => "\xe1\xbb\xa9", - "\xe1\xbb\xaa" => "\xe1\xbb\xab", - "\xe1\xbb\xac" => "\xe1\xbb\xad", - "\xe1\xbb\xae" => "\xe1\xbb\xaf", - "\xe1\xbb\xb0" => "\xe1\xbb\xb1", - "\xe1\xbb\xb2" => "\xe1\xbb\xb3", - "\xe1\xbb\xb4" => "\xe1\xbb\xb5", - "\xe1\xbb\xb6" => "\xe1\xbb\xb7", - "\xe1\xbb\xb8" => "\xe1\xbb\xb9", - "\xe1\xbc\x88" => "\xe1\xbc\x80", - "\xe1\xbc\x89" => "\xe1\xbc\x81", - "\xe1\xbc\x8a" => "\xe1\xbc\x82", - "\xe1\xbc\x8b" => "\xe1\xbc\x83", - "\xe1\xbc\x8c" => "\xe1\xbc\x84", - "\xe1\xbc\x8d" => "\xe1\xbc\x85", - "\xe1\xbc\x8e" => "\xe1\xbc\x86", - "\xe1\xbc\x8f" => "\xe1\xbc\x87", - "\xe1\xbc\x98" => "\xe1\xbc\x90", - "\xe1\xbc\x99" => "\xe1\xbc\x91", - "\xe1\xbc\x9a" => "\xe1\xbc\x92", - "\xe1\xbc\x9b" => "\xe1\xbc\x93", - "\xe1\xbc\x9c" => "\xe1\xbc\x94", - "\xe1\xbc\x9d" => "\xe1\xbc\x95", - "\xe1\xbc\xa9" => "\xe1\xbc\xa1", - "\xe1\xbc\xaa" => "\xe1\xbc\xa2", - "\xe1\xbc\xab" => "\xe1\xbc\xa3", - "\xe1\xbc\xac" => "\xe1\xbc\xa4", - "\xe1\xbc\xad" => "\xe1\xbc\xa5", - "\xe1\xbc\xae" => "\xe1\xbc\xa6", - "\xe1\xbc\xaf" => "\xe1\xbc\xa7", - "\xe1\xbc\xb8" => "\xe1\xbc\xb0", - "\xe1\xbc\xb9" => "\xe1\xbc\xb1", - "\xe1\xbc\xba" => "\xe1\xbc\xb2", - "\xe1\xbc\xbb" => "\xe1\xbc\xb3", - "\xe1\xbc\xbc" => "\xe1\xbc\xb4", - "\xe1\xbc\xbd" => "\xe1\xbc\xb5", - "\xe1\xbc\xbe" => "\xe1\xbc\xb6", - "\xe1\xbc\xbf" => "\xe1\xbc\xb7", - "\xe1\xbd\x88" => "\xe1\xbd\x80", - "\xe1\xbd\x89" => "\xe1\xbd\x81", - "\xe1\xbd\x8a" => "\xe1\xbd\x82", - "\xe1\xbd\x8b" => "\xe1\xbd\x83", - "\xe1\xbd\x8c" => "\xe1\xbd\x84", - "\xe1\xbd\x8d" => "\xe1\xbd\x85", - "\xe1\xbd\x99" => "\xe1\xbd\x91", - "\xe1\xbd\x9b" => "\xe1\xbd\x93", - "\xe1\xbd\x9d" => "\xe1\xbd\x95", - "\xe1\xbd\x9f" => "\xe1\xbd\x97", - "\xe1\xbd\xa9" => "\xe1\xbd\xa1", - "\xe1\xbd\xaa" => "\xe1\xbd\xa2", - "\xe1\xbd\xab" => "\xe1\xbd\xa3", - "\xe1\xbd\xac" => "\xe1\xbd\xa4", - "\xe1\xbd\xad" => "\xe1\xbd\xa5", - "\xe1\xbd\xae" => "\xe1\xbd\xa6", - "\xe1\xbd\xaf" => "\xe1\xbd\xa7", - "\xe1\xbe\x88" => "\xe1\xbe\x80", - "\xe1\xbe\x89" => "\xe1\xbe\x81", - "\xe1\xbe\x8a" => "\xe1\xbe\x82", - "\xe1\xbe\x8b" => "\xe1\xbe\x83", - "\xe1\xbe\x8c" => "\xe1\xbe\x84", - "\xe1\xbe\x8d" => "\xe1\xbe\x85", - "\xe1\xbe\x8e" => "\xe1\xbe\x86", - "\xe1\xbe\x8f" => "\xe1\xbe\x87", - "\xe1\xbe\x98" => "\xe1\xbe\x90", - "\xe1\xbe\x99" => "\xe1\xbe\x91", - "\xe1\xbe\x9a" => "\xe1\xbe\x92", - "\xe1\xbe\x9b" => "\xe1\xbe\x93", - "\xe1\xbe\x9c" => "\xe1\xbe\x94", - "\xe1\xbe\x9d" => "\xe1\xbe\x95", - "\xe1\xbe\x9e" => "\xe1\xbe\x96", - "\xe1\xbe\x9f" => "\xe1\xbe\x97", - "\xe1\xbe\xa9" => "\xe1\xbe\xa1", - "\xe1\xbe\xaa" => "\xe1\xbe\xa2", - "\xe1\xbe\xab" => "\xe1\xbe\xa3", - "\xe1\xbe\xac" => "\xe1\xbe\xa4", - "\xe1\xbe\xad" => "\xe1\xbe\xa5", - "\xe1\xbe\xae" => "\xe1\xbe\xa6", - "\xe1\xbe\xaf" => "\xe1\xbe\xa7", - "\xe1\xbe\xb8" => "\xe1\xbe\xb0", - "\xe1\xbe\xb9" => "\xe1\xbe\xb1", - "\xe1\xbe\xba" => "\xe1\xbd\xb0", - "\xe1\xbe\xbb" => "\xe1\xbd\xb1", - "\xe1\xbe\xbc" => "\xe1\xbe\xb3", - "\xe1\xbf\x88" => "\xe1\xbd\xb2", - "\xe1\xbf\x89" => "\xe1\xbd\xb3", - "\xe1\xbf\x8a" => "\xe1\xbd\xb4", - "\xe1\xbf\x8b" => "\xe1\xbd\xb5", - "\xe1\xbf\x8c" => "\xe1\xbf\x83", - "\xe1\xbf\x98" => "\xe1\xbf\x90", - "\xe1\xbf\x99" => "\xe1\xbf\x91", - "\xe1\xbf\x9a" => "\xe1\xbd\xb6", - "\xe1\xbf\x9b" => "\xe1\xbd\xb7", - "\xe1\xbf\xa9" => "\xe1\xbf\xa1", - "\xe1\xbf\xaa" => "\xe1\xbd\xba", - "\xe1\xbf\xab" => "\xe1\xbd\xbb", - "\xe1\xbf\xac" => "\xe1\xbf\xa5", - "\xe1\xbf\xb8" => "\xe1\xbd\xb8", - "\xe1\xbf\xb9" => "\xe1\xbd\xb9", - "\xe1\xbf\xba" => "\xe1\xbd\xbc", - "\xe1\xbf\xbb" => "\xe1\xbd\xbd", - "\xe1\xbf\xbc" => "\xe1\xbf\xb3", - "\xef\xbc\xa1" => "\xef\xbd\x81", - "\xef\xbc\xa2" => "\xef\xbd\x82", - "\xef\xbc\xa3" => "\xef\xbd\x83", - "\xef\xbc\xa4" => "\xef\xbd\x84", - "\xef\xbc\xa5" => "\xef\xbd\x85", - "\xef\xbc\xa6" => "\xef\xbd\x86", - "\xef\xbc\xa7" => "\xef\xbd\x87", - "\xef\xbc\xa8" => "\xef\xbd\x88", - "\xef\xbc\xa9" => "\xef\xbd\x89", - "\xef\xbc\xaa" => "\xef\xbd\x8a", - "\xef\xbc\xab" => "\xef\xbd\x8b", - "\xef\xbc\xac" => "\xef\xbd\x8c", - "\xef\xbc\xad" => "\xef\xbd\x8d", - "\xef\xbc\xae" => "\xef\xbd\x8e", - "\xef\xbc\xaf" => "\xef\xbd\x8f", - "\xef\xbc\xb0" => "\xef\xbd\x90", - "\xef\xbc\xb1" => "\xef\xbd\x91", - "\xef\xbc\xb2" => "\xef\xbd\x92", - "\xef\xbc\xb3" => "\xef\xbd\x93", - "\xef\xbc\xb4" => "\xef\xbd\x94", - "\xef\xbc\xb5" => "\xef\xbd\x95", - "\xef\xbc\xb6" => "\xef\xbd\x96", - "\xef\xbc\xb7" => "\xef\xbd\x97", - "\xef\xbc\xb8" => "\xef\xbd\x98", - "\xef\xbc\xb9" => "\xef\xbd\x99", - "\xef\xbc\xba" => "\xef\xbd\x9a", - ); - - #Unicode Character Database 6.0.0 (2010-06-04) - #autogenerated by unicode_blocks_txt2php() PHP function at 2011-06-04 00:19:39, 209 blocks total - public static $unicode_blocks = array( - 'Basic Latin' => array( - 0 => 0x0000, - 1 => 0x007F, - 2 => 0, - ), - 'Latin-1 Supplement' => array( - 0 => 0x0080, - 1 => 0x00FF, - 2 => 1, - ), - 'Latin Extended-A' => array( - 0 => 0x0100, - 1 => 0x017F, - 2 => 2, - ), - 'Latin Extended-B' => array( - 0 => 0x0180, - 1 => 0x024F, - 2 => 3, - ), - 'IPA Extensions' => array( - 0 => 0x0250, - 1 => 0x02AF, - 2 => 4, - ), - 'Spacing Modifier Letters' => array( - 0 => 0x02B0, - 1 => 0x02FF, - 2 => 5, - ), - 'Combining Diacritical Marks' => array( - 0 => 0x0300, - 1 => 0x036F, - 2 => 6, - ), - 'Greek and Coptic' => array( - 0 => 0x0370, - 1 => 0x03FF, - 2 => 7, - ), - 'Cyrillic' => array( - 0 => 0x0400, - 1 => 0x04FF, - 2 => 8, - ), - 'Cyrillic Supplement' => array( - 0 => 0x0500, - 1 => 0x052F, - 2 => 9, - ), - 'Armenian' => array( - 0 => 0x0530, - 1 => 0x058F, - 2 => 10, - ), - 'Hebrew' => array( - 0 => 0x0590, - 1 => 0x05FF, - 2 => 11, - ), - 'Arabic' => array( - 0 => 0x0600, - 1 => 0x06FF, - 2 => 12, - ), - 'Syriac' => array( - 0 => 0x0700, - 1 => 0x074F, - 2 => 13, - ), - 'Arabic Supplement' => array( - 0 => 0x0750, - 1 => 0x077F, - 2 => 14, - ), - 'Thaana' => array( - 0 => 0x0780, - 1 => 0x07BF, - 2 => 15, - ), - 'NKo' => array( - 0 => 0x07C0, - 1 => 0x07FF, - 2 => 16, - ), - 'Samaritan' => array( - 0 => 0x0800, - 1 => 0x083F, - 2 => 17, - ), - 'Mandaic' => array( - 0 => 0x0840, - 1 => 0x085F, - 2 => 18, - ), - 'Devanagari' => array( - 0 => 0x0900, - 1 => 0x097F, - 2 => 19, - ), - 'Bengali' => array( - 0 => 0x0980, - 1 => 0x09FF, - 2 => 20, - ), - 'Gurmukhi' => array( - 0 => 0x0A00, - 1 => 0x0A7F, - 2 => 21, - ), - 'Gujarati' => array( - 0 => 0x0A80, - 1 => 0x0AFF, - 2 => 22, - ), - 'Oriya' => array( - 0 => 0x0B00, - 1 => 0x0B7F, - 2 => 23, - ), - 'Tamil' => array( - 0 => 0x0B80, - 1 => 0x0BFF, - 2 => 24, - ), - 'Telugu' => array( - 0 => 0x0C00, - 1 => 0x0C7F, - 2 => 25, - ), - 'Kannada' => array( - 0 => 0x0C80, - 1 => 0x0CFF, - 2 => 26, - ), - 'Malayalam' => array( - 0 => 0x0D00, - 1 => 0x0D7F, - 2 => 27, - ), - 'Sinhala' => array( - 0 => 0x0D80, - 1 => 0x0DFF, - 2 => 28, - ), - 'Thai' => array( - 0 => 0x0E00, - 1 => 0x0E7F, - 2 => 29, - ), - 'Lao' => array( - 0 => 0x0E80, - 1 => 0x0EFF, - 2 => 30, - ), - 'Tibetan' => array( - 0 => 0x0F00, - 1 => 0x0FFF, - 2 => 31, - ), - 'Myanmar' => array( - 0 => 0x1000, - 1 => 0x109F, - 2 => 32, - ), - 'Georgian' => array( - 0 => 0x10A0, - 1 => 0x10FF, - 2 => 33, - ), - 'Hangul Jamo' => array( - 0 => 0x1100, - 1 => 0x11FF, - 2 => 34, - ), - 'Ethiopic' => array( - 0 => 0x1200, - 1 => 0x137F, - 2 => 35, - ), - 'Ethiopic Supplement' => array( - 0 => 0x1380, - 1 => 0x139F, - 2 => 36, - ), - 'Cherokee' => array( - 0 => 0x13A0, - 1 => 0x13FF, - 2 => 37, - ), - 'Unified Canadian Aboriginal Syllabics' => array( - 0 => 0x1400, - 1 => 0x167F, - 2 => 38, - ), - 'Ogham' => array( - 0 => 0x1680, - 1 => 0x169F, - 2 => 39, - ), - 'Runic' => array( - 0 => 0x16A0, - 1 => 0x16FF, - 2 => 40, - ), - 'Tagalog' => array( - 0 => 0x1700, - 1 => 0x171F, - 2 => 41, - ), - 'Hanunoo' => array( - 0 => 0x1720, - 1 => 0x173F, - 2 => 42, - ), - 'Buhid' => array( - 0 => 0x1740, - 1 => 0x175F, - 2 => 43, - ), - 'Tagbanwa' => array( - 0 => 0x1760, - 1 => 0x177F, - 2 => 44, - ), - 'Khmer' => array( - 0 => 0x1780, - 1 => 0x17FF, - 2 => 45, - ), - 'Mongolian' => array( - 0 => 0x1800, - 1 => 0x18AF, - 2 => 46, - ), - 'Unified Canadian Aboriginal Syllabics Extended' => array( - 0 => 0x18B0, - 1 => 0x18FF, - 2 => 47, - ), - 'Limbu' => array( - 0 => 0x1900, - 1 => 0x194F, - 2 => 48, - ), - 'Tai Le' => array( - 0 => 0x1950, - 1 => 0x197F, - 2 => 49, - ), - 'New Tai Lue' => array( - 0 => 0x1980, - 1 => 0x19DF, - 2 => 50, - ), - 'Khmer Symbols' => array( - 0 => 0x19E0, - 1 => 0x19FF, - 2 => 51, - ), - 'Buginese' => array( - 0 => 0x1A00, - 1 => 0x1A1F, - 2 => 52, - ), - 'Tai Tham' => array( - 0 => 0x1A20, - 1 => 0x1AAF, - 2 => 53, - ), - 'Balinese' => array( - 0 => 0x1B00, - 1 => 0x1B7F, - 2 => 54, - ), - 'Sundanese' => array( - 0 => 0x1B80, - 1 => 0x1BBF, - 2 => 55, - ), - 'Batak' => array( - 0 => 0x1BC0, - 1 => 0x1BFF, - 2 => 56, - ), - 'Lepcha' => array( - 0 => 0x1C00, - 1 => 0x1C4F, - 2 => 57, - ), - 'Ol Chiki' => array( - 0 => 0x1C50, - 1 => 0x1C7F, - 2 => 58, - ), - 'Vedic Extensions' => array( - 0 => 0x1CD0, - 1 => 0x1CFF, - 2 => 59, - ), - 'Phonetic Extensions' => array( - 0 => 0x1D00, - 1 => 0x1D7F, - 2 => 60, - ), - 'Phonetic Extensions Supplement' => array( - 0 => 0x1D80, - 1 => 0x1DBF, - 2 => 61, - ), - 'Combining Diacritical Marks Supplement' => array( - 0 => 0x1DC0, - 1 => 0x1DFF, - 2 => 62, - ), - 'Latin Extended Additional' => array( - 0 => 0x1E00, - 1 => 0x1EFF, - 2 => 63, - ), - 'Greek Extended' => array( - 0 => 0x1F00, - 1 => 0x1FFF, - 2 => 64, - ), - 'General Punctuation' => array( - 0 => 0x2000, - 1 => 0x206F, - 2 => 65, - ), - 'Superscripts and Subscripts' => array( - 0 => 0x2070, - 1 => 0x209F, - 2 => 66, - ), - 'Currency Symbols' => array( - 0 => 0x20A0, - 1 => 0x20CF, - 2 => 67, - ), - 'Combining Diacritical Marks for Symbols' => array( - 0 => 0x20D0, - 1 => 0x20FF, - 2 => 68, - ), - 'Letterlike Symbols' => array( - 0 => 0x2100, - 1 => 0x214F, - 2 => 69, - ), - 'Number Forms' => array( - 0 => 0x2150, - 1 => 0x218F, - 2 => 70, - ), - 'Arrows' => array( - 0 => 0x2190, - 1 => 0x21FF, - 2 => 71, - ), - 'Mathematical Operators' => array( - 0 => 0x2200, - 1 => 0x22FF, - 2 => 72, - ), - 'Miscellaneous Technical' => array( - 0 => 0x2300, - 1 => 0x23FF, - 2 => 73, - ), - 'Control Pictures' => array( - 0 => 0x2400, - 1 => 0x243F, - 2 => 74, - ), - 'Optical Character Recognition' => array( - 0 => 0x2440, - 1 => 0x245F, - 2 => 75, - ), - 'Enclosed Alphanumerics' => array( - 0 => 0x2460, - 1 => 0x24FF, - 2 => 76, - ), - 'Box Drawing' => array( - 0 => 0x2500, - 1 => 0x257F, - 2 => 77, - ), - 'Block Elements' => array( - 0 => 0x2580, - 1 => 0x259F, - 2 => 78, - ), - 'Geometric Shapes' => array( - 0 => 0x25A0, - 1 => 0x25FF, - 2 => 79, - ), - 'Miscellaneous Symbols' => array( - 0 => 0x2600, - 1 => 0x26FF, - 2 => 80, - ), - 'Dingbats' => array( - 0 => 0x2700, - 1 => 0x27BF, - 2 => 81, - ), - 'Miscellaneous Mathematical Symbols-A' => array( - 0 => 0x27C0, - 1 => 0x27EF, - 2 => 82, - ), - 'Supplemental Arrows-A' => array( - 0 => 0x27F0, - 1 => 0x27FF, - 2 => 83, - ), - 'Braille Patterns' => array( - 0 => 0x2800, - 1 => 0x28FF, - 2 => 84, - ), - 'Supplemental Arrows-B' => array( - 0 => 0x2900, - 1 => 0x297F, - 2 => 85, - ), - 'Miscellaneous Mathematical Symbols-B' => array( - 0 => 0x2980, - 1 => 0x29FF, - 2 => 86, - ), - 'Supplemental Mathematical Operators' => array( - 0 => 0x2A00, - 1 => 0x2AFF, - 2 => 87, - ), - 'Miscellaneous Symbols and Arrows' => array( - 0 => 0x2B00, - 1 => 0x2BFF, - 2 => 88, - ), - 'Glagolitic' => array( - 0 => 0x2C00, - 1 => 0x2C5F, - 2 => 89, - ), - 'Latin Extended-C' => array( - 0 => 0x2C60, - 1 => 0x2C7F, - 2 => 90, - ), - 'Coptic' => array( - 0 => 0x2C80, - 1 => 0x2CFF, - 2 => 91, - ), - 'Georgian Supplement' => array( - 0 => 0x2D00, - 1 => 0x2D2F, - 2 => 92, - ), - 'Tifinagh' => array( - 0 => 0x2D30, - 1 => 0x2D7F, - 2 => 93, - ), - 'Ethiopic Extended' => array( - 0 => 0x2D80, - 1 => 0x2DDF, - 2 => 94, - ), - 'Cyrillic Extended-A' => array( - 0 => 0x2DE0, - 1 => 0x2DFF, - 2 => 95, - ), - 'Supplemental Punctuation' => array( - 0 => 0x2E00, - 1 => 0x2E7F, - 2 => 96, - ), - 'CJK Radicals Supplement' => array( - 0 => 0x2E80, - 1 => 0x2EFF, - 2 => 97, - ), - 'Kangxi Radicals' => array( - 0 => 0x2F00, - 1 => 0x2FDF, - 2 => 98, - ), - 'Ideographic Description Characters' => array( - 0 => 0x2FF0, - 1 => 0x2FFF, - 2 => 99, - ), - 'CJK Symbols and Punctuation' => array( - 0 => 0x3000, - 1 => 0x303F, - 2 => 100, - ), - 'Hiragana' => array( - 0 => 0x3040, - 1 => 0x309F, - 2 => 101, - ), - 'Katakana' => array( - 0 => 0x30A0, - 1 => 0x30FF, - 2 => 102, - ), - 'Bopomofo' => array( - 0 => 0x3100, - 1 => 0x312F, - 2 => 103, - ), - 'Hangul Compatibility Jamo' => array( - 0 => 0x3130, - 1 => 0x318F, - 2 => 104, - ), - 'Kanbun' => array( - 0 => 0x3190, - 1 => 0x319F, - 2 => 105, - ), - 'Bopomofo Extended' => array( - 0 => 0x31A0, - 1 => 0x31BF, - 2 => 106, - ), - 'CJK Strokes' => array( - 0 => 0x31C0, - 1 => 0x31EF, - 2 => 107, - ), - 'Katakana Phonetic Extensions' => array( - 0 => 0x31F0, - 1 => 0x31FF, - 2 => 108, - ), - 'Enclosed CJK Letters and Months' => array( - 0 => 0x3200, - 1 => 0x32FF, - 2 => 109, - ), - 'CJK Compatibility' => array( - 0 => 0x3300, - 1 => 0x33FF, - 2 => 110, - ), - 'CJK Unified Ideographs Extension A' => array( - 0 => 0x3400, - 1 => 0x4DBF, - 2 => 111, - ), - 'Yijing Hexagram Symbols' => array( - 0 => 0x4DC0, - 1 => 0x4DFF, - 2 => 112, - ), - 'CJK Unified Ideographs' => array( - 0 => 0x4E00, - 1 => 0x9FFF, - 2 => 113, - ), - 'Yi Syllables' => array( - 0 => 0xA000, - 1 => 0xA48F, - 2 => 114, - ), - 'Yi Radicals' => array( - 0 => 0xA490, - 1 => 0xA4CF, - 2 => 115, - ), - 'Lisu' => array( - 0 => 0xA4D0, - 1 => 0xA4FF, - 2 => 116, - ), - 'Vai' => array( - 0 => 0xA500, - 1 => 0xA63F, - 2 => 117, - ), - 'Cyrillic Extended-B' => array( - 0 => 0xA640, - 1 => 0xA69F, - 2 => 118, - ), - 'Bamum' => array( - 0 => 0xA6A0, - 1 => 0xA6FF, - 2 => 119, - ), - 'Modifier Tone Letters' => array( - 0 => 0xA700, - 1 => 0xA71F, - 2 => 120, - ), - 'Latin Extended-D' => array( - 0 => 0xA720, - 1 => 0xA7FF, - 2 => 121, - ), - 'Syloti Nagri' => array( - 0 => 0xA800, - 1 => 0xA82F, - 2 => 122, - ), - 'Common Indic Number Forms' => array( - 0 => 0xA830, - 1 => 0xA83F, - 2 => 123, - ), - 'Phags-pa' => array( - 0 => 0xA840, - 1 => 0xA87F, - 2 => 124, - ), - 'Saurashtra' => array( - 0 => 0xA880, - 1 => 0xA8DF, - 2 => 125, - ), - 'Devanagari Extended' => array( - 0 => 0xA8E0, - 1 => 0xA8FF, - 2 => 126, - ), - 'Kayah Li' => array( - 0 => 0xA900, - 1 => 0xA92F, - 2 => 127, - ), - 'Rejang' => array( - 0 => 0xA930, - 1 => 0xA95F, - 2 => 128, - ), - 'Hangul Jamo Extended-A' => array( - 0 => 0xA960, - 1 => 0xA97F, - 2 => 129, - ), - 'Javanese' => array( - 0 => 0xA980, - 1 => 0xA9DF, - 2 => 130, - ), - 'Cham' => array( - 0 => 0xAA00, - 1 => 0xAA5F, - 2 => 131, - ), - 'Myanmar Extended-A' => array( - 0 => 0xAA60, - 1 => 0xAA7F, - 2 => 132, - ), - 'Tai Viet' => array( - 0 => 0xAA80, - 1 => 0xAADF, - 2 => 133, - ), - 'Ethiopic Extended-A' => array( - 0 => 0xAB00, - 1 => 0xAB2F, - 2 => 134, - ), - 'Meetei Mayek' => array( - 0 => 0xABC0, - 1 => 0xABFF, - 2 => 135, - ), - 'Hangul Syllables' => array( - 0 => 0xAC00, - 1 => 0xD7AF, - 2 => 136, - ), - 'Hangul Jamo Extended-B' => array( - 0 => 0xD7B0, - 1 => 0xD7FF, - 2 => 137, - ), - 'High Surrogates' => array( - 0 => 0xD800, - 1 => 0xDB7F, - 2 => 138, - ), - 'High Private Use Surrogates' => array( - 0 => 0xDB80, - 1 => 0xDBFF, - 2 => 139, - ), - 'Low Surrogates' => array( - 0 => 0xDC00, - 1 => 0xDFFF, - 2 => 140, - ), - 'Private Use Area' => array( - 0 => 0xE000, - 1 => 0xF8FF, - 2 => 141, - ), - 'CJK Compatibility Ideographs' => array( - 0 => 0xF900, - 1 => 0xFAFF, - 2 => 142, - ), - 'Alphabetic Presentation Forms' => array( - 0 => 0xFB00, - 1 => 0xFB4F, - 2 => 143, - ), - 'Arabic Presentation Forms-A' => array( - 0 => 0xFB50, - 1 => 0xFDFF, - 2 => 144, - ), - 'Variation Selectors' => array( - 0 => 0xFE00, - 1 => 0xFE0F, - 2 => 145, - ), - 'Vertical Forms' => array( - 0 => 0xFE10, - 1 => 0xFE1F, - 2 => 146, - ), - 'Combining Half Marks' => array( - 0 => 0xFE20, - 1 => 0xFE2F, - 2 => 147, - ), - 'CJK Compatibility Forms' => array( - 0 => 0xFE30, - 1 => 0xFE4F, - 2 => 148, - ), - 'Small Form Variants' => array( - 0 => 0xFE50, - 1 => 0xFE6F, - 2 => 149, - ), - 'Arabic Presentation Forms-B' => array( - 0 => 0xFE70, - 1 => 0xFEFF, - 2 => 150, - ), - 'Halfwidth and Fullwidth Forms' => array( - 0 => 0xFF00, - 1 => 0xFFEF, - 2 => 151, - ), - 'Specials' => array( - 0 => 0xFFF0, - 1 => 0xFFFF, - 2 => 152, - ), - 'Linear B Syllabary' => array( - 0 => 0x10000, - 1 => 0x1007F, - 2 => 153, - ), - 'Linear B Ideograms' => array( - 0 => 0x10080, - 1 => 0x100FF, - 2 => 154, - ), - 'Aegean Numbers' => array( - 0 => 0x10100, - 1 => 0x1013F, - 2 => 155, - ), - 'Ancient Greek Numbers' => array( - 0 => 0x10140, - 1 => 0x1018F, - 2 => 156, - ), - 'Ancient Symbols' => array( - 0 => 0x10190, - 1 => 0x101CF, - 2 => 157, - ), - 'Phaistos Disc' => array( - 0 => 0x101D0, - 1 => 0x101FF, - 2 => 158, - ), - 'Lycian' => array( - 0 => 0x10280, - 1 => 0x1029F, - 2 => 159, - ), - 'Carian' => array( - 0 => 0x102A0, - 1 => 0x102DF, - 2 => 160, - ), - 'Old Italic' => array( - 0 => 0x10300, - 1 => 0x1032F, - 2 => 161, - ), - 'Gothic' => array( - 0 => 0x10330, - 1 => 0x1034F, - 2 => 162, - ), - 'Ugaritic' => array( - 0 => 0x10380, - 1 => 0x1039F, - 2 => 163, - ), - 'Old Persian' => array( - 0 => 0x103A0, - 1 => 0x103DF, - 2 => 164, - ), - 'Deseret' => array( - 0 => 0x10400, - 1 => 0x1044F, - 2 => 165, - ), - 'Shavian' => array( - 0 => 0x10450, - 1 => 0x1047F, - 2 => 166, - ), - 'Osmanya' => array( - 0 => 0x10480, - 1 => 0x104AF, - 2 => 167, - ), - 'Cypriot Syllabary' => array( - 0 => 0x10800, - 1 => 0x1083F, - 2 => 168, - ), - 'Imperial Aramaic' => array( - 0 => 0x10840, - 1 => 0x1085F, - 2 => 169, - ), - 'Phoenician' => array( - 0 => 0x10900, - 1 => 0x1091F, - 2 => 170, - ), - 'Lydian' => array( - 0 => 0x10920, - 1 => 0x1093F, - 2 => 171, - ), - 'Kharoshthi' => array( - 0 => 0x10A00, - 1 => 0x10A5F, - 2 => 172, - ), - 'Old South Arabian' => array( - 0 => 0x10A60, - 1 => 0x10A7F, - 2 => 173, - ), - 'Avestan' => array( - 0 => 0x10B00, - 1 => 0x10B3F, - 2 => 174, - ), - 'Inscriptional Parthian' => array( - 0 => 0x10B40, - 1 => 0x10B5F, - 2 => 175, - ), - 'Inscriptional Pahlavi' => array( - 0 => 0x10B60, - 1 => 0x10B7F, - 2 => 176, - ), - 'Old Turkic' => array( - 0 => 0x10C00, - 1 => 0x10C4F, - 2 => 177, - ), - 'Rumi Numeral Symbols' => array( - 0 => 0x10E60, - 1 => 0x10E7F, - 2 => 178, - ), - 'Brahmi' => array( - 0 => 0x11000, - 1 => 0x1107F, - 2 => 179, - ), - 'Kaithi' => array( - 0 => 0x11080, - 1 => 0x110CF, - 2 => 180, - ), - 'Cuneiform' => array( - 0 => 0x12000, - 1 => 0x123FF, - 2 => 181, - ), - 'Cuneiform Numbers and Punctuation' => array( - 0 => 0x12400, - 1 => 0x1247F, - 2 => 182, - ), - 'Egyptian Hieroglyphs' => array( - 0 => 0x13000, - 1 => 0x1342F, - 2 => 183, - ), - 'Bamum Supplement' => array( - 0 => 0x16800, - 1 => 0x16A3F, - 2 => 184, - ), - 'Kana Supplement' => array( - 0 => 0x1B000, - 1 => 0x1B0FF, - 2 => 185, - ), - 'Byzantine Musical Symbols' => array( - 0 => 0x1D000, - 1 => 0x1D0FF, - 2 => 186, - ), - 'Musical Symbols' => array( - 0 => 0x1D100, - 1 => 0x1D1FF, - 2 => 187, - ), - 'Ancient Greek Musical Notation' => array( - 0 => 0x1D200, - 1 => 0x1D24F, - 2 => 188, - ), - 'Tai Xuan Jing Symbols' => array( - 0 => 0x1D300, - 1 => 0x1D35F, - 2 => 189, - ), - 'Counting Rod Numerals' => array( - 0 => 0x1D360, - 1 => 0x1D37F, - 2 => 190, - ), - 'Mathematical Alphanumeric Symbols' => array( - 0 => 0x1D400, - 1 => 0x1D7FF, - 2 => 191, - ), - 'Mahjong Tiles' => array( - 0 => 0x1F000, - 1 => 0x1F02F, - 2 => 192, - ), - 'Domino Tiles' => array( - 0 => 0x1F030, - 1 => 0x1F09F, - 2 => 193, - ), - 'Playing Cards' => array( - 0 => 0x1F0A0, - 1 => 0x1F0FF, - 2 => 194, - ), - 'Enclosed Alphanumeric Supplement' => array( - 0 => 0x1F100, - 1 => 0x1F1FF, - 2 => 195, - ), - 'Enclosed Ideographic Supplement' => array( - 0 => 0x1F200, - 1 => 0x1F2FF, - 2 => 196, - ), - 'Miscellaneous Symbols And Pictographs' => array( - 0 => 0x1F300, - 1 => 0x1F5FF, - 2 => 197, - ), - 'Emoticons' => array( - 0 => 0x1F600, - 1 => 0x1F64F, - 2 => 198, - ), - 'Transport And Map Symbols' => array( - 0 => 0x1F680, - 1 => 0x1F6FF, - 2 => 199, - ), - 'Alchemical Symbols' => array( - 0 => 0x1F700, - 1 => 0x1F77F, - 2 => 200, - ), - 'CJK Unified Ideographs Extension B' => array( - 0 => 0x20000, - 1 => 0x2A6DF, - 2 => 201, - ), - 'CJK Unified Ideographs Extension C' => array( - 0 => 0x2A700, - 1 => 0x2B73F, - 2 => 202, - ), - 'CJK Unified Ideographs Extension D' => array( - 0 => 0x2B740, - 1 => 0x2B81F, - 2 => 203, - ), - 'CJK Compatibility Ideographs Supplement' => array( - 0 => 0x2F800, - 1 => 0x2FA1F, - 2 => 204, - ), - 'Tags' => array( - 0 => 0xE0000, - 1 => 0xE007F, - 2 => 205, - ), - 'Variation Selectors Supplement' => array( - 0 => 0xE0100, - 1 => 0xE01EF, - 2 => 206, - ), - 'Supplementary Private Use Area-A' => array( - 0 => 0xF0000, - 1 => 0xFFFFF, - 2 => 207, - ), - 'Supplementary Private Use Area-B' => array( - 0 => 0x100000, - 1 => 0x10FFFF, - 2 => 208, - ), - ); - - #calling the methods of this class only statically! - private function __construct() {} - - /** - * Remove combining diactrical marks, with possibility of the restore - * Удаляет диакритические знаки в тексте, с возможностью восстановления (опция) - * - * @param string|null $s - * @param array|null $additional_chars for example: "\xc2\xad" #soft hyphen = discretionary hyphen - * @param bool $is_can_restored - * @param array|null &$restore_table - * @return string|bool|null Returns FALSE if error occurred - */ - public static function diactrical_remove($s, $additional_chars = null, $is_can_restored = false, &$restore_table = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if ($additional_chars) - { - foreach ($additional_chars as $k => &$v) $v = preg_quote($v, '/'); - $re = '/((?>' . self::$diactrical_re . '|' . implode('|', $additional_chars) . ')+)/sxSX'; - } - else $re = '/((?>' . self::$diactrical_re . ')+)/sxSX'; - if (! $is_can_restored) return preg_replace($re, '', $s); - - $restore_table = array(); - $a = preg_split($re, $s, -1, PREG_SPLIT_DELIM_CAPTURE); - $c = count($a); - if ($c === 1) return $s; - $pos = 0; - $s2 = ''; - for ($i = 0; $i < $c - 1; $i += 2) - { - $s2 .= $a[$i]; - #запоминаем символьные (не байтовые!) позиции - $pos += self::strlen($a[$i]); - $restore_table['offsets'][$pos] = $a[$i + 1]; - } - $restore_table['length'] = $pos + self::strlen(end($a)); - return $s2 . end($a); - } - - /** - * Restore combining diactrical marks, removed by self::diactrical_remove() - * In Russian: - * Восстанавливает диакритические знаки в тексте, при условии, что их символьные позиции и кол-во символов не изменились! - * - * @see self::diactrical_remove() - * @param string|null $s - * @param array $restore_table - * @return string|bool|null Returns FALSE if error occurred (broken $restore_table) - */ - public static function diactrical_restore($s, array $restore_table) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if (! $restore_table) return $s; - if (! is_int(@$restore_table['length']) || - ! is_array(@$restore_table['offsets']) || - $restore_table['length'] !== self::strlen($s)) return false; - $a = array(); - $length = $offset = 0; - $s2 = ''; - foreach ($restore_table['offsets'] as $pos => $diactricals) - { - $length = $pos - $offset; - $s2 .= self::substr($s, $offset, $length) . $diactricals; - $offset = $pos; - } - return $s2 . self::substr($s, $offset, strlen($s)); - } - - /** - * Encodes data from another character encoding to UTF-8. - * - * @param array|scalar|null $data - * @param string $charset - * @return array|scalar|null Returns FALSE if error occurred - */ - public static function convert_from($data, $charset = 'cp1251') - { - if (! ReflectionTypeHint::isValid()) return false; - return self::_convert($data, $charset, 'UTF-8'); - } - - /** - * Encodes data from UTF-8 to another character encoding. - * - * @param array|scalar|null $data - * @param string $charset - * @return array|scalar|null Returns FALSE if error occurred - */ - public static function convert_to($data, $charset = 'cp1251') - { - if (! ReflectionTypeHint::isValid()) return false; - return self::_convert($data, 'UTF-8', $charset); - } - - /** - * Recoding the data of any structure to/from UTF-8. - * Arrays traversed recursively, recoded keys and values. - * - * @see mb_encoding_aliases() - * @param array|scalar|null $data - * @param string $charset_from - * @param string $charset_to - * @return array|scalar|null Returns FALSE if error occurred - */ - private static function _convert($data, $charset_from, $charset_to) - { - if (! ReflectionTypeHint::isValid()) return false; #for recursive calls - if ($charset_from === $charset_to) return $data; - if (is_array($data)) - { - $d = array(); - foreach ($data as $k => &$v) - { - $k = self::_convert($k, $charset_from, $charset_to); - if ($k === false) return false; - $d[$k] = self::_convert($v, $charset_from, $charset_to); - if ($d[$k] === false && ! is_bool($v)) return false; - } - return $d; - } - if (is_string($data)) - { - #smart behaviour for errors protected + speed improve - if ($charset_from === 'UTF-8' && ! self::is_utf8($data)) return $data; - if ($charset_to === 'UTF-8' && self::is_utf8($data)) return $data; - - #since PHP-5.3.x iconv() faster then mb_convert_encoding() - if (function_exists('iconv')) return iconv($charset_from, $charset_to . '//IGNORE//TRANSLIT', $data); - if (function_exists('mb_convert_encoding')) return mb_convert_encoding($data, $charset_to, $charset_from); - - #charset_from - if ($charset_from === 'UTF-16' || $charset_from === 'UCS-2') return self::_convert_from_utf16($data); - if ($charset_from === 'cp1251' || $charset_from === 'cp1259') return strtr($data, self::$cp1259_table); - if ($charset_from === 'koi8-r' || $charset_from === 'KOI8-R') return strtr(convert_cyr_string($data, 'k', 'w'), self::$cp1259_table); - if ($charset_from === 'iso8859-5') return strtr(convert_cyr_string($data, 'i', 'w'), self::$cp1259_table); - if ($charset_from === 'cp866') return strtr(convert_cyr_string($data, 'a', 'w'), self::$cp1259_table); - if ($charset_from === 'mac-cyrillic') return strtr(convert_cyr_string($data, 'm', 'w'), self::$cp1259_table); - - #charset_to - if ($charset_to === 'cp1251' || $charset_to === 'cp1259') return strtr($data, array_flip(self::$cp1259_table)); - - #last trying - if (function_exists('recode_string')) - { - $s = @recode_string($charset_from . '..' . $charset_to, $data); - if (is_string($s)) return $s; - } - - trigger_error('Convert "' . $charset_from . '" --> "' . $charset_to . '" is not supported native, "iconv" or "mbstring" extension required', E_USER_WARNING); - return false; - } - return $data; - } - - /** - * Convert UTF-16 / UCS-2 encoding string to UTF-8. - * Surrogates UTF-16 are supported! - * - * In Russian: - * Преобразует строку из кодировки UTF-16 / UCS-2 в UTF-8. - * Суррогаты UTF-16 поддерживаются! - * - * @param string $s - * @param string $type 'BE' -- big endian byte order - * 'LE' -- little endian byte order - * @param bool $to_array returns array chars instead whole string? - * @return string|array|bool UTF-8 string, array chars or FALSE if error occurred - */ - private static function _convert_from_utf16($s, $type = 'BE', $to_array = false) - { - static $types = array( - 'BE' => 'n', #unsigned short (always 16 bit, big endian byte order) - 'LE' => 'v', #unsigned short (always 16 bit, little endian byte order) - ); - if (! array_key_exists($type, $types)) - { - trigger_error('Unexpected value in 2-nd parameter, "' . $type . '" given!', E_USER_WARNING); - return false; - } - #the fastest way: - if (function_exists('iconv') || function_exists('mb_convert_encoding')) - { - if (function_exists('iconv')) $s = iconv('UTF-16' . $type, 'UTF-8', $s); - elseif (function_exists('mb_convert_encoding')) $s = mb_convert_encoding($s, 'UTF-8', 'UTF-16' . $type); - if (! $to_array) return $s; - return self::str_split($s); - } - - /* - http://en.wikipedia.org/wiki/UTF-16 - - The improvement that UTF-16 made over UCS-2 is its ability to encode - characters in planes 1-16, not just those in plane 0 (BMP). - - UTF-16 represents non-BMP characters (those from U+10000 through U+10FFFF) - using a pair of 16-bit words, known as a surrogate pair. - First 1000016 is subtracted from the code point to give a 20-bit value. - This is then split into two separate 10-bit values each of which is represented - as a surrogate with the most significant half placed in the first surrogate. - To allow safe use of simple word-oriented string processing, separate ranges - of values are used for the two surrogates: 0xD800-0xDBFF for the first, most - significant surrogate and 0xDC00-0xDFFF for the second, least significant surrogate. - - For example, the character at code point U+10000 becomes the code unit sequence 0xD800 0xDC00, - and the character at U+10FFFD, the upper limit of Unicode, becomes the sequence 0xDBFF 0xDFFD. - Unicode and ISO/IEC 10646 do not, and will never, assign characters to any of the code points - in the U+D800-U+DFFF range, so an individual code value from a surrogate pair does not ever - represent a character. - - http://www.russellcottrell.com/greek/utilities/SurrogatePairCalculator.htm - http://www.russellcottrell.com/greek/utilities/UnicodeRanges.htm - - Conversion of a Unicode scalar value S to a surrogate pair : - H = Math.floor((S - 0x10000) / 0x400) + 0xD800; - L = ((S - 0x10000) % 0x400) + 0xDC00; - The conversion of a surrogate pair to a scalar value: - N = ((H - 0xD800) * 0x400) + (L - 0xDC00) + 0x10000; - */ - $a = array(); - $hi = false; - foreach (unpack($types[$type] . '*', $s) as $codepoint) - { - #surrogate process - if ($hi !== false) - { - $lo = $codepoint; - if ($lo < 0xDC00 || $lo > 0xDFFF) $a[] = "\xEF\xBF\xBD"; #U+FFFD REPLACEMENT CHARACTER (for broken char) - else - { - $codepoint = (($hi - 0xD800) * 0x400) + ($lo - 0xDC00) + 0x10000; - $a[] = self::chr($codepoint); - } - $hi = false; - } - elseif ($codepoint < 0xD800 || $codepoint > 0xDBFF) $a[] = self::chr($codepoint); #not surrogate - else $hi = $codepoint; #surrogate was found - } - return $to_array ? $a : implode('', $a); - } - - /** - * Strips out device control codes in the ASCII range. - * - * @param string|null String to clean - * @return string|bool|null Returns FALSE if error occurred - */ - public static function strict($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]+/sSX', '', $s); - } - - /** - * Check the data accessory to the class of characters ASCII. - * For null, integer, float, boolean returns TRUE. - * - * Массивы обходятся рекурсивно, если в хотябы одном элементе массива - * его значение не ASCII, возвращается FALSE. - * - * @param array|scalar|null $data - * @return bool - */ - public static function is_ascii($data) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_array($data)) - { - foreach ($data as $k => &$v) - { - if (! self::is_ascii($k) || ! self::is_ascii($v)) return false; - } - return true; - } - #ltrim() little faster then preg_match() - #if (is_string($data)) return preg_match('/^[\x00-\x7f]*$/sSX', $data); #deprecated - if (is_string($data)) return ltrim($data, "\x00..\x7f") === ''; - if (is_scalar($data) || is_null($data)) return true; #~ null, integer, float, boolean - return false; #object or resource - } - - /** - * Returns true if data is valid UTF-8 and false otherwise. - * For null, integer, float, boolean returns TRUE. - * - * The arrays are traversed recursively, if At least one element of the array - * its value is not in UTF-8, returns FALSE. - * - * @link http://www.w3.org/International/questions/qa-forms-utf-8.html - * @link http://ru3.php.net/mb_detect_encoding - * @link http://webtest.philigon.ru/articles/utf8/ - * @link http://unicode.coeurlumiere.com/ - * @param array|scalar|null $data - * @param bool $is_strict strict the range of ASCII? - * @return bool - */ - public static function is_utf8($data, $is_strict = true) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_array($data)) - { - foreach ($data as $k => &$v) - { - if (! self::is_utf8($k, $is_strict) || ! self::is_utf8($v, $is_strict)) return false; - } - return true; - } - if (is_string($data)) - { - if (! preg_match('~~suSX', $data)) return false; - if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) return false; - #preg_match('~~suSX') much faster (up to 4 times), then mb_check_encoding($data, 'UTF-8')! - #if (function_exists('mb_check_encoding') && ! mb_check_encoding($data, 'UTF-8')) return false; #DEPRECATED - if ($is_strict && preg_match('/[^\x09\x0A\x0D\x20-\xBF\xC2-\xF7]/sSX', $data)) return false; - return true; - } - if (is_scalar($data) || is_null($data)) return true; #~ null, integer, float, boolean - return false; #object or resource - } - - /** - * Tries to detect if a string is in Unicode encoding - * - * @deprecated Slowly, use self::is_utf8() instead - * @see self::is_utf8() - * @param string $s текст - * @param bool $is_strict строгая проверка диапазона ASCII? - * @return bool - */ - public static function check($s, $is_strict = true) - { - if (! ReflectionTypeHint::isValid()) return false; - for ($i = 0, $len = strlen($s); $i < $len; $i++) - { - $c = ord($s[$i]); - if ($c < 0x80) #1 byte 0bbbbbbb - { - if ($is_strict === false || ($c > 0x1F && $c < 0x7F) || $c == 0x09 || $c == 0x0A || $c == 0x0D) continue; - } - if (($c & 0xE0) == 0xC0) $n = 1; #2 bytes 110bbbbb 10bbbbbb - elseif (($c & 0xF0) == 0xE0) $n = 2; #3 bytes 1110bbbb 10bbbbbb 10bbbbbb - elseif (($c & 0xF8) == 0xF0) $n = 3; #4 bytes 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb - elseif (($c & 0xFC) == 0xF8) $n = 4; #5 bytes 111110bb 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb - elseif (($c & 0xFE) == 0xFC) $n = 5; #6 bytes 1111110b 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb - else return false; #does not match any model - #n bytes matching 10bbbbbb follow ? - for ($j = 0; $j < $n; $j++) - { - $i++; - if ($i == $len || ((ord($s[$i]) & 0xC0) != 0x80) ) return false; - } - } - return true; - } - - /** - * Check the data in UTF-8 charset on given ranges of the standard UNICODE. - * The suitable alternative to regular expressions. - * - * For null, integer, float, boolean returns TRUE. - * - * Arrays traversed recursively (keys and values). - * At least if one array element value is not passed checking, it returns FALSE. - * - * @example - * #A simple check the standard named ranges: - * UTF8::blocks_check('поисковые системы Google и Yandex', array('Basic Latin', 'Cyrillic')); - * #You can check the named, direct ranges or codepoints together: - * UTF8::blocks_check('поисковые системы Google и Yandex', array(array(0x20, 0x7E), #[\x20-\x7E] - * array(0x0410, 0x044F), #[A-Яa-я] - * 0x0401, #russian yo (Ё) - * 0x0451, #russian ye (ё) - * 'Arrows', - * )); - * - * @link http://www.unicode.org/charts/ - * @param array|scalar|null $data - * @param array|string $blocks - * @return bool Возвращает TRUE, если все символы из текста принадлежат указанным диапазонам - * и FALSE в противном случае или для разбитого UTF-8. - */ - public static function blocks_check($data, $blocks) - { - if (! ReflectionTypeHint::isValid()) return false; - - if (is_array($data)) - { - foreach ($data as $k => &$v) - { - if (! self::blocks_check($k, $blocks) || ! self::blocks_check($v, $blocks)) return false; - } - return true; - } - - if (is_string($data)) - { - $chars = self::str_split($data); - if ($chars === false) return false; #broken UTF-8 - unset($data); #memory free - $skip = array(); #save to cache already checked symbols - foreach ($chars as $i => $char) - { - if (array_key_exists($char, $skip)) continue; #speed improve - $codepoint = self::ord($char); - if ($codepoint === false) return false; #broken UTF-8 - $is_valid = false; - $blocks = (array)$blocks; - foreach ($blocks as $j => $block) - { - if (is_string($block)) - { - if (! array_key_exists($block, self::$unicode_blocks)) - { - trigger_error('Unknown block "' . $block . '"!', E_USER_WARNING); - return false; - } - list ($min, $max) = self::$unicode_blocks[$block]; - } - elseif (is_array($block)) list ($min, $max) = $block; - elseif (is_int($block)) $min = $max = $block; - else trigger_error('A string/array/int type expected for block[' . $j . ']!', E_USER_ERROR); - if ($codepoint >= $min && $codepoint <= $max) - { - $is_valid = true; - break; - } - }#foreach - if (! $is_valid) return false; - $skip[$char] = null; - }#foreach - return true; - } - if (is_scalar($data) || is_null($data)) return true; #~ null, integer, float, boolean - return false; #object or resource - } - - /** - * Recode $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES from $charset encoding to UTF-8, if necessary. - * A side effect is a positive protection against XSS attacks with non-printable characters on the vulnerable PHP function. - * Thus web forms can be sent to the server in 2-encoding: $charset and UTF-8. - * For example: ?тест[тест]=тест - * - * Алгоритм работы: - * 1) Функция проверяет массивы $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES - * на корректность значений элементов кодировке UTF-8. - * 2) Значения не в UTF-8 принимаются как $charset и конвертируется в UTF-8, - * при этом байты от 0x00 до 0x7F (ASCII) сохраняются как есть. - * 3) Сконвертированные значения снова проверяются. - * Если данные опять не в кодировке UTF-8, то они считаются разбитыми и функция возвращает FALSE. - * - * NOTICE - * Функция должна вызываться после self::unescape_request()! - * - * @see self::unescape_request() - * @param bool $is_hex2bin Декодировать HEX-данные? - * Пример: 0xd09ec2a0d0bad0bed0bcd0bfd0b0d0bdd0b8d0b8 => О компании - * Параметры в URL адресах иногда бывает удобно кодировать не функцией rawurlencode(), - * а использовать следующий механизм (к тому же кодирующий данные более компактно): - * '0x' . bin2hex($string) - * @param string $charset - * @return bool Возвращает TRUE, если все значения элементов массивов в кодировке UTF-8 - * и FALSE + E_USER_WARNING в противном случае. - */ - public static function autoconvert_request($is_hex2bin = false, $charset = 'cp1251') - { - if (! ReflectionTypeHint::isValid()) return false; - $is_converted = false; - $is_broken = false; - foreach (array('_GET', '_POST', '_COOKIE', '_FILES') as $k => $v) - { - if (! array_key_exists($v, $GLOBALS)) continue; - #использовать array_walk_recursive() не предоставляется возможным, - #т.к. его callback функция не поддерживает передачу ключа по ссылке - $GLOBALS[$v] = self::_autoconvert_request_recursive($GLOBALS[$v], $is_converted, $is_broken, $is_hex2bin, $charset); - if ($is_broken) - { - trigger_error('Array $' . $v . ' does not have keys/values in UTF-8 charset!', E_USER_WARNING); - return false; - } - } - if ($is_converted) - { - $_REQUEST = - (isset($_COOKIE) ? $_COOKIE : array()) + - (isset($_POST) ? $_POST : array()) + - (isset($_GET) ? $_GET : array()); - } - return true; - } - - private static function _autoconvert_request_recursive(&$data, &$is_converted, &$is_broken, $is_hex2bin, $charset) - { - if ($is_broken) return $data; #speed improve - if (is_array($data)) - { - $d = array(); - foreach ($data as $k => &$v) - { - $k = self::_autoconvert_request($k, $is_converted, $is_broken, $is_hex2bin, $charset); - if ($is_broken) return $data; #speed improve - $d[$k] = self::_autoconvert_request_recursive($v, $is_converted, $is_broken, $is_hex2bin, $charset); - if ($is_broken) return $data; #speed improve - } - return $d; - } - return self::_autoconvert_request($data, $is_converted, $is_broken, $is_hex2bin, $charset); - } - - private static function _autoconvert_request(&$s, &$is_converted, &$is_broken, $is_hex2bin, $charset) - { - #regexp speed improve by using strpos() - if ($is_hex2bin && strpos($s, '0x') === 0 && preg_match('/^0x((?:[\da-fA-F]{2})+)$/sSX', $s, $m)) - { - $s = pack('H' . strlen($m[1]), $m[1]); #hex2bin() - $is_converted = true; - } - if (! self::is_utf8($s)) - { - $s = self::convert_from($s, $charset); - if ($s === false) $is_broken = true; - elseif (! self::is_utf8($s)) - { - trigger_error('String 0x ' . substr(bin2hex($s), 0, 100) . '... is not UTF-8!', E_USER_WARNING); - $is_broken = true; - } - else $is_converted = true; - } - return $s; - } - - /** - * Сравнение строк - * - * @param string|null $s1 - * @param string|null $s2 - * @param string $locale For example, 'en_CA', 'ru_RU' - * @return int|bool|null Returns FALSE if error occurred - * Returns < 0 if $s1 is less than $s2; - * > 0 if $s1 is greater than $s2; - * 0 if they are equal. - */ - public static function strcmp($s1, $s2, $locale = '') - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s1) || is_null($s2)) return null; - if (! function_exists('collator_create')) return strcmp($s1, $s2); - # PHP 5 >= 5.3.0, PECL intl >= 1.0.0 - # If empty string ("") or "root" are passed, UCA rules will be used. - $c = new Collator($locale); - if (! $c) - { - # Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened. - trigger_error(intl_get_error_message(), E_USER_WARNING); - return false; - } - return $c->compare($s1, $s2); - } - - /** - * Сравнение строк для N первых символов - * - * @param string|null $s1 - * @param string|null $s2 - * @param int $length - * @return int|bool|null Returns FALSE if error occurred - * Returns < 0 if $s1 is less than $s2; - * > 0 if $s1 is greater than $s2; - * 0 if they are equal. - */ - public static function strncmp($s1, $s2, $length) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s1) || is_null($s2)) return null; - return self::strcmp(self::substr($s1, 0, $length), self::substr($s2, 0, $length)); - } - - /** - * Implementation strcasecmp() function for UTF-8 encoding string. - * - * @param string|null $s1 - * @param string|null $s2 - * @return int|bool|null Returns FALSE if error occurred - * Returns < 0 if $s1 is less than $s2; - * > 0 if $s1 is greater than $s2; - * 0 if they are equal. - */ - public static function strcasecmp($s1, $s2) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s1) || is_null($s2)) return null; - return self::strcmp(self::lowercase($s1), self::lowercase($s2)); - } - - /** - * Converts a UTF-8 string to a UNICODE codepoints - * - * @param string|null $s UTF-8 string - * @return array|bool|null Unicode codepoints - * Returns FALSE if $s broken (not UTF-8) - */ - public static function to_unicode($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - $s2 = null; - #since PHP-5.3.x iconv() little faster then mb_convert_encoding() - if (function_exists('iconv')) $s2 = @iconv('UTF-8', 'UCS-4BE', $s); - elseif (function_exists('mb_convert_encoding')) $s2 = @mb_convert_encoding($s, 'UCS-4BE', 'UTF-8'); - if (is_string($s2)) return array_values(unpack('N*', $s2)); - if ($s2 !== null) return false; - - $a = self::str_split($s); - if ($a === false) return false; - return array_map(array(__CLASS__, 'ord'), $a); - } - - /** - * Converts a UNICODE codepoints to a UTF-8 string - * - * @param array|null $a Unicode codepoints - * @return string|bool|null UTF-8 string - * Returns FALSE if error occurred - */ - public static function from_unicode($a) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($a)) return $a; - - #since PHP-5.3.x iconv() little faster then mb_convert_encoding() - if (function_exists('iconv')) - { - array_walk($a, function(&$cp) { $cp = pack('N', $cp); }); - $s = @iconv('UCS-4BE', 'UTF-8', implode('', $a)); - if (! is_string($s)) return false; - return $s; - } - if (function_exists('mb_convert_encoding')) - { - array_walk($a, function(&$cp) { $cp = pack('N', $cp); }); - $s = mb_convert_encoding(implode('', $a), 'UTF-8', 'UCS-4BE'); - if (! is_string($s)) return false; - return $s; - } - - return implode('', array_map(array(__CLASS__, 'chr'), $a)); - } - - /** - * Converts a UTF-8 character to a UNICODE codepoint - * - * @param string|null $char UTF-8 character - * @return int|bool|null Unicode codepoint - * Returns FALSE if $char broken (not UTF-8) - */ - public static function ord($char) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($char)) return $char; - - static $cache = array(); - if (array_key_exists($char, $cache)) return $cache[$char]; #speed improve - - switch (strlen($char)) - { - case 1 : return $cache[$char] = ord($char); - case 2 : return $cache[$char] = (ord($char{1}) & 63) | - ((ord($char{0}) & 31) << 6); - case 3 : return $cache[$char] = (ord($char{2}) & 63) | - ((ord($char{1}) & 63) << 6) | - ((ord($char{0}) & 15) << 12); - case 4 : return $cache[$char] = (ord($char{3}) & 63) | - ((ord($char{2}) & 63) << 6) | - ((ord($char{1}) & 63) << 12) | - ((ord($char{0}) & 7) << 18); - default : - trigger_error('Character 0x' . bin2hex($char) . ' is not UTF-8!', E_USER_WARNING); - return false; - } - } - - /** - * Converts a UNICODE codepoint to a UTF-8 character - * - * @param int|digit|null $cp Unicode codepoint - * @return string|bool|null UTF-8 character - * Returns FALSE if error occurred - */ - public static function chr($cp) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($cp)) return $cp; - - static $cache = array(); - if (array_key_exists($cp, $cache)) return $cache[$cp]; #speed improve - - if ($cp <= 0x7f) return $cache[$cp] = chr($cp); - if ($cp <= 0x7ff) return $cache[$cp] = chr(0xc0 | ($cp >> 6)) . - chr(0x80 | ($cp & 0x3f)); - if ($cp <= 0xffff) return $cache[$cp] = chr(0xe0 | ($cp >> 12)) . - chr(0x80 | (($cp >> 6) & 0x3f)) . - chr(0x80 | ($cp & 0x3f)); - if ($cp <= 0x10ffff) return $cache[$cp] = chr(0xf0 | ($cp >> 18)) . - chr(0x80 | (($cp >> 12) & 0x3f)) . - chr(0x80 | (($cp >> 6) & 0x3f)) . - chr(0x80 | ($cp & 0x3f)); - #U+FFFD REPLACEMENT CHARACTER - return $cache[$cp] = "\xEF\xBF\xBD"; - } - - /** - * Implementation chunk_split() function for UTF-8 encoding string. - * - * @param string|null $s - * @param int|digit|null $length - * @param string|null $glue - * @return string|bool|null Returns FALSE if error occurred - */ - public static function chunk_split($s, $length = null, $glue = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - $length = intval($length); - $glue = strval($glue); - if ($length < 1) $length = 76; - if ($glue === '') $glue = "\r\n"; - if (! is_array($a = self::str_split($s, $length))) return false; - return implode($glue, $a); - } - - /** - * Changes all keys in an array - * - * @param array|null $a - * @param int $mode {CASE_LOWER|CASE_UPPER} - * @return array|bool|null Returns FALSE if error occurred - */ - public static function array_change_key_case($a, $mode) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_array($a)) return $a; - $a2 = array(); - foreach ($a as $k => $v) - { - if (is_string($k)) - { - $k = self::convert_case($k, $mode); - if ($k === false) return false; - } - $a2[$k] = $v; - } - return $a2; - } - - /** - * Конвертирует регистр букв в данных в кодировке UTF-8. - * Массивы обходятся рекурсивно, при этом конвертируются только значения - * в элементах массива, а ключи остаются без изменений. - * Для конвертирования только ключей используйте метод self::array_change_key_case(). - * - * @see self::array_change_key_case() - * @link http://www.unicode.org/charts/PDF/U0400.pdf - * @link http://ru.wikipedia.org/wiki/ISO_639-1 - * @param array|scalar|null $data Данные произвольной структуры - * @param int $mode {CASE_LOWER|CASE_UPPER} - * @param bool $is_ascii_optimization for speed improve - * @return scalar|bool|null Returns FALSE if error occurred - */ - public static function convert_case($data, $mode, $is_ascii_optimization = true) - { - if (! ReflectionTypeHint::isValid()) return false; - - if (is_array($data)) - { - foreach ($data as $k => &$v) $v = self::convert_case($v, $mode); - return $data; - } - if (! is_string($data) || ! $data) return $data; - - if ($mode === CASE_UPPER) - { - if ($is_ascii_optimization && self::is_ascii($data)) return strtoupper($data); #speed improve! - #deprecated, since PHP-5.3.x strtr() 2-3 times faster then mb_strtolower() - #if (function_exists('mb_strtoupper')) return mb_strtoupper($data, 'utf-8'); - return strtr($data, array_flip(self::$convert_case_table)); - } - if ($mode === CASE_LOWER) - { - if ($is_ascii_optimization && self::is_ascii($data)) return strtolower($data); #speed improve! - #deprecated, since PHP-5.3.x strtr() 2-3 times faster then mb_strtolower() - #if (function_exists('mb_strtolower')) return mb_strtolower($data, 'utf-8'); - return strtr($data, self::$convert_case_table); - } - trigger_error('Parameter 2 should be a constant of CASE_LOWER or CASE_UPPER!', E_USER_WARNING); - return $data; - } - - /** - * Convert a data to lower case - * - * @param array|scalar|null $data - * @return scalar|bool|null Returns FALSE if error occurred */ - public static function lowercase($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_LOWER); - } - - /** - * Convert a data to upper case - * - * @param array|scalar|null $data - * @return scalar|null Returns FALSE if error occurred - */ - public static function uppercase($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_UPPER); - } - - /** - * Convert a data to lower case - * - * @param array|scalar|null $data - * @return scalar|bool|null Returns FALSE if error occurred - */ - public static function strtolower($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_LOWER); - } - - /** - * Convert a data to upper case - * - * @param array|scalar|null $data - * @return scalar|null Returns FALSE if error occurred - */ - public static function strtoupper($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_UPPER); - } - - /** - * Convert all HTML entities to native UTF-8 characters - * Функция декодирует гораздо больше именованных сущностей, чем стандартная html_entity_decode() - * Все dec и hex сущности так же переводятся в UTF-8. - * - * Example: '"' or '"' or '"' will be converted to '"'. - * - * @link http://www.htmlhelp.com/reference/html40/entities/ - * @link http://www.alanwood.net/demos/ent4_frame.html (HTML 4.01 Character Entity References) - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset1.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset2.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset3.asp?frame=true - * - * @param scalar|null $s - * @param bool $is_special_chars Дополнительно обрабатывать специальные html сущности? (< > & ") - * @return scalar|null Returns FALSE if error occurred - */ - public static function html_entity_decode($s, $is_special_chars = false) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_string($s)) return $s; - - #speed improve - if (strlen($s) < 4 #по минимальной длине сущности - 4 байта: &#d; &xx; - || ($pos = strpos($s, '&') === false) || strpos($s, ';', $pos) === false) return $s; - - $table = self::$html_entity_table; - if ($is_special_chars) $table += self::$html_special_chars_table; - - #replace named entities - $s = strtr($s, $table); - #block below deprecated, since PHP-5.3.x strtr() 1.5 times faster - if (0 && preg_match_all('/&[a-zA-Z]++\d*+;/sSX', $s, $m, null, $pos)) - { - foreach (array_unique($m[0]) as $entity) - { - if (array_key_exists($entity, $table)) $s = str_replace($entity, $table[$entity], $s); - } - } - - #заменяем числовые dec и hex сущности: - if (strpos($s, '&#') !== false) #speed improve - { - $class = __CLASS__; - $html_special_chars_table_flipped = array_flip(self::$html_special_chars_table); - $s = preg_replace_callback('/&#((x)[\da-fA-F]{1,6}+|\d{1,7}+);/sSX', - function (array $m) use ($class, $html_special_chars_table_flipped, $is_special_chars) - { - $codepoint = isset($m[2]) && $m[2] === 'x' ? hexdec($m[1]) : $m[1]; - if (! $is_special_chars) - { - $char = pack('C', $codepoint); - if (array_key_exists($char, $html_special_chars_table_flipped)) return $html_special_chars_table_flipped[$char]; - } - return $class::chr($codepoint); - }, $s); - } - return $s; - } - - /** - * Convert special UTF-8 characters to HTML entities. - * Функция кодирует гораздо больше именованных сущностей, чем стандартная htmlentities() - * - * @link http://www.htmlhelp.com/reference/html40/entities/ - * @link http://www.alanwood.net/demos/ent4_frame.html (HTML 4.01 Character Entity References) - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset1.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset2.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset3.asp?frame=true - * - * @param scalar|null $s - * @param bool $is_special_chars_only Обрабатывать только специальные html сущности? (< > & ") - * @return scalar|null Returns FALSE if error occurred - */ - public static function html_entity_encode($s, $is_special_chars_only = false) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_string($s)) return $s; - - #if ($is_special_chars_only) return strtr($s, array_flip(self::$html_special_chars_table)); - if ($is_special_chars_only) return htmlspecialchars($s); - - #replace UTF-8 chars to named entities: - $s = strtr($s, array_flip(self::$html_entity_table)); - #block below deprecated, since PHP-5.3.x strtr() 3 times faster - if (0 && preg_match_all('~(?> [\xc2\xc3\xc5\xc6\xcb\xce\xcf][\x80-\xbf] #2 bytes - | \xe2[\x80-\x99][\x82-\xac] #3 bytes - ) - ~sxSX', $s, $m)) - { - $table = array_flip(self::$html_entity_table); - foreach (array_unique($m[0]) as $char) - { - if (array_key_exists($char, $table)) $s = str_replace($char, $table[$char], $s); - } - } - - return $s; - } - - /** - * Make regular expression for case insensitive match - * Example (non ASCII): "123_слово_test" => "123_(с|С)(л|Л)(о|О)(в|В)(о|О)_[tT][eE][sS][tT]" - * Example (only ASCII): "123_test" => "(?i:123_test)" - * - * @param string $s - * @param string|null $delimiter If the optional delimiter is specified, it will also be escaped. - * This is useful for escaping the delimiter that is required by the PCRE functions. - * The / is the most commonly used delimiter. - * @return string|bool|null Returns FALSE if error occurred - */ - public static function preg_quote_case_insensitive($s, $delimiter = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if (self::is_ascii($s)) return '(?i:' . preg_quote($s, $delimiter) . ')'; #speed improve - - $s_re = ''; - $s_lc = UTF8::lowercase($s); if ($s_lc === false) return false; - $s_uc = UTF8::uppercase($s); if ($s_uc === false) return false; - - $chars_lc = UTF8::str_split($s_lc); if ($chars_lc === false) return false; - $chars_uc = UTF8::str_split($s_uc); if ($chars_uc === false) return false; - - foreach ($chars_lc as $i => $char) - { - if ($chars_lc[$i] === $chars_uc[$i]) - $s_re .= preg_quote($chars_lc[$i], $delimiter); - elseif (self::is_ascii($chars_lc[$i])) - $s_re .= '[' . preg_quote($chars_lc[$i] . $chars_uc[$i], $delimiter) . ']'; - else - $s_re .= '(' . preg_quote($chars_lc[$i], $delimiter) . '|' - . preg_quote($chars_uc[$i], $delimiter) . ')'; - } - return $s_re; - } - - /** - * Call preg_match_all() and convert byte offsets into character offsets for PREG_OFFSET_CAPTURE flag. - * This is regardless of whether you use /u modifier. - * - * @link http://bolknote.ru/2010/09/08/~2704 - * - * @param string $pattern - * @param string|null $subject - * @param array $matches - * @param int $flags - * @param int $char_offset - * @return array|bool|null Returns FALSE if error occurred - */ - public static function preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $char_offset = 0) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($subject)) return null; - - $byte_offset = ($char_offset > 0) ? strlen(self::substr($subject, 0, $char_offset)) : $char_offset; - - $return = preg_match_all($pattern, $subject, $matches, $flags, $byte_offset); - if ($return === false) return false; - - if ($flags & PREG_OFFSET_CAPTURE) - { - foreach ($matches as &$match) - { - foreach ($match as &$a) $a[1] = self::strlen(substr($subject, 0, $a[1])); - } - } - - return $return; - } - - #alias for self::str_limit() - public static function truncate($s, $maxlength = null, $continue = "\xe2\x80\xa6", &$is_cutted = null, $tail_min_length = 20) - { - return self::str_limit($s, $maxlength, $continue, $is_cutted, $tail_min_length); - } - - /** - * Обрезает текст в кодировке UTF-8 до заданной длины, - * причём последнее слово показывается целиком, а не обрывается на середине. - * Html сущности корректно обрабатываются. - * - * @param string|null $s Текст в кодировке UTF-8 - * @param int|null|digit $maxlength Ограничение длины текста - * @param string $continue Завершающая строка, которая будет вставлена после текста, если он обрежется - * @param bool|null &$is_cutted Текст был обрезан? - * @param int|digit $tail_min_length Если длина "хвоста", оставшегося после обрезки текста, меньше $tail_min_length, - * то текст возвращается без изменений - * @return string|bool|null Returns FALSE if error occurred - */ - public static function str_limit($s, $maxlength = null, $continue = "\xe2\x80\xa6", &$is_cutted = null, $tail_min_length = 20) #"\xe2\x80\xa6" = "…" - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - $is_cutted = false; - if ($continue === null) $continue = "\xe2\x80\xa6"; - if (! $maxlength) $maxlength = 256; - - #speed improve block - #{{{ - if (strlen($s) <= $maxlength) return $s; - $s2 = str_replace("\r\n", '?', $s); - $s2 = preg_replace('/&(?> [a-zA-Z][a-zA-Z\d]+ - | \#(?> \d{1,4} - | x[\da-fA-F]{2,4} - ) - ); # html сущности (< > & ") - /sxSX', '?', $s2); - if (strlen($s2) <= $maxlength || self::strlen($s2) <= $maxlength) return $s; - #}}} - - $r = preg_match_all('/(?> \r\n # переносы строк - | &(?> [a-zA-Z][a-zA-Z\d]+ - | \#(?> \d{1,4} - | x[\da-fA-F]{2,4} - ) - ); # html сущности (< > & ") - | . - ) - /sxuSX', $s, $m); - if ($r === false) return false; - - #d($m); - if (count($m[0]) <= $maxlength) return $s; - - $left = implode('', array_slice($m[0], 0, $maxlength)); - #из диапазона ASCII исключаем буквы, цифры, открывающие парные символы [a-zA-Z\d\(\{\[] и некоторые др. символы - #нельзя вырезать в конце строки символ ";", т.к. он используются в сущностях &xxx; - $left2 = rtrim($left, "\x00..\x28\x2A..\x2F\x3A\x3C..\x3E\x40\x5B\x5C\x5E..\x60\x7B\x7C\x7E\x7F"); - if (strlen($left) !== strlen($left2)) $return = $left2 . $continue; - else - { - #добавляем остаток к обрезанному слову - $right = implode('', array_slice($m[0], $maxlength)); - preg_match('/^(?> [\d\)\]\}\-\.:]+ #цифры, закрывающие парные символы, дефис для составных слов, дата, время, IP-адреса, URL типа www.ya.ru:80! - | \p{L}+ #буквы - | \xe2\x80\x9d #закрывающие кавычки - | \xe2\x80\x99 #закрывающие кавычки - | \xe2\x80\x9c #закрывающие кавычки - | \xc2\xbb #закрывающие кавычки - )+ - /suxSX', $right, $m); - #d($m); - $right = isset($m[0]) ? rtrim($m[0], '.-') : ''; - $return = $left . $right; - if (strlen($return) !== strlen($s)) $return .= $continue; - } - if (self::strlen($s) - self::strlen($return) < $tail_min_length) return $s; - - $is_cutted = true; - return $return; - } - - /** - * Implementation str_split() function for UTF-8 encoding string. - * - * @param string|null $s - * @param int|null|digit $length - * @return array|bool|null Returns FALSE if error occurred - */ - public static function str_split($s, $length = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - $length = ($length === null) ? 1 : intval($length); - if ($length < 1) return false; - #there are limits in regexp for {min,max}! - if (preg_match_all('~.~suSX', $s, $m) === false) return false; - if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) return false; - if ($length === 1) $a = $m[0]; - else - { - $a = array(); - for ($i = 0, $c = count($m[0]); $i < $c; $i += $length) $a[] = implode('', array_slice($m[0], $i, $length)); - } - return $a; - } - - /** - * Implementation strlen() function for UTF-8 encoding string. - * - * @param string|null $s - * @return int|bool|null Returns FALSE if error occurred - */ - public static function strlen($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - //since PHP-5.3.x mb_strlen() faster then strlen(utf8_decode()) - if (function_exists('mb_strlen')) return mb_strlen($s, 'utf-8'); - - /* - utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright. - It's much faster than iconv_strlen() - Note: this function does not count bad UTF-8 bytes in the string - these are simply ignored - */ - return strlen(utf8_decode($s)); - - /* - #slowly then strlen(utf8_decode()) - if (function_exists('iconv_strlen')) return iconv_strlen($s, 'utf-8'); - - #Do not count UTF-8 continuation bytes - #return strlen(preg_replace('/[\x80-\xBF]/sSX', '', $s)); - - #slowly then strlen(utf8_decode()) - preg_match_all('~.~suSX', $str, $m); - return count($m[0]); - - #slowly then preg_match_all() + count() - $n = 0; - for ($i = 0, $len = strlen($s); $i < $len; $i++) - { - $c = ord(substr($s, $i, 1)); - if ($c < 0x80) $n++; #single-byte (0xxxxxx) - elseif (($c & 0xC0) == 0xC0) $n++; #multi-byte starting byte (11xxxxxx) - } - return $n; - */ - } - - /** - * Implementation strpos() function for UTF-8 encoding string - * - * @param string|null $s The entire string - * @param string|int $needle The searched substring - * @param int|null $offset The optional offset parameter specifies the position from which the search should be performed - * @return int|bool|null Returns the numeric position of the first occurrence of needle in haystack. - * If needle is not found, will return FALSE. - */ - public static function strpos($s, $needle, $offset = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if ($offset === null || $offset < 0) $offset = 0; - if (function_exists('mb_strpos')) return mb_strpos($s, $needle, $offset, 'utf-8'); - #iconv_strpos() deprecated, because slowly than self::strlen(substr()) - #if (function_exists('iconv_strpos')) return iconv_strpos($s, $needle, $offset, 'utf-8'); - $byte_pos = $offset; - do if (($byte_pos = strpos($s, $needle, $byte_pos)) === false) return false; - while (($char_pos = self::strlen(substr($s, 0, $byte_pos++))) < $offset); - return $char_pos; - } - - /** - * Find position of first occurrence of a case-insensitive string. - * - * @param string|null $s The entire string - * @param string|int $needle The searched substring - * @param int|null $offset The optional offset parameter specifies the position from which the search should be performed - * @return int|bool|null Returns the numeric position of the first occurrence of needle in haystack. - * If needle is not found, will return FALSE. - */ - public static function stripos($s, $needle, $offset = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if ($offset === null || $offset < 0) $offset = 0; - if (function_exists('mb_stripos')) return mb_stripos($s, $needle, $offset, 'utf-8'); - - #optimization block (speed improve) - #{{{ - $ascii_int = intval(self::is_ascii($s)) + intval(self::is_ascii($needle)); - if ($ascii_int === 1) return false; - if ($ascii_int === 2) return stripos($s, $needle, $offset); - #}}} - - $s = self::convert_case($s, CASE_LOWER, false); - if ($s === false) return false; - $needle = self::convert_case($needle, CASE_LOWER, false); - if ($needle === false) return false; - return self::strpos($s, $needle, $offset); - } - - /** - * Implementation strrev() function for UTF-8 encoding string - * - * @param string|null $s - * @return string|bool|null Returns FALSE if error occurred - */ - public static function strrev($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if (0) #TODO test speed - { - $s = self::_convert($s, 'UTF-8', 'UTF-32'); - if (! is_string($s)) return false; - $s = implode('', array_reverse(str_split($s, 4))); - return self::_convert($s, 'UTF-32', 'UTF-8'); - } - - if (! is_array($a = self::str_split($s))) return false; - return implode('', array_reverse($a)); - } - - /** - * Implementation substr() function for UTF-8 encoding string. - * - * @link http://www.w3.org/International/questions/qa-forms-utf-8.html - * @param string|null $s - * @param int|digit $offset - * @param int|null|digit $length - * @return string|bool|null Returns FALSE if error occurred - */ - public static function substr($s, $offset, $length = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - #since PHP-5.3.x mb_substr() faster then iconv_substr() - if (function_exists('mb_substr')) - { - if ($length === null) $length = self::strlen($s); - return mb_substr($s, $offset, $length, 'utf-8'); - } - if (function_exists('iconv_substr')) - { - if ($length === null) $length = self::strlen($s); - return iconv_substr($s, $offset, $length, 'utf-8'); - } - - static $_s = null; - static $_a = null; - - if ($_s !== $s) $_a = self::str_split($_s = $s); - if (! is_array($_a)) return false; - if ($length !== null) $a = array_slice($_a, $offset, $length); - else $a = array_slice($_a, $offset); - return implode('', $a); - } - - /** - * Implementation substr_replace() function for UTF-8 encoding string. - * - * @param string|null $s - * @param string|int $replacement - * @param int|digit $start - * @param int|null $length - * @return string|bool|null Returns FALSE if error occurred - */ - public static function substr_replace($s, $replacement, $start, $length = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if (! is_array($a = self::str_split($s))) return false; - array_splice($a, $start, $length, $replacement); - return implode('', $a); - } - - /** - * Implementation ucfirst() function for UTF-8 encoding string. - * Преобразует первый символ строки в кодировке UTF-8 в верхний регистр. - * - * @param string|null $s - * @param bool $is_other_to_lowercase остальные символы преобразуются в нижний регистр? - * @return string|bool|null Returns FALSE if error occurred - */ - public static function ucfirst($s, $is_other_to_lowercase = true) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - if ($s === '' || ! is_string($s)) return $s; - if (! preg_match('/^(.)(.*)$/suSX', $s, $m)) return false; - return self::uppercase($m[1]) . ($is_other_to_lowercase ? self::lowercase($m[2]) : $m[2]); - } - - /** - * Implementation ucwords() function for UTF-8 encoding string. - * Преобразует в верхний регистр первый символ каждого слова в строке в кодировке UTF-8, - * остальные символы каждого слова преобразуются в нижний регистр. - * - * @param string|null $s - * @param bool $is_other_to_lowercase остальные символы преобразуются в нижний регистр? - * @param string $spaces_re - * @return string|bool|null Returns FALSE if error occurred - */ - public static function ucwords($s, $is_other_to_lowercase = true, $spaces_re = '~([\pZ\s]+)~suSX') #\pXps is POSIX space: property Z or tab, NL, VT, FF, CR - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - - $words = preg_split($spaces_re, $s, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - foreach ($words as $k => $word) - { - $words[$k] = self::ucfirst($word, $is_other_to_lowercase = true); - if ($words[$k] === false) return false; - } - return implode('', $words); - } - - /** - * Decodes a string in the format %uXXXX or %u{XXXXXX} in the UTF-8 string. - * - * Используется для декодирования данных типа "%u0442%u0435%u0441%u0442", - * закодированных устаревшей функцией javascript://encode(). - * Рекомендуется использовать функцию javascript://encodeURIComponent(). - * - * NOTICE - * Устаревший формат %uXXXX позволяет использовать юникод только из диапазона UCS-2, т.е. от U+0 до U+FFFF - * - * @param scalar|array|null $data - * @param bool $is_rawurlencode - * @return scalar|array|null Returns FALSE if error occurred - */ - public static function unescape($data, $is_rawurlencode = false) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_array($data)) - { - $d = array(); - foreach ($data as $k => &$v) - { - $k = self::unescape($k, $is_rawurlencode); - if ($k === false) return false; - $d[$k] = self::unescape($v, $is_rawurlencode); - if ($d[$k] === false && ! is_bool($v)) return false; - } - return $d; - } - if (is_string($data)) - { - if (strpos($data, '%u') === false) return $data; #use strpos() for speed improving - return preg_replace_callback('/%u( [\da-fA-F]{4}+ #%uXXXX only UCS-2 - | \{ [\da-fA-F]{1,6}+ \} #%u{XXXXXX} extended form for all UNICODE charts - ) - /sxSX', - function (array $m) use ($is_rawurlencode) - { - $codepoint = hexdec(trim($m[1], '{}')); - $char = self::chr($codepoint); - return $is_rawurlencode ? rawurlencode($char) : $char; - }, - $data); - } - if (is_scalar($data) || is_null($data)) return $data; #~ null, integer, float, boolean - return false; #object or resource - } - - /** - * 1) Corrects the global arrays $_GET, $_POST, $_COOKIE, $_REQUEST - * decoded values ​​in the format %uXXXX and %u{XXXXXX}, encoded, - * for example, through an outdated javascript function escape(). - * Standard PHP5 cannot do it. - * 2) If in the HTTP_COOKIE there are parameters with the same name, - * takes the last value, not the first, as in the QUERY_STRING. - * 3) Creates an array of $_POST for non-standard Content-Type, for example, "Content-Type: application/octet-stream". - * Standard PHP5 creates an array for "Content-Type: application/x-www-form-urlencoded" and "Content-Type: multipart/form-data". - * - * Сессии, куки и независимая авторизация на поддоменах. - * - * ПРИМЕР 1 - * У рабочего сайта http://domain.com появились поддомены. - * Для кроссдоменной авторизации через механизм сессий имя хоста для COOKIE было изменено с "domain.com" на ".domain.com" - * В результате авторизация не работает. - * Помогает очистка COOKIE, но их принудительная очистка на тысячах пользовательских компьютеров проблематична. - * Проблема в следующем: если в HTTP_COOKIE есть параметры с одинаковым именем, то берётся последнее значение, - * а не первое, как в QUERY_STRING. - * Более подробное описание: - * PHP не правильно (?) обрабатывает заголовок HTTP_COOKIE, если там встречаются параметры с одинаковым именем, но разными значениями. - * Пример запроса HTTP-заголовка клиентом: "Cookie: sid=chpgs2fiak-330mzqza; sid=cmz5tnp5zz-xlbbgqp" - * В этом случае сервер берёт первое значение, а не последнее. - * Хотя если в QUERY_STRING есть такая ситуация, всегда берётся последний параметр. - * В HTTP_COOKIE два параметра с одинаковым именем могут появиться, если отправить клиенту следующие HTTP-заголовки: - * "Set-Cookie: sid=chpgs2fiak-330mzqza; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=domain.com" (только domain.com) - * "Set-Cookie: sid=cmz6uqorzv-1bn35110; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.domain.com" (domain.com и все его поддомены) - * Решение: поменять имя сессии. - * - * ПРИМЕР 2 - * Есть рабочие сайты: http://domain.com (основной), http://admin.domain.com (админка), - * http://sub1.domain.com (подпроект 1), http://sub2.domain.com, (подпроект 2). - * Так же имеется сервер разработки http://dev.domain.com, на котором м. б. свои поддомены. - * Требуется сделать независимую кросс-доменную авторизацию для http://*.domain.com и http://*.dev.domain.com. - * Для сохранения статуса авторизации будем использовать сессию, имя и значение которой пишется в COOKIE. - * Т. к. домены http://*.dev.domain.com имеют пересечение с доменами http://*.domain.com, - * для независимой авторизации нужно использовать разные имена сессий. - * Пример HTTP заголовков ответа сервера: - * "Set-Cookie: sid=chpgs2fiak-330mzqza; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.domain.com" (.domain.com и все его поддомены) - * "Set-Cookie: sid.dev=cmz6uqorzv-1bn35110; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.dev.domain.com" (dev.domain.com и все его поддомены) - * - * @link http://tools.ietf.org/html/rfc2965 RFC 2965 - HTTP State Management Mechanism - * @return void - */ - public static function unescape_request() - { - $fixed = false; - #ATTENTION! HTTP_RAW_POST_DATA is only accessible when Content-Type of POST request is NOT default "application/x-www-form-urlencoded"! - $HTTP_RAW_POST_DATA = isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' ? (isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : @file_get_contents('php://input')) : null; - if (ini_get('always_populate_raw_post_data')) $GLOBALS['HTTP_RAW_POST_DATA'] = $HTTP_RAW_POST_DATA; - foreach (array( '_GET' => isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null, - '_POST' => $HTTP_RAW_POST_DATA, - '_COOKIE' => isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : null, - ) as $k => $v) - { - if (! is_string($v)) continue; - if ($k === '_COOKIE') - { - $v = preg_replace('/; *+/sSX', '&', $v); - unset($_COOKIE); #будем парсить HTTP_COOKIE сами, чтобы сделать обработку как у QUERY_STRING - } - if (strpos($v, '%u') !== false) - { - parse_str(self::unescape($v, $is_rawurlencode = true), $GLOBALS[$k]); - $fixed = true; - continue; - } - if (array_key_exists($k, $GLOBALS)) continue; - parse_str($v, $GLOBALS[$k]); - $fixed = true; - } - if ($fixed) - { - $_REQUEST = - (isset($_COOKIE) ? $_COOKIE : array()) + - (isset($_POST) ? $_POST : array()) + - (isset($_GET) ? $_GET : array()); - } - } - - /** - * Calculates the height of the edit text in ",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,""],legend:[1,"
      ","
      "],area:[1,"",""],param:[1,"",""],thead:[1,"
    ","
    "],tr:[2,"","
    "],col:[2,"","
    "],td:[3,"","
    "],_default:l.htmlSerialize?[0,"",""]:[1,"X
    ","
    "]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?""!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("