Browse Source

init

master
Meik Baum 11 months ago
commit
988d292618
  1. 12
      docker-compose.yml
  2. 15
      docker-stack.yml
  3. 128
      nZEDb_data/nZEDb/.scrutinizer.yml
  4. 101
      nZEDb_data/nZEDb/.travis.yml
  5. 5629
      nZEDb_data/nZEDb/Changelog
  6. 229
      nZEDb_data/nZEDb/INSTALL.txt
  7. 150
      nZEDb_data/nZEDb/README.md
  8. 1551
      nZEDb_data/nZEDb/ReleaseNotes
  9. 43
      nZEDb_data/nZEDb/_install/install.sh
  10. 5
      nZEDb_data/nZEDb/app/.htaccess
  11. 100
      nZEDb_data/nZEDb/app/config/bootstrap.php
  12. 66
      nZEDb_data/nZEDb/app/config/bootstrap/action.php
  13. 102
      nZEDb_data/nZEDb/app/config/bootstrap/cache.php
  14. 281
      nZEDb_data/nZEDb/app/config/bootstrap/connections.php
  15. 49
      nZEDb_data/nZEDb/app/config/bootstrap/console.php
  16. 35
      nZEDb_data/nZEDb/app/config/bootstrap/errors.php
  17. 233
      nZEDb_data/nZEDb/app/config/bootstrap/g11n.php
  18. 162
      nZEDb_data/nZEDb/app/config/bootstrap/libraries.php
  19. 32
      nZEDb_data/nZEDb/app/config/bootstrap/logger.php
  20. 62
      nZEDb_data/nZEDb/app/config/bootstrap/media.php
  21. 81
      nZEDb_data/nZEDb/app/config/bootstrap/session.php
  22. 73
      nZEDb_data/nZEDb/app/config/bootstrap/yenc.php
  23. 9
      nZEDb_data/nZEDb/app/config/fix.json
  24. 105
      nZEDb_data/nZEDb/app/config/routes.php
  25. 43
      nZEDb_data/nZEDb/app/config/syntax.json
  26. 69
      nZEDb_data/nZEDb/app/controllers/CountriesController.php
  27. 80
      nZEDb_data/nZEDb/app/controllers/GroupsController.php
  28. 26
      nZEDb_data/nZEDb/app/controllers/HelloWorldController.php
  29. 73
      nZEDb_data/nZEDb/app/controllers/MultigroupPostersController.php
  30. 54
      nZEDb_data/nZEDb/app/controllers/PagesController.php
  31. 70
      nZEDb_data/nZEDb/app/controllers/PredbController.php
  32. 68
      nZEDb_data/nZEDb/app/controllers/SettingsController.php
  33. 69
      nZEDb_data/nZEDb/app/controllers/VideosController.php
  34. 52
      nZEDb_data/nZEDb/app/extensions/action/Controller.php
  35. 76
      nZEDb_data/nZEDb/app/extensions/adapter/data/source/Nntp.php
  36. 127
      nZEDb_data/nZEDb/app/extensions/adapter/data/source/database/MySql.php
  37. 0
      nZEDb_data/nZEDb/app/extensions/adapter/empty
  38. 293
      nZEDb_data/nZEDb/app/extensions/command/Update.php
  39. 162
      nZEDb_data/nZEDb/app/extensions/command/Usenet.php
  40. 159
      nZEDb_data/nZEDb/app/extensions/command/Verify.php
  41. 148
      nZEDb_data/nZEDb/app/extensions/command/Version.php
  42. 0
      nZEDb_data/nZEDb/app/extensions/command/empty
  43. 107
      nZEDb_data/nZEDb/app/extensions/command/verify/Permissions.php
  44. 259
      nZEDb_data/nZEDb/app/extensions/command/verify/Tables.php
  45. 66
      nZEDb_data/nZEDb/app/extensions/console/Command.php
  46. 368
      nZEDb_data/nZEDb/app/extensions/console/Response.php
  47. 64
      nZEDb_data/nZEDb/app/extensions/data/Model.php
  48. 0
      nZEDb_data/nZEDb/app/extensions/helper/empty
  49. 219
      nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/ControlStructuresHaveCorrectFormat.php
  50. 43
      nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/EndsWithCloseTag.php
  51. 58
      nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/HasCorrectPermissions.php
  52. 48
      nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/HasNoTrailingWhitespace.php
  53. 216
      nZEDb_data/nZEDb/app/extensions/util/Git.php
  54. 335
      nZEDb_data/nZEDb/app/extensions/util/Versions.php
  55. 83
      nZEDb_data/nZEDb/app/extensions/util/Yenc.php
  56. 58
      nZEDb_data/nZEDb/app/extensions/util/yenc/adapter/NzedbYenc.php
  57. 209
      nZEDb_data/nZEDb/app/extensions/util/yenc/adapter/Php.php
  58. 21
      nZEDb_data/nZEDb/app/index.php
  59. 2
      nZEDb_data/nZEDb/app/libraries/.gitignore
  60. 27
      nZEDb_data/nZEDb/app/models/Countries.php
  61. 31
      nZEDb_data/nZEDb/app/models/Films.php
  62. 441
      nZEDb_data/nZEDb/app/models/Groups.php
  63. 53
      nZEDb_data/nZEDb/app/models/MultigroupPosters.php
  64. 77
      nZEDb_data/nZEDb/app/models/Predb.php
  65. 30
      nZEDb_data/nZEDb/app/models/ReleasesGroups.php
  66. 294
      nZEDb_data/nZEDb/app/models/Settings.php
  67. 30
      nZEDb_data/nZEDb/app/models/SteamApps.php
  68. 151
      nZEDb_data/nZEDb/app/models/Tables.php
  69. 33
      nZEDb_data/nZEDb/app/models/Videos.php
  70. 0
      nZEDb_data/nZEDb/app/models/empty
  71. 0
      nZEDb_data/nZEDb/app/resources/g11n/empty
  72. 0
      nZEDb_data/nZEDb/app/resources/tmp/cache/templates/empty
  73. 0
      nZEDb_data/nZEDb/app/resources/tmp/logs/empty
  74. 0
      nZEDb_data/nZEDb/app/resources/tmp/tests/empty
  75. 20
      nZEDb_data/nZEDb/app/tests/cases/controllers/CountriesControllerTest.php
  76. 37
      nZEDb_data/nZEDb/app/tests/cases/controllers/MultigroupPostersControllerTest.php
  77. 37
      nZEDb_data/nZEDb/app/tests/cases/controllers/SettingsControllerTest.php
  78. 20
      nZEDb_data/nZEDb/app/tests/cases/controllers/VideosControllerTest.php
  79. 0
      nZEDb_data/nZEDb/app/tests/cases/controllers/empty
  80. 0
      nZEDb_data/nZEDb/app/tests/cases/extensions/adapter/empty
  81. 0
      nZEDb_data/nZEDb/app/tests/cases/extensions/command/empty
  82. 1
      nZEDb_data/nZEDb/app/tests/cases/extensions/data/source/empty
  83. 0
      nZEDb_data/nZEDb/app/tests/cases/extensions/helper/empty
  84. 35
      nZEDb_data/nZEDb/app/tests/cases/extensions/util/YencTest.php
  85. BIN
      nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc-test.txt
  86. 5
      nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc-test.ync
  87. BIN
      nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc1.zip
  88. BIN
      nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc2.zip
  89. 16
      nZEDb_data/nZEDb/app/tests/cases/models/CountriesTest.php
  90. 17
      nZEDb_data/nZEDb/app/tests/cases/models/MultigroupPostersTest.php
  91. 36
      nZEDb_data/nZEDb/app/tests/cases/models/SettingsTest.php
  92. 16
      nZEDb_data/nZEDb/app/tests/cases/models/VideosTest.php
  93. 0
      nZEDb_data/nZEDb/app/tests/cases/models/empty
  94. 0
      nZEDb_data/nZEDb/app/tests/functional/empty
  95. 0
      nZEDb_data/nZEDb/app/tests/integration/empty
  96. 0
      nZEDb_data/nZEDb/app/tests/mocks/empty
  97. 110
      nZEDb_data/nZEDb/app/views/_errors/development.html.php
  98. 0
      nZEDb_data/nZEDb/app/views/elements/empty
  99. 1
      nZEDb_data/nZEDb/app/views/hello_world/index.html.php
  100. 54
      nZEDb_data/nZEDb/app/views/layouts/default.html.php

12
docker-compose.yml

@ -0,0 +1,12 @@
version: '3'
services:
nzedb:
image: hub.pi-farm.duckdns.org/nzedb_aio:arm64
container_name: nzedb
ports:
- 8800:80
volumes:
- ./nZEDb_data/nZEDb:/var/www/nZEDb
- ./nZEDb_db/mysql:/var/lib/mysql
restart: unless-stopped

15
docker-stack.yml

@ -0,0 +1,15 @@
version: '3'
services:
nzedb:
image: hub.pi-farm.duckdns.org/nzedb_aio:arm64
container_name: nzedb
ports:
- 8800:80
volumes:
- /media/pi/usb_hd/docker/nzedb/nZEDb_data/nZEDb:/var/www/nZEDb
- /media/pi/usb_hd/docker/nzedb/nZEDb_db/mysql:/var/lib/mysql
deploy:
placement:
constraints:
- "node.hostname==pi-04"

128
nZEDb_data/nZEDb/.scrutinizer.yml

@ -0,0 +1,128 @@
build:
dependencies:
before:
# Overwrites inferred commands
override:
- 'composer install --no-interaction --no-dev --prefer-source --no-scripts --ignore-platform-reqs'
environment:
memcached: true
nodes:
analysis:
project_setup:
override: true
tests:
override: [php-scrutinizer-run]
php70:
environment:
php:
version: 7.0.27
ini:
memory_limit: "4096M"
php71:
environment:
php:
version: 7.1
ini:
memory_limit: "4096M"
php72:
environment:
php:
version: 7.2
ini:
memory_limit: "4096M"
checks:
php:
avoid_closing_tag: false
avoid_multiple_statements_on_same_line: true
avoid_perl_style_comments: true
avoid_superglobals: false
avoid_usage_of_logical_operators: true
blank_line_after_namespace_declaration: true
classes_in_camel_caps: true
code_rating: true
duplication: true
encourage_postdec_operator: true
encourage_single_quotes: true
fix_php_opening_tag: false
function_in_camel_caps: true
newline_at_end_of_file: true
no_exit: false
no_global_keyword: false
no_mixed_inline_html: false
no_short_method_names:
minimum: '3'
no_short_variable_names:
minimum: '3'
no_underscore_prefix_in_methods: true
no_underscore_prefix_in_properties: true
one_class_per_file: true
optional_parameters_at_the_end: true
param_doc_comment_if_not_inferrable: true
php5_style_constructor: true
properties_in_camelcaps: true
psr2_class_declaration: false
psr2_control_structure_declaration: false
psr2_switch_declaration: false
remove_php_closing_tag: false
require_braces_around_control_structures: false
security_vulnerabilities: false
side_effects_or_types: false
single_namespace_per_use: false
coding_style:
php:
braces:
classes_functions:
class: new-line
function: new-line
closure: end-of-line
do_while:
opening: end-of-line
if:
opening: end-of-line
for:
opening: end-of-line
switch:
opening: end-of-line
try:
opening: end-of-line
while:
opening: end-of-line
indentation:
general:
use_tabs: true
spaces:
around_operators:
bitwise: true
concatenation: true
other:
after_type_cast: false
upper_lower_casing:
keywords:
general: lower
constants:
true_false_null: undefined
filter:
excluded_paths:
- "docs/"
- "resources/"
- "app/config/bootstrap/action.php"
- "app/config/bootstrap/cache.php"
- "app/config/bootstrap/console.php"
- "app/config/bootstrap/errors.php"
- "app/config/bootstrap/g11n.php"
- "app/config/bootstrap/logger.php"
- "app/config/bootstrap/media.php"
- "app/config/bootstrap/session.php"
- "app/config/routes.php"
dependency_paths:
- "app/libraries/"
- "libraries/"
- "libs/"

101
nZEDb_data/nZEDb/.travis.yml

@ -0,0 +1,101 @@
language: php
sudo: required
dist: trusty
group: edge
branches:
only:
- 0.x
- Latest-testing
- dev
- nzedb-php7.2
notifications:
irc:
channels:
- "irc.synirc.net#nZEDbAnnounce"
on_success: always
on_failure: always
use_notice: true
skip_join: true
template:
- "\x030[\x0310Travis-ci\x030]\x03 Commit \x0314{%{commit}}\x03 by \x0315(%{author})\x03@\x0313%{repository_name}/%{branch}\x03 has \x037%{result}\x03: \x032%{build_url}\x03"
php:
- '7.1'
- '7.2'
addons:
mariadb: '10.0'
apt:
packages:
- apache2
- libapache2-mod-fastcgi
- curl
before_install:
- composer validate
install:
- yes '' | pecl install imagick
# Install composer packages.
- composer install --prefer-dist
before_script:
- curl -O https://raw.githubusercontent.com/nZEDb/travis-ci-files/master/cat_logs.sh
# Create mysql user.
- mysql -u root -e "GRANT ALL ON nzedb.* TO 'nzedb'@'localhost' IDENTIFIED BY 'nzedbpass';"
- mysql -u root -e "GRANT FILE ON *.* TO 'nzedb'@'localhost';"
- mysql -u root -e "GRANT SUPER ON *.* TO 'nzedb'@'localhost';"
# Disable apparmor.
- if service apparmor status; then service apparmor stop; update-rc.d -f apparmor remove; service apparmor teardown; fi
# Change MySQL settings.
- if [[ -f /etc/mysql/my.cnf ]]; then sudo sed -i "s/\[mysqld\]/\[mysqld\]\ngroup_concat_max_len = 8192/" /etc/mysql/my.cnf; fi
# Change PHP settings.
- echo 'max_execution_time = 120' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini
- echo 'memory_limit = 1024M' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini
# Enable php-fpm
- sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf
# Required for PHP 7
- if [[ -f ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf.default ]]; then sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf; fi
- sudo a2enmod rewrite actions fastcgi alias
- echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
- ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm
# Configure apache virtual hosts
- sudo a2dissite 000-default
- curl -O https://raw.githubusercontent.com/nZEDb/travis-ci-files/master/apache.conf
- sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place apache.conf
- sudo mv apache.conf /etc/apache2/sites-available/default.conf
- sudo a2ensite default.conf
- sudo sed -i "s/AllowOverride None/AllowOverride All/g" /etc/apache2/apache2.conf
- sudo sed -i "s/Require all denied/Require all granted/g" /etc/apache2/apache2.conf
- sudo service apache2 restart
# Set permissions, can't use newgrp with travis so we need to do it this way.
- sudo chmod -R 777 /home/travis/
# Download/configure nZEDb installer test script.
- curl -O https://raw.githubusercontent.com/nZEDb/travis-ci-files/master/test_nzedb_installer.sh
- sed -i 's/DBUSER=".*"/DBUSER="nzedb"/' test_nzedb_installer.sh
- sed -i 's/DBPASS=".*"/DBPASS="nzedbpass"/' test_nzedb_installer.sh
- sed -i 's/DBSOCKET=".*"/DBSOCKET=""/' test_nzedb_installer.sh
- sed -i "s?NZEDBPATH=\".*\"?NZEDBPATH=\"$(pwd)\"?" test_nzedb_installer.sh
- sed -i 's/HOST=".*"/HOST="127.0.0.1"/' test_nzedb_installer.sh
# Configure nZEDb settings.
- cp configuration/settings.example.php configuration/settings.php
- sed -i "s/'nZEDb_DEBUG', false/'nZEDb_DEBUG', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGGING', false/'nZEDb_LOGGING', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGINFO', false/'nZEDb_LOGINFO', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGNOTICE', false/'nZEDb_LOGNOTICE', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGWARNING', false/'nZEDb_LOGWARNING', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGERROR', false/'nZEDb_LOGERROR', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGFATAL', false/'nZEDb_LOGFATAL', true/" configuration/settings.php
- sed -i "s/'nZEDb_LOGQUERIES', false/'nZEDb_LOGQUERIES', true/" configuration/settings.php
script:
# Run nZEDb installer test script.
- bash test_nzedb_installer.sh
# Get contents of logs regardless of success / failure, this will help us fix potential minor issues.
after_success:
- bash cat_logs.sh
after_failure:
- bash cat_logs.sh

5629
nZEDb_data/nZEDb/Changelog

File diff suppressed because it is too large

229
nZEDb_data/nZEDb/INSTALL.txt

@ -0,0 +1,229 @@
REQUIREMENTS
Executable programs in PATH
git https://git-scm.com/downloads
which https://savannah.gnu.org/projects/which/
file http://darwinsys.com/file/
PHP
php version 5.6 or higher
(ini file settings)
date.timezone Set to your local (http://ca3.php.net/manual/en/timezones.php)
memory limit at 1024 or more (memory_limit = 1024M)
minimum execution time of 120+ seconds (max_execution_time = 120)
sessions enabled (This should be enabled by default ; http://support.qualityunit.com/021373-How-To-Enable-Session-Support-for-PHP)
Make sure you update the ini for both web (fpm or apache) and cli (the date.timezone options are important)
(extensions)
Curl
Ctype
Date
EXIF
Filter
GD
Hash
Iconv
JSON
MBString
Mcrypt
OpenSSL
PEAR
PCRE
PDO
PDO MySQL
POSIX (On unix operating systems)
Session
SimpleXML
Sockets
ZLib
Database:
MySQL 5.5+
max_allowed_packet = 16M
group_concat_max_len = 8192
Non root MySQL USER.
MySQL user with ALL permissions. (GRANT ALL ON *.* TO 'YourMySQLUsername'@'YourMySQLServerIPAddress';)
MySQL user with FILE permissions. (GRANT FILE ON *.* TO 'YourMySQLUsername'@'YourMySQLServerIPAddress';)
If the database is remote:
[client]
loose-local-infile=1
MariaDB recommended. https://mariadb.org/
Note for some linux O/S's:
Apparmor must be disabled or configured to ignore MySQL.
Web server (it is recommended to only install one, unless you know what you are doing):
Apache https://httpd.apache.org/
mod_rewrite enabled
.htaccess allow override on
In apache 2.4 Directory AllowOverride must be true.
Nginx http://nginx.org/
Lighttpd http://www.lighttpd.net/
You must set up an alias to the resources/covers folder. (apache example: Alias /covers /srv/http/nZEDb/resources/covers)
OPTIONAL REQUIREMENTS
PHP
(extensions)
Memcached (caching query results) (Memcached, not the memcache extension).
To enabled in nZEDb: www/config.php -> change MEMCACHE_ENABLED to true
simple_php_yenc_decode (https://github.com/kevinlekiller/simple_php_yenc_decode) for decoding yEnc faster.
3rd Party API Keys (recommended to get your own api keys)
tmdb http://api.themoviedb.org/2.1/
amazon https://affiliate-program.amazon.com/gp/advertising/api/detail/main.html
rottentomatoes http://developer.rottentomatoes.com
trakt.tv http://docs.trakt.apiary.io/
anidb http://anidb.net
Executable programs in PATH
unrar 3.9+ http://www.rarlab.com/download.htm
7zip http://www.7-zip.org/download.html
timeout https://www.gnu.org/software/coreutils/coreutils.html
ffmpeg or libav https://www.ffmpeg.org/download.html
mediainfo https://mediaarea.net/en/MediaInfo/Download
screen https://www.gnu.org/software/screen/
tmux
tmux http://tmux.sourceforge.net/
time https://www.gnu.org/software/time/
Daemons
Cache server (can be configured in www/settings.php):
memcached http://memcached.org/
redis http://redis.io/
IRC (see misc/IRCScraper/ folder)
znc http://wiki.znc.in/ZNC
sphinx (see www/settings.php and misc/sphinxsearch/ folder)
sphinx http://sphinxsearch.com/
INSTALLATION
See the guides here: https://github.com/nZEDb/nZEDb/wiki/Install-Guides
For other operating systems:
Install the required programs listed above, optionally install the optional requirements.
Clone the nZEDb repository using git.
Set up a virtualhost (see below for examples) on your web server for the www/ folder of the cloned git.
Browse to the install page on a web browser (http://mysite/install)
Refer to the list of requirements above if you encounter any errors during install, or the FAQ in the README.
Once installed activate only one or two groups to test with first (a.b.teevee is a good choice), this
will save you time if it is not working correctly.
Run the misc/update/update_binaries.php and misc/update/update_releases.php scripts in via command-line.
If updating was successful then you can continue to setup your site and configure the update scripts for auto-updating.
RUNNING OUTSIDE OF WEB ROOT
This is not officially supported. If you choose to do this, it is up to you to get it working ;-)
set www\.htaccess RewriteBase to your virtual directory
SAMPLE VIRTUALHOST FILES
Modify these to suit your server.
Apache 2.2:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName localhost
DocumentRoot "/srv/http/nZEDb/www"
LogLevel warn
ServerSignature Off
ErrorLog /var/log/apache2/error.log
<Directory "/srv/http/nZEDb/www">
Options FollowSymLinks
AllowOverride All
Order allow,deny
allow from all
</Directory>
Alias /covers /srv/http/nZEDb/resources/covers
</VirtualHost>
Apache 2.4:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName localhost
DocumentRoot "/srv/http/nZEDb/www"
LogLevel warn
ServerSignature Off
ErrorLog /var/log/apache2/error.log
<Directory "/srv/http/nZEDb/www">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Alias /covers /srv/http/nZEDb/resources/covers
</VirtualHost>
Nginx:
server {
listen 80 default_server;
server_name localhost;
# These are the log locations, you should not have to change these.
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# This is the root web folder for nZEDb, you shouldn't have to change this.
root /srv/http/nZEDb/www/;
index index.html index.htm index.php;
location ~* \.(?:css|eot|gif|gz|ico|inc|jpe?g|js|ogg|oga|ogv|mp4|m4a|mp3|png|svg|ttf|txt|woff|xml)$ {
expires max;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
location / {
try_files $uri $uri/ @rewrites;
}
location ^~ /covers/ {
# This is where the nZEDb covers folder should be in.
root /srv/http/nZEDb/resources;
}
location @rewrites {
rewrite ^/([^/\.]+)/([^/]+)/([^/]+)/? /index.php?page=$1&id=$2&subpage=$3 last;
rewrite ^/([^/\.]+)/([^/]+)/?$ /index.php?page=$1&id=$2 last;
rewrite ^/([^/\.]+)/?$ /index.php?page=$1 last;
}
location /admin {
}
location /install {
}
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
# Uncomment the following line and comment the .sock line if you want to use TCP.
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/var/run/php5-fpm.sock;
# The next two lines should go in your fastcgi_params
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

150
nZEDb_data/nZEDb/README.md

@ -0,0 +1,150 @@
Stable: [![Build Status](https://travis-ci.org/nZEDb/nZEDb.svg?branch=0.x)](https://travis-ci.org/nZEDb/nZEDb) Testing: [![Build Status](https://travis-ci.org/nZEDb/nZEDb.svg?branch=Latest-testing)](https://travis-ci.org/nZEDb/nZEDb) Dev: [![Build Status](https://travis-ci.org/nZEDb/nZEDb.svg?branch=dev)](https://travis-ci.org/nZEDb/nZEDb)
nZEDb automatically scans usenet, similar to the way web spiders scan the internet. It does this by collecting usenet headers and temporarily storing them in a database until they can be collated into posts/releases. It provides a web-based front-end providing search, browse, and programmable (API) functionality.
This project is a fork of the open source usenet indexer newznab plus: https://github.com/anth0/nnplus
nZEDb improves upon the original design, implementing several new features including:
- Optional multi-threaded processing (header retrieval, release creation, post-processing etc)
- Advanced search features (name, subject, category, post-date etc)
- Intelligent local caching of metadata
- Optional sharing of comments with other nZEDb sites
- Optional tmux (terminal session multiplexing) engine that provides thread, database and performance monitoring
- Image and video samples
- SABnzbd/NZBGet integration (web, API and pause/resume)
- CouchPotato integration (web and API)
## Prerequisites
System Administration know-how. nZEDb is not plug-n-play software. Installation and operation requires a moderate amount of administration experience. nZEDb is designed and developed with GNU/Linux operating systems. Certain features are not available on other platforms. An experienced Windows administrator should be able to run nZEDb on a Windows OS.
### Hardware
4GB RAM, 2 cores(threads) and 20GB disk space minimum.
If you wish to use more than 5 threads a quad core CPU is beneficial. While nZEDb can run with
these minimums, you will have very limited performance.
The overall speed of nZEDb is largely governed by performance of the database. As many of the database tables should be held within system RAM as possible. See Database Section below.
### Software
PHP (current actively supported versions and various modules)
MariaDB 10.0 (strongly preferred database choice)
The installation guides have more detailed software requirements.
### Database
Most (if not all) distributions ship MariaDB with a default configuration that will perform well on a Raspberry Pi. If you wish to store more that 500K releases, these default settings will quickly lead to poor performance. Expect this.
As a general rule of thumb the database will need a minimum of 1-2G buffer RAM for every million releases you intend to store. That RAM should be assigned to either of these two parameters:
- key_buffer_size (MyISAM)
- innodb_buffer_pool_size (InnoDB)
Use [mysqltuner.pl](http://mysqltuner.pl "MySQL tuner - Use it!") for recommendations for these and other important tuner parameters. Also refer to the project's wiki page: https://github.com/nZEDb/nZEDb/wiki/Database-tuning. This is particularly important before you start any large imports or backfills.
MariaDB is normally shipped using MyISAM tables by default. This is fine for running with one or a few threads and is a good way to start using nZEDb. You should migrate to the InnoDB table format if nZEDB is configured to use one of the following:
thread counts > 5
tmux mode
This conversion script is helpful:
misc/testing/DB/convert_mysql_tables.php
Before converting to InnoDB be sure to set:
innodb_file_per_table
<br>
## Installation
Specific installation guides for common Operating Systems can be found on the nZEDb github wiki: https://github.com/nZEDb/nZEDb/wiki/Install-Guides
## Getting Started
After you have installed nZEDb and gone throught the initial web-based installation steps (step1, step2 etc.), then review the settings on the Admin-Site-Edit page.
Most of the default settings are fine, however some will need changing.
The two amazon keys and the associate tag are needed to fetch anything from amazon. The trakt.tv key is optional, but it can help fetching extra information when tvrage and the NFO fails.
Setting the paths to unrar/ffmpeg/mediainfo is optional, but unrar is recommended for retrieving release names and finding passwords. It's best to get the very latest versions of these utilities, whatever comes as default with your distro is often not good enough.
If you have set the path to unrar, deep rar inspection is recommended.
Compressed headers are recommended if your provider supports XFeature gzip compression. (XFeature GZIP compression, originally by wafflehouse : link on pastebin was removed)
Once you have set all the options, you can enable one or two groups and start with the simple screen script running in single-threaded mode. Look in the misc/update directory; update_binaries.php downloads usenet articles into the local database; update_releases.php attempts to group these articles into releases and create NZB files.
Once you've become more familiar with the application, enable a few more groups and if needed enable multi-threading (with low thread counts i.e. < 5). We do not recommend enabling all the groups unless you have performant hardware and good database tuning knowledge.
If you want an automated way of doing this, you can use one of the scripts in the nix, or tmux folder. The Windows scripts may work.
To clean up the release names, check out fixReleaseNames.php in misc/testing.
For an overview of a complete process, look at the misc/update/nix/screen/sequential/threaded.sh script.
Advanced users may be interested to try the tmux version of nZEDb in either Complete Sequential, Sequential or non-Sequential (fully parallel) mode. Before starting, review the tmux settings in Site-Edit -> Tmux Settings.
### Support
There is a web forum were you can search for issues previously encountered by others:
https://forums.nzedb.com/
Also on IRC: irc.synirc.net #nZEDb
### Note
The nZEDb team have no control over and are not responsible for what is posted on the usenet. Best efforts are made to avoid hazardous content (e.g. virii, malware etc) by nZEDb's automated processess. If you find any objectionable content, please direct any complaints to your usenet provider.
### The Team
Kevin123, jonnyboy, Miatrix, zombu2, Codeslave, sinfuljosh, ugo, Whitelighter, Bart39, archer(niel), ThePeePs, ruhllatio, DariusIII<br /><br />
<a href="https://nzedb.github.io/donate" target="_blank">Donate</a>
<p>
### Licenses
nZEDb is GPL v3. See /docs/LICENSE.txt for the full license.
Other licenses by various software used by nZEDb:
Git.php => MIT and GPL v3
Net_NNTP => W3C
PHPMailer => GNU Lesser General Public License
forkdaemon-php => Barracuda Networks, Inc.
getid3 => GPL v3
password_compat => Anthony Ferrara
rarinfo => Modified BSD
smarty => GNU Lesser General Public v2.1
AmazonProductAPI.php => Sameer Borate
GiantBombAPI.php => MIT
TMDb PHP API class => BSD
TVDB PHP API => Moinax
TVMaze PHP API => JPinkney
Zip file creation class => No license specified.
simple_html_dom.php => MIT
All external libraries will have their full licenses in their respective folders.
Some licenses might have been missed in this document for various external software, they will be included in their respectful folders.

1551
nZEDb_data/nZEDb/ReleaseNotes

File diff suppressed because it is too large

43
nZEDb_data/nZEDb/_install/install.sh

@ -0,0 +1,43 @@
#!/bin/bash
echo "nZEDb Installer"
echo "----------------------"
echo ""
echo "Getting the nZEDb app from GitHub"
echo ""
git clone https://github.com/nZEDb/nZEDb.git
cd nZEDb
echo ""
if type -p composer >/dev/null 2>&1; then
composer install
else if [ -f "composer.phar" ]; then
php composer.phar install
else
echo ""
echo "Getting Composer for you..."
curl -sS https://getcomposer.org/installer | php
php composer.phar install
fi
fi
echo ""
echo "Setting cache directory permissions for you..."
sudo chown -R www-data:www-data /var/lib/php/sessions/
chmod 755 ./
chmod -R g+s ./
chmod -R 755 app/libraries
chmod -R 775 app/resources
chmod -R 775 configuration
chmod -R 775 libraries
chmod -R 775 resources
chmod -R 775 www
chmod +x ./zed
alias zed='./zed'
echo ""
echo ""
echo "Installation complete."
echo "Now run the setup via the web site's /install page."
echo "------------------------"

5
nZEDb_data/nZEDb/app/.htaccess

@ -0,0 +1,5 @@
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>

100
nZEDb_data/nZEDb/app/config/bootstrap.php

@ -0,0 +1,100 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* @copyright Copyright 2015, Union of RAD
* @license http://opensource.org/licenses/bsd-license.php The BSD License
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config;
/**
* Load nZEDb global constants.
*/
require_once \dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'nzedb' . DIRECTORY_SEPARATOR . 'constants.php';
/**
* This is the primary bootstrap file of your application, and is loaded immediately after the front
* controller (`webroot/index.php`) is invoked. It includes references to other feature-specific
* bootstrap files that you can turn on and off to configure the services needed for your
* application.
*
* Besides global configuration of external application resources, these files also include
* configuration for various classes to interact with one another, usually through _filters_.
* Filters are Lithium's system of creating interactions between classes without tight coupling. See
* the `Filters` class for more information.
*
* If you have other services that must be configured globally for the entire application, create a
* new bootstrap file and `require` it here.
*
* @see lithium\aop\Filters
*/
/**
* The libraries file contains the loading instructions for all plugins, frameworks and other class
* libraries used in the application, including the Lithium core, and the application itself. These
* instructions include library names, paths to files, and any applicable class-loading rules. This
* file also statically loads common classes to improve bootstrap performance.
*/
require_once __DIR__ . '/bootstrap/libraries.php';
/**
* The error configuration allows you to use the filter system along with the advanced matching
* rules of the `ErrorHandler` class to provide a high level of control over managing exceptions in
* your application, with no impact on framework or application code.
*/
// require __DIR__ . '/bootstrap/errors.php';
/**
* This file defines bindings between classes which are triggered during the request cycle, and
* allow the framework to automatically configure its environmental settings. You can add your own
* behavior and modify the dispatch cycle to suit your needs.
*/
require_once __DIR__ . '/bootstrap/action.php';
/**
* This file contains configurations for connecting to external caching resources, as well as
* default caching rules for various systems within your application
*/
if (PHP_SAPI !== 'cli') {
require __DIR__ . '/bootstrap/cache.php';
}
/**
* Include this file if your application uses one or more database connections.
*/
require_once __DIR__ . '/bootstrap/connections.php';
/**
* This file contains configuration for session (and/or cookie) storage, and user or web service
* authentication.
*/
// require __DIR__ . '/bootstrap/session.php';
/**
* This file contains your application's globalization rules, including inflections,
* transliterations, localized validation, and how localized text should be loaded. Uncomment this
* line if you plan to globalize your site.
*/
// require __DIR__ . '/bootstrap/g11n.php';
/**
* This file contains configurations for handling different content types within the framework,
* including converting data to and from different formats, and handling static media assets.
*/
// require __DIR__ . '/bootstrap/media.php';
/**
* This file configures console filters and settings, specifically output behavior and coloring.
*/
if (PHP_SAPI === 'cli') {
require_once __DIR__ . '/bootstrap/console.php';
}
require_once __DIR__ . '/bootstrap/logger.php';
/**
* This file configures the yEnc utility class for using available extensions.
*/
require_once __DIR__ . '/bootstrap/yenc.php';
?>

66
nZEDb_data/nZEDb/app/config/bootstrap/action.php

@ -0,0 +1,66 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
* Copyright 2009, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
//use Exception;
use lithium\action\Dispatcher;
use lithium\aop\Filters;
use lithium\core\Environment;
use lithium\core\Libraries;
/**
* This filter intercepts the `run()` method of the `Dispatcher`, and first passes the `'request'`
* parameter (an instance of the `Request` object) to the `Environment` class to detect which
* environment the application is running in. Then, loads all application routes in all plugins,
* loading the default application routes last.
* Change this code if plugin routes must be loaded in a specific order (i.e. not the same order as
* the plugins are added in your bootstrap configuration), or if application routes must be loaded
* first (in which case the default catch-all routes should be removed).
* If `Dispatcher::run()` is called multiple times in the course of a single request, change the
* `include`s to `include_once`.
*
* @see lithium\action\Request
* @see lithium\core\Environment
* @see lithium\net\http\Router
*/
Filters::apply(Dispatcher::class, 'run', function ($params, $next) {
Environment::set($params['request']);
foreach (array_reverse(Libraries::get()) as $name => $config) {
if ($name === 'lithium') {
continue;
}
$file = "{$config['path']}/config/routes.php";
file_exists($file) ? \call_user_func(function () use ($file) { include $file; }) : null;
}
return $next($params);
});
/**
* This filter protects against HTTP host header attacks, by matching the `Host` header
* sent by the client against a known list of good hostnames. You'll need to modify
* the list of hostnames inside the filter before using it.
*
* @link http://li3.me/docs/book/manual/1.x/quality-code/security
* @link http://www.skeletonscribe.net/2013/05/practical-http-host-header-attacks.html
*/
// Filters::apply(Dispatcher::class, 'run', function($params, $next) {
// $whitelist = [
// 'example.org',
// 'www.example.org'
// ];
// foreach ($whitelist as $host) {
// if ($params['request']->host === $host) {
// return $next($params);
// }
// }
// throw new Exception('Suspicious Operation');
// });
?>

102
nZEDb_data/nZEDb/app/config/bootstrap/cache.php

@ -0,0 +1,102 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
* Copyright 2010, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\action\Dispatcher;
use lithium\aop\Filters;
use lithium\storage\Cache;
use lithium\core\Libraries;
use lithium\core\Environment;
use lithium\data\source\database\adapter\MySql;
use lithium\data\source\database\adapter\PostgreSql;
use lithium\data\source\database\adapter\Sqlite3;
/**
* Configuration
*
* Configures the adapters to use with the cache class. Available adapters are `Memcache`,
* `File`, `Redis`, `Apc`, `XCache` and `Memory`. Please see the documentation on the
* adapters for specific characteristics and requirements.
*
* By default the almost always available `File` cache adapter is used below. This
* is for getting oyu up and running only and should be replaced with a better Cache
* configuration, based on the cache/s you plan to use.
*
* @see lithium\storage\Cache
* @see lithium\storage\cache\adapters
* @see lithium\storage\cache\strategies
*/
Cache::config([
'default' => [
'adapter' => 'File',
'strategies' => ['Serializer']
]
]);
// Cache::config([
// 'default' => [
// 'adapter' => 'Memcache',
// 'scope' => hash('md5', LITHIUM_APP_PATH)
// ]
// ]);
/**
* Apply
*
* Applies caching to neuralgic points of the framework but only when we are running
* in production. This is also a good central place to add your own caching rules.
* A couple of caching rules are already defined below:
*
* 1. Cache paths for auto-loaded and service-located classes.
* 2. Cache describe calls on all connections that use a `Database` based adapter.
*
* @see lithium\core\Environment
* @see lithium\core\Libraries
*/
if (!Environment::is('production')) {
return;
}
Filters::apply(Dispatcher::class, 'run', function ($params, $next) {
$cacheKey = 'core.libraries';
if ($cached = Cache::read('default', $cacheKey)) {
$cached = (array)$cached + Libraries::cache();
Libraries::cache($cached);
}
$result = $next($params);
if ($cached != ($data = Libraries::cache())) {
Cache::write('default', $cacheKey, $data, '+1 day');
}
return $result;
});
$schemaCache = function ($params, $next) {
if ($params['fields']) {
return $next($params);
}
$cacheKey = "data.connections.{$params['meta']['connection']}.";
$cacheKey .= "sources.{$params['entity']}.schema";
return Cache::read('default',
$cacheKey,
[
'write' => function () use ($params, $next) {
return ['+1 day' => $next($params)];
}
]);
};
Filters::apply(MySql::class, 'describe', $schemaCache);
Filters::apply(PostgreSql::class, 'describe', $schemaCache);
Filters::apply(Sqlite3::class, 'describe', $schemaCache);
?>

281
nZEDb_data/nZEDb/app/config/bootstrap/connections.php

@ -0,0 +1,281 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* @copyright Copyright 2015, Union of RAD
* @license http://opensource.org/licenses/bsd-license.php The BSD License
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\data\Connections;
/**
* ### Configuring backend database connections
*
* Lithium supports a wide variety relational and non-relational databases, and is designed to allow
* and encourage you to take advantage of multiple database technologies, choosing the most optimal
* one for each task.
*
* As with other `Adaptable`-based configurations, each database configuration is defined by a name,
* and an array of information detailing what database adapter to use, and how to connect to the
* database server. Unlike when configuring other classes, `Connections` uses two keys to determine
* which class to select. First is the `'type'` key, which specifies the type of backend to
* connect to. For relational databases, the type is set to `'database'`. For HTTP-based backends,
* like CouchDB, the type is `'http'`. Some backends have no type grouping, like MongoDB, which is
* unique and connects via a custom PECL extension. In this case, the type is set to `'MongoDb'`,
* and no `'adapter'` key is specified. In other cases, the `'adapter'` key identifies the unique
* adapter of the given type, i.e. `'MySql'` for the `'database'` type, or `'CouchDb'` for the
* `'http'` type. Note that while adapters are always specified in CamelCase form, types are
* specified either in CamelCase form, or in underscored form, depending on whether an `'adapter'`
* key is specified. See the examples below for more details.
*
* ### Multiple environments
*
* As with other `Adaptable` classes, `Connections` supports optionally specifying different
* configurations per named connection, depending on the current environment. For information on
* specifying environment-based configurations, see the `Environment` class.
*
* @see lithium\core\Adaptable
* @see lithium\core\Environment
*/
/**
* Uncomment this configuration to use MongoDB as your default database.
*/
// Connections::add('default', [
// 'type' => 'MongoDb',
// 'host' => 'localhost',
// 'database' => 'app'
// ]);
/**
* Uncomment this configuration to use CouchDB as your default database.
*/
// Connections::add('default', [
// 'type' => 'http',
// 'adapter' => 'CouchDb',
// 'host' => 'localhost',
// 'database' => 'app'
// ]);
/**
* Uncomment this configuration to use MySQL as your default database.
*
* Strict mode can be enabled or disabled, older MySQL versions were
* by default non-strict.
*/
// Connections::add('default', [
// 'type' => 'database',
// 'adapter' => 'MySql',
// 'host' => 'localhost',
// 'login' => 'root',
// 'password' => '',
// 'database' => 'app',
// 'encoding' => 'UTF-8',
// 'strict' => false
// ]);
use app\models\Settings;
use nzedb\utility\Misc;
\lithium\util\Inflector::rules('uninflected', ['predb']);
if (! \defined('DB_MOCK')) {
// Add new condition to use DB_MOCK mode here.
if (\defined('MAINTENANCE_MODE_ENABLED') && MAINTENANCE_MODE_ENABLED == true) {
\define('DB_MOCK', true);
} else {
\define('DB_MOCK', false);
}
}
if (DB_MOCK === true) {
if (\defined('nZEDb_DEBUG') && nZEDb_DEBUG === true) {
echo 'No connection defined, using mock connection.' . PHP_EOL;
}
Connections::add('mock',
[
'type' => 'database',
'adapter' => 'Mock',
'host' => 'localhost',
'port' => '3306',
'login' => 'root',
'password' => 'root_pass',
'database' => 'nZEDb',
'encoding' => 'UTF-8',
'timezone' => ini_get('date.timezone'),
]
);
}
// Check for install.lock first. If it exists, so should config.php
if (file_exists(INSTALLED)) {
// This allows us to set up a db config separate to that created by /install
$config1 = LITHIUM_APP_PATH . DS . 'config' . DS . 'db-config.php';
$config2 = nZEDb_CONFIGS . 'config.php';
$config = file_exists($config1) ? $config1 : $config2;
if (!file_exists($config)) {
throw new \ErrorException(
"No valid configuration file found at '$config'"
);
}
require_once $config;
switch (DB_SYSTEM) {
case 'mysql':
$adapter = 'MySql';
break;
case 'pgsql':
$adapter = 'PostgreSql';
break;
default:
break;
}
if (isset($adapter)) {
if (empty(DB_SOCKET)) {
$host = empty(DB_PORT) ? DB_HOST : DB_HOST . ':' . DB_PORT;
} else {
$host = DB_SOCKET;
}
Connections::add('default',
[
'type' => 'database',
'adapter' => $adapter,
'host' => $host,
'login' => DB_USER,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'encoding' => 'UTF-8',
'persistent' => false,
'timezone' => ini_get('date.timezone'),
]
);
Connections::add('information_schema',
[
'type' => 'database',
'adapter' => $adapter,
'host' => $host,
'login' => DB_USER,
'password' => DB_PASSWORD,
'database' => 'information_schema',
'encoding' => 'UTF-8',
'persistent' => false,
'timezone' => ini_get('date.timezone'),
]
);
try {
Misc::setCoversConstant(
Settings::value('site.main.coverspath')
);
} catch (\Error $e) {
echo $e->getMessage() . \PHP_EOL;
exit();
}
} else {
throw new \ErrorException(
"No valid database adapter provided in configuration file '$config'"
);
}
} else if (file_exists(nZEDb_CONFIGS . 'dev-config.json')) {
$config = json_decode(file_get_contents(nZEDb_CONFIGS . 'dev-config.json'), true);
$db =& $config['db'];
switch ($db['system']) {
case 'mysql':
$adapter = 'MySql';
break;
case 'pgsql':
$adapter = 'PostgreSql';
break;
default:
throw new \RuntimeException('Invalid database system in dev-config file!');
break;
}
if (empty($db['socket'])) {
$host = empty($db['port']) ? $db['host'] : $db['host'] . ':' . $db['port'];
} else {
$host = $db['socket'];
}
Connections::add('default',
[
'type' => 'database',
'adapter' => $adapter,
'host' => $host,
'login' => $db['user'],
'password' => $db['password'],
'database' => $db['database'],
'encoding' => 'UTF-8',
'persistent' => $db['persist'],
'timezone' => ini_get('date.timezone'),
// If enabled this forces all table column names to be lower-cased. This should only
// be needed by users with long standing databases that were created with upper-cased
// names for some fields.
'lowercase' => false,
]
);
if ($config['debug']['enabled'] === true) {
if (!defined('DB_SYSTEM')) {
define('DB_SYSTEM', strtolower($adapter));
}
if (!defined('DB_HOST')) {
define('DB_HOST', $db['host']);
}
if (!defined('DB_PORT')) {
define('DB_PORT', $db['port']);
}
if (!defined('DB_SOCKET')) {
define('DB_SOCKET', $db['socket']);
}
if (!defined('DB_USER')) {
define('DB_USER', $db['user']);
}
if (!defined('DB_PASSWORD')) {
define('DB_PASSWORD', $db['password']);
}
if (!defined('DB_NAME')) {
define('DB_NAME', $db['database']);
}
if (!defined('DB_PCONNECT')) {
define('DB_PCONNECT', $db['persist']);
}
$usp =& $config['usp'];
define('NNTP_USERNAME', $usp['connection1']['username']);
define('NNTP_PASSWORD', $usp['connection1']['password']);
define('NNTP_SERVER', $usp['connection1']['server']);
define('NNTP_PORT', $usp['connection1']['port']);
define('NNTP_SSLENABLED', $usp['connection1']['ssl']);
define('NNTP_SOCKET_TIMEOUT', $usp['connection1']['timeout']);
define('NNTP_USERNAME_A', $usp['connection2']['username']);
define('NNTP_PASSWORD_A', $usp['connection2']['password']);
define('NNTP_SERVER_A', $usp['connection2']['server']);
define('NNTP_PORT_A', $usp['connection2']['port']);
define('NNTP_SSLENABLED_A', $usp['connection2']['ssl']);
define('NNTP_SOCKET_TIMEOUT_A', $usp['connection2']['timeout']);
}
Misc::setCoversConstant(
Settings::value('site.main.coverspath')
);
}
?>

49
nZEDb_data/nZEDb/app/config/bootstrap/console.php

@ -0,0 +1,49 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* Copyright 2010, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\aop\Filters;
use lithium\console\Dispatcher;
use lithium\core\Environment;
use lithium\core\Libraries;
/**
* This filter sets the environment based on the current request. By default, `$request->env`, for
* example in the command `li3 help --env=production`, is used to determine the environment.
*
* Routes are also loaded, to facilitate URL generation from within the console environment.
*/
Filters::apply(Dispatcher::class, 'run', function ($params, $next)
{
Environment::set($params['request']);
foreach (array_reverse(Libraries::get()) as $name => $config) {
if ($name === 'lithium') {
continue;
}
$file = "{$config['path']}/config/routes.php";
file_exists($file) ? \call_user_func(function () use ($file) { include $file; }) : null;
}
return $next($params);
});
/**
* This filter will convert {:heading} to the specified color codes. This is useful for colorizing
* output and creating different sections.
*/
// Filters::apply(Dispatcher::class, '_call', function($params, $next) {
// $params['callable']->response->styles([
// 'heading' => '\033[1;30;46m'
// ]);
// return $next($params);
// });
?>

35
nZEDb_data/nZEDb/app/config/bootstrap/errors.php

@ -0,0 +1,35 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
* Copyright 2011, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\action\Dispatcher;
use lithium\core\ErrorHandler;
use lithium\action\Response;
use lithium\net\http\Media;
ErrorHandler::apply(Dispatcher::class . '::run', [], function ($info, $params)
{
$response = new Response([
'request' => $params['request'],
'status' => $info['exception']->getCode()
]);
Media::render($response, compact('info', 'params'),
[
'library' => true,
'controller' => '_errors',
'template' => 'development',
'layout' => 'error',
'request' => $params['request']
]
);
return $response;
});
?>

233
nZEDb_data/nZEDb/app/config/bootstrap/g11n.php

@ -0,0 +1,233 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* Copyright 2010, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\action\Dispatcher as ActionDispatcher;
use lithium\aop\Filters;
use lithium\core\Libraries;
use lithium\console\Dispatcher as ConsoleDispatcher;
use lithium\core\Environment;
use lithium\g11n\Locale;
use lithium\g11n\Catalog;
use lithium\g11n\Message;
use lithium\g11n\Multibyte;
use lithium\net\http\Media;
use lithium\util\Inflector;
use lithium\util\Validator;
/**
* Dates
*
* Sets the default timezone used by all date/time functions.
*/
date_default_timezone_set('UTC');
/**
* Locales
*
* Adds globalization specific settings to the environment. The settings for
* the current locale, time zone and currency are kept as environment settings.
* This allows for _centrally_ switching, _transparently_ setting and
* retrieving globalization related settings.
*
* The environment settings are:
*
* - `'locale'` The default effective locale.
* - `'locales'` Application locales available mapped to names. The available locales are used
* to negotiate he effective locale, the names can be used i.e. when displaying
* a menu for choosing the locale to users.
*
* @see lithium\g11n\Message
* @see lithium\core\Environment
*/
$locale = 'en';
$locales = ['en' => 'English'];
Environment::set('production', compact('locale', 'locales'));
Environment::set('development', compact('locale', 'locales'));
Environment::set('test', ['locale' => 'en', 'locales' => ['en' => 'English']]);
/**
* Effective/Request Locale
*
* Intercepts dispatching processes in order to set the effective locale by using
* the locale of the request or if that is not available retrieving a locale preferred
* by the client.
*
* @see lithium\g11n\Message
* @see lithium\core\Environment
*/
$setLocale = function ($params, $next) {
if (!$params['request']->locale()) {
$params['request']->locale(Locale::preferred($params['request']));
}
Environment::set(true, ['locale' => $params['request']->locale()]);
return $next($params);
};
Filters::apply(ActionDispatcher::class, '_callable', $setLocale);
Filters::apply(ConsoleDispatcher::class, '_callable', $setLocale);
/**
* Resources
*
* Globalization (g11n) catalog configuration. The catalog allows for obtaining and
* writing globalized data. Each configuration can be adjusted through the following settings:
*
* - `'adapter'` _string_: The name of a supported adapter. The builtin adapters are `Memory` (a
* simple adapter good for runtime data and testing), `Php`, `Gettext`, `Cldr` (for
* interfacing with Unicode's common locale data repository) and `Code` (used mainly for
* extracting message templates from source code).
*
* - `'path'` All adapters with the exception of the `Memory` adapter require a directory
* which holds the data.
*
* - `'scope'` If you plan on using scoping i.e. for accessing plugin data separately you
* need to specify a scope for each configuration, except for those using the `Memory`,
* `Php` or `Gettext` adapter which handle this internally.
*
* @see lithium\g11n\Catalog
* @link https://github.com/UnionOfRAD/li3_lldr
* @link https://github.com/UnionOfRAD/li3_cldr
*/
Catalog::config([
'runtime' => [
'adapter' => 'Memory'
],
// 'app' => [
// 'adapter' => 'Gettext',
// 'path' => Libraries::get(true, 'resources') . '/g11n'
// ],
'lithium' => [
'adapter' => 'Php',
'path' => LITHIUM_LIBRARY_PATH . '/lithium/g11n/resources/php'
]
] + Catalog::config());
/**
* Multibyte Strings
*
* Configuration for the `Multibyte` class which allows to work with UTF-8
* encoded strings. At least one configuration named `'default'` must be
* present. Available adapters are `Intl`, `Mbstring` and `Iconv`. Please keep
* in mind that each adapter may act differently upon input containing bad
* UTF-8 sequences. These differences aren't currently equalized or abstracted
* away.
*
* @see lithium\g11n\Multibyte
*/
Multibyte::config([
// 'default' => ['adapter' => 'Intl'],
'default' => ['adapter' => 'Mbstring'],
// 'default' => ['adapter' => 'Iconv']
] + Multibyte::config());
/**
* Transliteration
*
* Load locale specific transliteration rules through the `Catalog` class or
* specify them manually to make `Inflector::slug()` work better with
* characters specific to a locale.
*
* @see lithium\g11n\Catalog
* @see lithium\util\Inflector::slug()
*/
// Inflector::rules('transliteration', Catalog::read(true, 'inflection.transliteration', 'en'));
// Inflector::rules('transliteration', ['/É|Ê/' => 'E']);
/**
* Grammar
*
* If your application has custom singular or plural rules you can configure
* that by uncommenting the lines below.
*
* @see lithium\g11n\Catalog
* @see lithium\util\Inflector
*/
// Inflector::rules('singular', ['rules' => ['/rata/' => '\1ratus']]);
// Inflector::rules('singular', ['irregular' => ['foo' => 'bar']]);
// Inflector::rules('plural', ['rules' => ['/rata/' => '\1ratum']]);
// Inflector::rules('plural', ['irregular' => ['bar' => 'foo']]);
// Inflector::rules('uninflected', 'bord');
// Inflector::rules('uninflected', ['bord', 'baird']);
/**
* Validation
*
* Overwrites certain validation rules in order to make them locale aware. Locale
* specific versions are added as formats to those rules. In order to validate a
* german postal code you may use the following configuration in a model.
*
* {{{
* // ...
* public $validates = (
* 'zip' => [
* ['postalCode', 'format' => 'de_DE']
* ]
* // ...
* }}}
*
* When no format or the special `any` format is provided the rule will use the
* built-in regular expression. This ensures that default behavior isn't affected.
*
* The regular expression for a locale aware rule is retrieved using the `Catalog`
* class. To add support for more locales and rules have a look at the `li3_lldr`
* and `li3_cldr` projects.
*
* Further enables support for multibyte strings through the `Multibyte` class by
* overwriting rules (currently just `lengthBetween`).
*
* @link https://github.com/UnionOfRAD/li3_lldr
* @link https://github.com/UnionOfRAD/li3_cldr
* @see lithium\g11n\Catalog
* @see lithium\g11n\Multibyte
* @see lithium\util\Validator
*/
foreach (['phone', 'postalCode', 'ssn'] as $name) {
$regex = Validator::rules($name);
Validator::add($name, function ($value, $format, $options) use ($name, $regex) {
if ($format !== 'any') {
$regex = Catalog::read(true, "validation.{$name}", $format);
}
if (!$regex) {
$message = "Cannot find regular expression for validation rule `{$name}` ";
$message .= "using format/locale `{$format}`.";
throw new RuntimeException($message);
}
return preg_match($regex, $value);
});
}
Validator::add('lengthBetween', function ($value, $format, $options) {
$length = Multibyte::strlen($value);
$options += ['min' => 1, 'max' => 255];
return ($length >= $options['min'] && $length <= $options['max']);
});
/**
* In-View Translation
* Integration with `View`. Embeds message translation aliases into the `View`
* class (or other content handler, if specified) when content is rendered. This
* enables translation functions, i.e. `<?=$t("Translated content"); ?>`.
*
* @see lithium\g11n\Message::aliases()
* @see lithium\net\http\Media
*/
Filters::apply(Media::class, '_handle', function ($params, $next) {
$params['handler'] += ['outputFilters' => []];
$params['handler']['outputFilters'] += Message::aliases();
return $next($params);
});
?>

162
nZEDb_data/nZEDb/app/config/bootstrap/libraries.php

@ -0,0 +1,162 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* @copyright Copyright 2015, Union of RAD
* @license http://opensource.org/licenses/bsd-license.php The BSD License
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
/**
* The libraries file is where you configure the various plugins, frameworks, and other libraries
* to be used by your application, including your application itself. This file also defines some
* global constants used to tell Lithium where to find your application and support libraries
* (including Lithium itself). It uses the `Libraries` class to add configurations for the groups of
* classes used in your app.
*
* In Lithium, a _library_ is any collection of classes located in a single base directory, which
* all share the same class-to-file naming convention, and usually a common class or namespace
* prefix. While all collections of classes are considered libraries, there are two special types of
* libraries:
*
* - **Applications**: Applications are libraries which follow the organizational conventions that
* Lithium defines for applications (see `Libraries::locate()` and `Libraries::paths()`), and
* which also include a web-accessible document root (i.e. the `webroot/` folder), and can
* dispatch HTTP requests (i.e. through `webroot/index.php`).
*
* - **Plugins**: Plugins are libraries which generally follow the same organizational conventions
* as applications, but are designed to be used within the context of another application. They
* _may_ include a public document root for supporting assets, but this requires a symlink from
* `libraries/<plugin-name>/webroot` to `<app-name>/webroot/<plugin-name>` (recommended for
* production), or a media filter to load plugin resources (see `/config/bootstrap/media.php`).
*
* Note that a library can be designed as both an application and a plugin, but this requires some
* special considerations in the bootstrap process, such as removing any `require` statements, and
* conditionally defining the constants below.
*
* By default, libraries are stored in the base `/libraries` directory, or in the
* application-specific `<app-name>/libraries` directory. Libraries can be loaded from either place
* without additional configuration, but note that if the same library is in both directories, the
* application-specific `libraries` directory will override the global one.
*
* The one exception to this is the _primary_ library, which is an application configured with
* `'default' => true` (see below); this library uses the `LITHIUM_APP_PATH` constant (also defined
* below) as its path. Note, however, that any library can be overridden with an arbitrary path by
* passing the `'path'` key to its configuration. See `Libraries::add()` for more options.
*
* @see lithium\core\Libraries
*/
/**
* This is the path to your application's directory. It contains all the sub-folders for your
* application's classes and files. You don't need to change this unless your webroot folder is
* stored outside of your app folder.
*/
if (!\defined('LITHIUM_APP_PATH')) {
\define('LITHIUM_APP_PATH', \realpath(\dirname(__DIR__, 2)));
}
/**
* This is the path to the class libraries used by your application, and must contain a copy of the
* Lithium core. By default, this directory is named `libraries`, and resides in the same
* directory as your application. If you use the same libraries in multiple applications, you can
* set this to a shared path on your server.
*/
if(!\defined('LITHIUM_LIBRARY_PATH')) {
\define('LITHIUM_LIBRARY_PATH', \realpath(\dirname(__DIR__, 3) . '/libraries'));
}
/**
* Locate and load Lithium core library files. Throws a fatal error if the core can't be found.
* If your Lithium core directory is named something other than `lithium`, change the string below.
*/
if (!include_once LITHIUM_LIBRARY_PATH . '/lithium/core/Libraries.php') {
$message = "Lithium core could not be found. Check the value of LITHIUM_LIBRARY_PATH in ";
$message .= __FILE__ . ". It should point to the directory containing your ";
$message .= "/libraries directory.";
throw new \ErrorException($message);
}
use lithium\core\Libraries;
/**
* Optimize default request cycle by loading common classes. If you're implementing custom
* request/response or dispatch classes, you can safely remove these. Actually, you can safely
* remove them anyway, they're just there to give slightly you better out-of-the-box performance.
*/
require LITHIUM_LIBRARY_PATH . '/lithium/core/ObjectDeprecated.php';
require LITHIUM_LIBRARY_PATH . '/lithium/core/StaticObjectDeprecated.php';
require LITHIUM_LIBRARY_PATH . '/lithium/core/MergeInheritable.php';
require LITHIUM_LIBRARY_PATH . '/lithium/aop/Filters.php';
require LITHIUM_LIBRARY_PATH . '/lithium/util/Inflector.php';
require LITHIUM_LIBRARY_PATH . '/lithium/util/Text.php';
require LITHIUM_LIBRARY_PATH . '/lithium/util/Set.php';
require LITHIUM_LIBRARY_PATH . '/lithium/core/Adaptable.php';
require LITHIUM_LIBRARY_PATH . '/lithium/core/Environment.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/Message.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/http/Message.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/http/Media.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/http/Request.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/http/Response.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/http/Route.php';
require LITHIUM_LIBRARY_PATH . '/lithium/net/http/Router.php';
require LITHIUM_LIBRARY_PATH . '/lithium/action/Controller.php';
require LITHIUM_LIBRARY_PATH . '/lithium/action/Dispatcher.php';
require LITHIUM_LIBRARY_PATH . '/lithium/action/Request.php';
require LITHIUM_LIBRARY_PATH . '/lithium/action/Response.php';
require LITHIUM_LIBRARY_PATH . '/lithium/storage/Cache.php';
require LITHIUM_LIBRARY_PATH . '/lithium/storage/cache/Adapter.php';
/**
* Add the Lithium core library. This sets default paths and initializes the autoloader. You
* generally should not need to override any settings.
*/
Libraries::add('lithium');
/**
* Add the application. You can pass a `'path'` key here if this bootstrap file is outside of
* your main application, but generally you should not need to change any settings.
*/
Libraries::add('app', ['default' => true]);
/**
* Add lithium plugins. You may manually add plugins or use the library discovery mechanism
* by uncommenting the code below. This will automatically register any libraries prefixed
* with `li3_` in the libraries directories and enable autoloading of them.
*/
foreach ([LITHIUM_LIBRARY_PATH, LITHIUM_APP_PATH . '/libraries'] as $base) {
foreach (glob($base . '/li3_*', GLOB_ONLYDIR) as $path) {
Libraries::add(basename($path), compact('path'));
}
}
/**
* Enable external autoloading through composer by including its autoloader bootstrap. The
* `autoload.php` file will be available once `composer install` was run.
*/
$file = LITHIUM_LIBRARY_PATH . '/autoload.php';
if (file_exists($file)) {
require_once $file;
}
if (file_exists(INSTALLED)) {
Libraries::add('nzedb',
[
'bootstrap' => 'bootstrap.php',
'path' => nZEDb_ROOT . 'nzedb',
]);
}
/**
* Add some plugins:
*/
//if (is_dir(LITHIUM_LIBRARY_PATH . DS . 'li3_docs')) {
// Libraries::add('li3_docs', ['index' => ['app', 'lithium', 'li3_docs', 'manual']]);
//}
//if (is_dir(LITHIUM_LIBRARY_PATH . DS . 'li3_quality')) {
// Libraries::add('li3_quality');
//}
?>

32
nZEDb_data/nZEDb/app/config/bootstrap/logger.php

@ -0,0 +1,32 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2017 nZEDb
*/
use lithium\analysis\Logger;
Logger::config([
'default' => [
'adapter' => 'File',
'path' => nZEDb_LOGS,
'priority' => ['debug','emergency', 'alert', 'critical', 'error']
],
'system' => ['adapter' => 'Syslog']
]);
?>

62
nZEDb_data/nZEDb/app/config/bootstrap/media.php

@ -0,0 +1,62 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
* Copyright 2010, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\net\http\Media;
use lithium\util\Collection;
// use lithium\aop\Filters;
// use lithium\action\Dispatcher;
// use lithium\action\Response;
/**
* The `Collection` class, which serves as the base class for some of Lithium's data objects
* (`RecordSet` and `Document`) provides a way to manage data collections in a very flexible and
* intuitive way, using closures and SPL interfaces. The `to()` method allows a `Collection` (or
* subclass) to be converted to another format, such as an array. The `Collection` class also allows
* other classes to be connected as handlers to convert `Collection` objects to other formats.
* The following connects the `Media` class as a format handler, which allows `Collection`s to be
* exported to any format with a handler provided by `Media`, i.e. JSON. This enables things like
* the following:
* ```
* $posts = Post::find('all');
* return $posts->to('json');
* ```
*/
Collection::formats(Media::class);
/**
* This filter is a convenience method which allows you to automatically route requests for static
* assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the
* `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js`
* will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem.
* In production, it is recommended that you disable this filter in favor of symlinking each
* plugin's `webroot` directory into your main application's `webroot` directory, or adding routing
* rules in your web server's configuration.
*/
// Filters::apply(Dispatcher::class, '_callable', function($params, $next) {
// $url = ltrim($params['request']->url, '/');
// list($library, $asset) = explode('/', $url, 2) + ["", ""];
//
// if ($asset && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) {
// return function() use ($file) {
// $info = pathinfo($file);
// $media = Media::type($info['extension']);
// $content = (array) $media['content'];
//
// return new Response([
// 'headers' => ['Content-type' => reset($content)],
// 'body' => file_get_contents($file)
// ]);
// };
// }
// return $next($params);
// });
?>

81
nZEDb_data/nZEDb/app/config/bootstrap/session.php

@ -0,0 +1,81 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* Copyright 2010, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\config\bootstrap;
use lithium\storage\Session;
// use lithium\security\Auth;
/**
* This configures your session storage. The Cookie storage adapter must be connected first, since
* it intercepts any writes where the `'expires'` key is set in the options array.
* The default name is based on the lithium app path. Remember, if your app is numeric or has
* special characters you might want to use Inflector::slug() or set this manually.
*/
$name = basename(LITHIUM_APP_PATH);
Session::config([
// 'cookie' => ['adapter' => 'Cookie', 'name' => $name],
'default' => ['adapter' => 'Php', 'session.name' => $name]
]);
/**
* Uncomment the lines below to enable forms-based authentication. This configuration will attempt
* to authenticate users against a `Users` model. In a controller, run
* `Auth::check('default', $this->request)` to authenticate a user. This will check the POST data of
* the request (`lithium\action\Request::$data`) to see if the fields match the `'fields'` key of
* the configuration below. If successful, it will write the data returned from `Users::first()` to
* the session using the default session configuration.
* Once the session data is written, you can call `Auth::check('default')` to check authentication
* status or retrieve the user's data from the session. Call `Auth::clear('default')` to remove the
* user's authentication details from the session. This effectively logs a user out of the system.
* To modify the form input that the adapter accepts, or how the configured model is queried, or how
* the data is stored in the session, see the `Form` adapter API or the `Auth` API, respectively.
*
* @see lithium\security\auth\adapter\Form
* @see lithium\action\Request::$data
* @see lithium\security\Auth
*/
// Auth::config([
// 'default' => [
// 'adapter' => 'Form',
// 'model' => 'Users',
// 'fields' => ['username', 'password']
// ]
// ]);
use app\models\Users;
use lithium\security\Password;
Auth::config(
[
'default' => [
'adapter' => 'Form',
'model' => 'Users'
],
]
);
/*
if (!\lithium\data\Connections::get('default')) {
Users::applyFilter('save',
function ($self, $params, $chain)
{
if ($params['data']) {
$params['entity']->set($params['data']);
$params['data'] = [];
}
if (!$params['entity']->exists()) {
$params['entity']->password = Password::hash($params['entity']->password);
}
return $chain->next($self, $params, $chain);
}
);
}
*/
?>

73
nZEDb_data/nZEDb/app/config/bootstrap/yenc.php

@ -0,0 +1,73 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
use app\models\Settings;
use lithium\aop\Filters;
use lithium\action\Dispatcher;
if (defined('nZEDb_INSTALLER') && nZEDb_INSTALLER !== false) {
$adapter = 'Php';
} else {
switch (true) {
case extension_loaded('yenc'):
if (method_exists('\yenc\yEnc', 'version') &&
version_compare(
\yenc\yEnc::version(),
'1.2.2',
'>='
)
) {
$adapter = 'NzedbYenc';
break;
} else {
trigger_error('Your version of the php-yenc extension is out of date and will be
ignored. Please update it to use the extension.', E_USER_WARNING);
}
default:
$adapter = 'Php';
}
}
app\extensions\util\Yenc::config(
[
'default' => [
'adapter' => $adapter
],
'nzedb' => [
'adapter' => 'NzedbYenc'
],
'php' => [
'adapter' => 'Php'
],
]
);
Filters::apply(Ypart::class,
'parseBlock',
function ($params, $next) {
return $next($params);
});
?>

9
nZEDb_data/nZEDb/app/config/fix.json

@ -0,0 +1,9 @@
{
"name": "Default Rule Set",
"rules": [],
"skip":[
"StringTextRename"
],
"options": {
}
}

105
nZEDb_data/nZEDb/app/config/routes.php

@ -0,0 +1,105 @@
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2015, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
/**
* The routes file is where you define your URL structure, which is an important part of the
* [information architecture](http://en.wikipedia.org/wiki/Information_architecture) of your
* application. Here, you can use _routes_ to match up URL pattern strings to a set of parameters,
* usually including a controller and action to dispatch matching requests to. For more information,
* see the `Router` and `Route` classes.
*
* @see lithium\net\http\Router
* @see lithium\net\http\Route
*/
use lithium\net\http\Router;
use lithium\core\Environment;
/**
* ### Continuation routes
*
* With globalization enabled a localized route is configured by connecting a
* continuation route. Once the route has been connected, all the other
* application routes become localized and may now carry a locale.
*
* Requests to routes like `/en/posts/edit/1138` or `/fr/posts/edit/1138` will
* carry a locale, while `/posts/edit/1138` keeps on working as it did before.
*/
if ($locales = Environment::get('locales')) {
$template = '/{:locale:' . join('|', array_keys($locales)) . '}/{:args}';
Router::connect($template, array(), array('continue' => true));
}
/**
* ### Basic page routes
*
* Here, we are connecting `'/'` (the base path) to controller called `'Pages'`,
* its action called `view()`, and we pass a param to select the view file
* to use (in this case, `/views/pages/home.html.php`; see `app\controllers\PagesController`
* for details).
*
* @see app\controllers\PagesController
*/
Router::connect('/', 'Pages::view');
/**
* Connect the rest of `PagesController`'s URLs. This will route URLs like `/pages/about` to
* `PagesController`, rendering `/views/pages/about.html.php` as a static page.
*/
Router::connect('/pages/{:args}', 'Pages::view');
/**
* ### Testing routes
*
* Add the testing routes. These routes are only connected in non-production environments, and allow
* browser-based access to the test suite for running unit and integration tests for the Lithium
* core, as well as your own application and any other loaded plugins or frameworks. Browse to
* [http://path/to/app/test](/test) to run tests.
*/
if (!Environment::is('production')) {
Router::connect('/test/{:args}', array('controller' => 'lithium\test\Controller'));
Router::connect('/test', array('controller' => 'lithium\test\Controller'));
}
/**
* ### Database object routes
*
* The routes below are used primarily for accessing database objects, where `{:id}` corresponds to
* the primary key of the database object, and can be accessed in the controller as
* `$this->request->id`.
*
* If you're using a relational database, such as MySQL, SQLite or Postgres, where the primary key
* is an integer, uncomment the routes below to enable URLs like `/posts/edit/1138`,
* `/posts/view/1138.json`, etc.
*/
// Router::connect('/{:controller}/{:action}/{:id:\d+}.{:type}', array('id' => null));
// Router::connect('/{:controller}/{:action}/{:id:\d+}');
/**
* If you're using a document-oriented database, such as CouchDB or MongoDB, or another type of
* database which uses 24-character hexidecimal values as primary keys, uncomment the routes below.
*/
// Router::connect('/{:controller}/{:action}/{:id:[0-9a-f]{24}}.{:type}', array('id' => null));
// Router::connect('/{:controller}/{:action}/{:id:[0-9a-f]{24}}');
/**
* ### Default controller/action routes
*
* Finally, connect the default route. This route acts as a catch-all, intercepting requests in the
* following forms:
*
* - `/foo/bar`: Routes to `FooController::bar()` with no parameters passed.
* - `/foo/bar/param1/param2`: Routes to `FooController::bar('param1, 'param2')`.
* - `/foo`: Routes to `FooController::index()`, since `'index'` is assumed to be the action if none
* is otherwise specified.
*
* In almost all cases, custom routes should be added above this one, since route-matching works in
* a top-down fashion.
*/
Router::connect('/{:controller}/{:action}/{:args}');
?>

43
nZEDb_data/nZEDb/app/config/syntax.json

@ -0,0 +1,43 @@
{
"name": "Default Rule Set",
"rules": [
"BeginsWithOpenTag",
"ClassesDoNotUseSuperglobalsDirectly",
"ConstructsWithoutBrackets",
"ControlStructuresHaveCorrectFormat",
"DoesntExceedMaxLineLength",
"EndsWithCloseTag",
"HasCorrectCastSpacing",
"HasCorrectCommentStyle",
"HasCorrectEncoding",
"HasCorrectFunctionNames",
"HasCorrectInlineHTML",
"HasCorrectPermissions",
"HasCorrectTabIndention",
"HasCorrectVariableNames",
"HasExplicitPropertyAndMethodVisibility",
"HasNoForbiddenStatements",
"HasNoPrivateMethods",
"HasNoTrailingWhitespace",
"HasTabsAsIndentation",
"MultipleBlankLines",
"OperatorSpacing",
"ProtectedNamesStartWithUnderscore",
"TabsOnlyAppearFirst",
"UnusedUseStatements",
"WeakComparisonOperators"
],
"skipped": [
"ControlStructuresHaveCorrectSpacing",
"HasCorrectDocblockStyle",
"HasCorrectClassName",
"HasNoTrailingWhitespaceExceptNewline"
],
"options": {
"DoesntExceedMaxLineLength": {
"softLimit": false,
"hardLimit": 100,
"tabWidth": 4
}
}
}

69
nZEDb_data/nZEDb/app/controllers/CountriesController.php

@ -0,0 +1,69 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\controllers;
use app\models\Countries;
use lithium\action\DispatchException;
class CountriesController extends \lithium\action\Controller
{
public function index() {
$countries = Countries::all();
return compact('countries');
}
public function view() {
$country = Countries::first($this->request->id);
return compact('country');
}
public function add() {
$country = Countries::create();
if (($this->request->data) && $country->save($this->request->data)) {
return $this->redirect(['Countries::view', 'args' => [$country->id]]);
}
return compact('country');
}
public function edit() {
$country = Countries::find($this->request->id);
if (!$country) {
return $this->redirect('Countries::index');
}
if (($this->request->data) && $country->save($this->request->data)) {
return $this->redirect(['Countries::view', 'args' => [$country->id]]);
}
return compact('country');
}
public function delete() {
if (!$this->request->is('post') && !$this->request->is('delete')) {
$msg = "Countries::delete can only be called with http:post or http:delete.";
throw new DispatchException($msg);
}
Countries::find($this->request->id)->delete();
return $this->redirect('Countries::index');
}
}
?>

80
nZEDb_data/nZEDb/app/controllers/GroupsController.php

@ -0,0 +1,80 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\controllers;
use app\models\Groups;
use lithium\action\DispatchException;
class GroupsController extends \lithium\action\Controller
{
public function add()
{
$group = Groups::create();
if ($this->request->data && $group->save($this->request->data)) {
return $this->redirect(['Groups::view', 'args' => [$group->id]]);
}
return \compact('group');
}
public function delete()
{
if (! $this->request->is('post') && ! $this->request->is('delete')) {
$msg = 'Groups::delete can only be called with http:post or http:delete.';
throw new DispatchException($msg);
}
Groups::find($this->request->id)->delete();
return $this->redirect('Groups::index');
}
public function edit()
{
$group = Groups::find($this->request->id);
if (! $group) {
return $this->redirect('Groups::index');
}
if ($this->request->data && $group->save($this->request->data)) {
return $this->redirect(['Groups::view', 'args' => [$group->id]]);
}
return \compact('group');
}
public function index()
{
$groups = Groups::all();
return \compact('groups');
}
public function view()
{
$group = Groups::first($this->request->id);
return \compact('group');
}
}
?>

26
nZEDb_data/nZEDb/app/controllers/HelloWorldController.php

@ -0,0 +1,26 @@
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2015, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
namespace app\controllers;
class HelloWorldController extends \lithium\action\Controller {
public function index() {
return $this->render(array('layout' => false));
}
public function to_string() {
return "Hello World";
}
public function to_json() {
return $this->render(array('json' => 'Hello World'));
}
}
?>

73
nZEDb_data/nZEDb/app/controllers/MultigroupPostersController.php

@ -0,0 +1,73 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\controllers;
use app\models\MultigroupPosters;
use lithium\action\DispatchException;
class MultigroupPostersController extends \lithium\action\Controller
{
public function index()
{
$multigroupPosters = MultigroupPosters::all();
return compact('multigroupPosters');
}
public function view()
{
$multigroupPoster = MultigroupPosters::first($this->request->id);
return compact('multigroupPoster');
}
public function add()
{
$multigroupPoster = MultigroupPosters::create();
if (($this->request->data) && $multigroupPoster->save($this->request->data)) {
return $this->redirect(['MultigroupPosters::view', 'args' => [$multigroupPoster->id]]);
}
return compact('multigroupPoster');
}
public function edit()
{
$multigroupPoster = MultigroupPosters::find($this->request->id);
if (!$multigroupPoster) {
return $this->redirect('MultigroupPosters::index');
}
if (($this->request->data) && $multigroupPoster->save($this->request->data)) {
return $this->redirect(['MultigroupPosters::view', 'args' => [$multigroupPoster->id]]);
}
return compact('multigroupPoster');
}
public function delete()
{
if (!$this->request->is('post') && !$this->request->is('delete')) {
$msg = 'MultigroupPosters::delete can only be called with http:post or http:delete.';
throw new DispatchException($msg);
}
MultigroupPosters::find($this->request->id)->delete();
return $this->redirect('MultigroupPosters::index');
}
}
?>

54
nZEDb_data/nZEDb/app/controllers/PagesController.php

@ -0,0 +1,54 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\controllers;
/**
* This controller is used for serving static pages by name, which are located in the `/views/pages`
* folder.
*
* A Lithium application's default routing provides for automatically routing and rendering
* static pages using this controller. The default route (`/`) will render the `home` template, as
* specified in the `view()` action.
*
* Additionally, any other static templates in `/views/pages` can be called by name in the URL. For
* example, browsing to `/pages/about` will render `/views/pages/about.html.php`, if it exists.
*
* Templates can be nested within directories as well, which will automatically be accounted for.
* For example, browsing to `/pages/about/company` will render
* `/views/pages/about/company.html.php`.
*/
class PagesController extends \lithium\action\Controller {
public function view()
{
$options = [];
$path = func_get_args();
if (empty($path) || $path === ['home']) {
$path = ['home'];
$options['compiler'] = ['fallback' => true];
}
$options['template'] = join('/', $path);
return $this->render($options);
}
}
?>

70
nZEDb_data/nZEDb/app/controllers/PredbController.php

@ -0,0 +1,70 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:.
*
* @link <http://www.gnu.org/licenses/>.
*
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\controllers;
use app\models\Predb;
use lithium\action\DispatchException;
class PredbController extends \lithium\action\Controller
{
/* Comment out the actions related to views.
public function index() {
$predb = Predb::all();
return compact('predb');
}
public function view() {
$predb = Predb::first($this->request->id);
return compact('predb');
}
public function add() {
$predb = Predb::create();
if (($this->request->data) && $predb->save($this->request->data)) {
return $this->redirect(['Predb::view', 'args' => [$predb->id]]);
}
return compact('predb');
}
public function edit() {
$predb = Predb::find($this->request->id);
if (!$predb) {
return $this->redirect('Predb::index');
}
if (($this->request->data) && $predb->save($this->request->data)) {
return $this->redirect(['Predb::view', 'args' => [$predb->id]]);
}
return compact('predb');
}
public function delete() {
if (!$this->request->is('post') && !$this->request->is('delete')) {
$msg = "Predb::delete can only be called with http:post or http:delete.";
throw new DispatchException($msg);
}
Predb::find($this->request->id)->delete();
return $this->redirect('Predb::index');
}
*/
}
?>

68
nZEDb_data/nZEDb/app/controllers/SettingsController.php

@ -0,0 +1,68 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\controllers;
use app\models\Settings;
use lithium\action\DispatchException;
class SettingsController extends \lithium\action\Controller {
public function index() {
$settings = Settings::all();
return compact('settings');
}
public function view() {
$setting = Settings::first($this->request->id);
return compact('setting');
}
public function add() {
$setting = Settings::create();
if (($this->request->data) && $setting->save($this->request->data)) {
return $this->redirect(array('Settings::view', 'args' => array($setting->id)));
}
return compact('setting');
}
public function edit() {
$setting = Settings::find($this->request->id);
if (!$setting) {
return $this->redirect('Settings::index');
}
if (($this->request->data) && $setting->save($this->request->data)) {
return $this->redirect(array('Settings::view', 'args' => array($setting->id)));
}
return compact('setting');
}
public function delete() {
if (!$this->request->is('post') && !$this->request->is('delete')) {
$msg = "Settings::delete can only be called with http:post or http:delete.";
throw new DispatchException($msg);
}
Settings::find($this->request->id)->delete();
return $this->redirect('Settings::index');
}
}
?>

69
nZEDb_data/nZEDb/app/controllers/VideosController.php

@ -0,0 +1,69 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\controllers;
use app\models\Videos;
use lithium\action\DispatchException;
class VideosController extends \lithium\action\Controller {
public function index() {
$videos = Videos::all();
return compact('videos');
}
public function view() {
$video = Videos::first($this->request->id);
return compact('video');
}
public function add() {
$video = Videos::create();
if ($this->request->data && $video->save($this->request->data)) {
return $this->redirect(['Videos::view', 'args' => [$video->id]]);
}
return compact('video');
}
public function edit() {
$video = Videos::find($this->request->id);
if (!$video) {
return $this->redirect('Videos::index');
}
if ($this->request->data && $video->save($this->request->data)) {
return $this->redirect(['Videos::view', 'args' => [$video->id]]);
}
return compact('video');
}
public function delete() {
if (!$this->request->is('post') && !$this->request->is('delete')) {
$msg = 'Videos::delete can only be called with http:post or http:delete.';
throw new DispatchException($msg);
}
Videos::find($this->request->id)->delete();
return $this->redirect('Videos::index');
}
}
?>

52
nZEDb_data/nZEDb/app/extensions/action/Controller.php

@ -0,0 +1,52 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:.
*
* @link <http://www.gnu.org/licenses/>.
*
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\extensions\action;
use nzedb\data\Source;
class Controller extends \lithium\action\Controller
{
/**
* Constructor.
*
* @see lithium\action\Controller::$request
* @see lithium\action\Controller::$response
* @see lithium\action\Controller::$_render
* @see lithium\action\Controller::$_classes
*
* @param array $config Available configuration options are:
* - `'request'` _object|null_: Either a request object or `null`.
* - `'response'` _array_: Options for constructing the response object.
* - `'render'` _array_: Rendering control options.
* - `'classes'` _array_
*
* @return void
*/
public function __construct(array $config = [])
{
$defaults = [
'request' => null,
'response' => [],
'render' => [],
'classes' => [],
];
parent::__construct($config + $defaults);
}
}

76
nZEDb_data/nZEDb/app/extensions/adapter/data/source/Nntp.php

@ -0,0 +1,76 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\extensions\adapter\data\source;
use app\models\Settings;
/**
* The `Nntp` class provides the base-level abstraction for connecting to a Usenet Service Provider.
*
* @package app\extensions\adapter\data\source
*/
abstract class Nntp extends \lithium\data\Source
{
/**
* Constructor.
*
* @param $config array Available configuration options are:
*
* @return Nntp object on success, exception on failure.
*/
public function __construct(array $config = [])
{
$defaults = [
];
parent::__construct($config + $defaults);
}
public function connect()
{
// TODO: Implement connect() method.
}
public function create($query, array $options = [])
{
// TODO: Implement create() method.
}
public function delete($query, array $options = [])
{
// TODO: add reporting that this is not supported.
}
public function disconnect()
{
// TODO: Implement disconnect() method.
}
public function read($query, array $options = [])
{
// TODO: Implement read() method.
}
public function update($query, array $options = [])
{
// TODO: add reporting that this is not supported.
}
}

127
nZEDb_data/nZEDb/app/extensions/adapter/data/source/database/MySql.php

@ -0,0 +1,127 @@
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
* Copyright 2016, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace app\extensions\adapter\data\source\database;
/**
* MySQL database driver. Extends the `Database` class to implement the necessary
* SQL-formatting and resultset-fetching features for working with MySQL databases.
* - Implements optional strict mode.
* For more information on configuring the database connection, see
* the `__construct()` method.
*
* @see \lithium\data\source\database\adapter\MySql::__construct()
* @see \lithium\data\source\database\adapter\MySql::strict()
*/
class MySql extends \lithium\data\source\database\adapter\MySql
{
/**
* @var string|null Timezone of the session connection as set or retrieved by timezone().
*/
protected $session_tz = null;
/**
* Constructor.
*
* @link http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict
* @see \lithium\data\source\Database::__construct()
* @see \lithium\data\Source::__construct()
* @see \lithium\data\Connections::add()
*
* @param array $config The available configuration options are the following. Further options
* are inherited from the parent classes. Typically, these parameters are
* set in `Connections::add()`, when adding the adapter to the list of
* active connections.
* - `'host'` _string_: A string in the form of `'<host>'`, `'<host>:<port>'`
* or `':<port>'` indicating the host and/or port to connect to. When one
* or both are not provided uses general server defaults.
* To use Unix sockets specify the path to the socket (i.e. `'/path/to/socket'`).
* - `'lowercase'` _boolean_: If enabled this forces all table column names
* to be lower-cased. This should only be needed by users with long
* standing databases that were created with upper-cased names for some
* fields.
* - `'strict'` _boolean|null_: When `true` will enable strict mode by setting
* sql-mode to `STRICT_ALL_TABLES`. When `false` will disable strict mode
* explictly by settings sql-mode to an empty value ``. A value of `null`
* leaves the setting untouched (this is the default) and the default setting
* of the database is used.
* - `'timezone'` _string_: A valid timezone string for the connection. By
* default this is null and the connection's timezone is not changed.
*
* @return \app\extensions\adapter\data\source\database\MySql
*/
public function __construct(array $config = [])
{
$defaults = [
'host' => static::DEFAULT_HOST . ':' . static::DEFAULT_PORT,
'lowercase' => false,
'strict' => null,
'timezone' => null,
];
parent::__construct($config + $defaults);
}
/**
* Connects to the database by creating a PDO intance using the constructed DSN string.
* Will set specific options on the connection as provided.
*
* @return boolean Returns `true` if a database connection could be established,
* otherwise `false`.
*/
public function connect()
{
if (!parent::connect()) {
return false;
}
if ($this->_config['timezone'] !== null && !$this->timezone($this->_config['timezone'])) {
return false;
}
if ($this->_config['lowercase'] === true) {
return $this->connection->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER);
}
return true;
}
/**
* Get/Set the timezone for the connection.
*
* @param string|null $value If null returns the current timezone for the connection. Otherwise
* it attemps to set the timezone for the connection to the value
* supplied.
*
* @return bool|string TZ string of the connection if $value is null, otherwise a boolean
* indicating if setting the timezone succeeded or failed.
*/
public function timezone($value = null)
{
if ($value === null) {
if ($this->session_tz === null) {
$this->session_tz = $this->connection->query(
'SELECT @@session.time_zone')->fetchColumn();
}
$result = $this->session_tz;
} else if (empty($value)) {
$result = false;
trigger_error(__CLASS__ . '::' . __METHOD__ . ': Empty value passed for timezone setting! Check date.timezone setting is set in PHP\'s configuration file.',E_USER_WARNING);
} else {
$result = $this->connection->exec("SET time_zone = '$value'") !== false;
if ($result) {
$this->session_tz = $value;
}
}
return $result;
}
}
?>

0
nZEDb_data/nZEDb/app/extensions/adapter/empty

293
nZEDb_data/nZEDb/app/extensions/command/Update.php

@ -0,0 +1,293 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\command;
use app\extensions\util\Git;
use app\extensions\util\Versions;
use lithium\console\command\Help;
use nzedb\db\DbUpdate;
use Phinx\Console\PhinxApplication;
use Smarty;
/**
* Update various aspects of your indexer.
*
* Actions:
* * all|nzedb Fetches current git repo, composer dependencies, and update latest Db patches.
* * db Update the Db with any patches not yet applied.
* * git Performs git pull.
* * predb Fetch and import TSV files into the predb table.
*
* @package app\extensions\command
*/
class Update extends \app\extensions\console\Command
{
const UPDATES_FILE = nZEDb_CONFIGS . 'updates.json';
/**
* @var \app\extensions\util\Git object.
*/
protected $git;
/**
* @var array Decoded JSON updates file.
*/
protected $updates = null;
private $gitBranch;
private $gitTag;
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config = [])
{
$defaults = [
'classes' => $this->_classes,
'git' => null,
'request' => null,
'response' => [],
];
parent::__construct($config + $defaults);
}
public function all()
{
$this->nzedb();
}
public function db()
{
// TODO Add check to determine if the indexer or other scripts are running. Hopefully
// also prevent web access.
$this->out('Checking database version...', 'primary');
$versions = new Versions(['git' => ($this->git instanceof Git) ? $this->git : null]);
try {
$currentDb = $versions->getSQLPatchFromDB();
$currentXML = $versions->getSQLPatchFromFile();
} catch (\PDOException $e) {
$this->out('Error fetching patch versions!', 'error');
return 1;
}
$this->out("Db: $currentDb,\tFile: $currentXML");
if ($currentDb < $currentXML) {
$db = new DbUpdate(['backup' => false]);
$db->processPatches(['safe' => false]);
} else {
$this->out('Up to date.', 'info');
}
//return $this->migrate();
}
public function git()
{
// TODO Add check to determine if the indexer or other scripts are running. Hopefully
// also prevent web access.
$this->initialiseGit();
if (!in_array($this->git->getBranch(), $this->git->getBranchesMain())) {
$this->out("Not on the stable or dev branch! Refusing to update repository", 'error');
return;
}
return trim($this->git->pull());
}
/**
* Runs Phinx's migrate command.
*
* @return int
*/
public function migrate(): int
{
$oldArgv = $_SERVER['argv'];
// Build the command for phinx. This is needed for the application to read the parameters.
$_SERVER['argv'] = [
'phinx',
'migrate',
'-c',
\nZEDb_CONFIGS . 'phinx.php'];
// Instantiate and run the phinx app.
$app = new PhinxApplication();
$result = $app->run();
$_SERVER['argv'][] = $oldArgv;
return $result;
}
public function nzedb()
{
try {
$this->git();
$status = $this->composer();
if ($status) {
$this->out('Composer failed to update!!', 'error');
return false;
} else {
$fail = $this->db();
if ($fail) {
$this->out('Db updating failed!!', 'error');
return 1;
}
};
$this->scripts();
$smarty = new Smarty();
$smarty->setCompileDir(nZEDb_SMARTY_TEMPLATES);
$cleared = $smarty->clearCompiledTemplate();
if ($cleared) {
$this->out('The Smarty compiled template cache has been cleared for you', 'primary');
} else if (!empty(glob(nZEDb_SMARTY_TEMPLATES . '*.php', GLOB_NOSORT))) {
$this->out('You should clear your Smarty compiled template cache at: ' .
nZEDb_SMARTY_TEMPLATES,
'primary');
}
} catch (\Exception $e) {
$this->error($e->getMessage());
echo $e->getMessage() . \PHP_EOL;
}
}
/**
* Import/Update the predb table using tab separated value files.
*/
public function predb()
{
$this->out('predb not available yet!', 'error');
}
public function run($command = null)
{
if (!$command || ($this->request->args() === null)) {
return $this->_help();
}
if (!$command) {
return $this->_help();
}
if ($this->_execute($command)) {
return true;
}
$this->error("{$command} could not be created.");
return false;
}
/**
* Issues the command to 'install' the composer package.
*
* It first checks the current branch for stable versions. If found then the '--no-dev'
* option is added to the command to prevent development packages being also downloded.
*
* @return integer Return status from Composer.
*/
protected function composer()
{
$this->initialiseGit();
$command = 'composer install';
if (\in_array($this->gitBranch, $this->git->getBranchesStable(), false)) {
$command .= ' --prefer-dist --no-dev';
} else {
$command .= ' --prefer-source';
}
$this->out('Running composer install process...', 'primary');
$oldwd = getcwd();
if ($oldwd !== false) {
$oldwd = \chdir(\nZEDb_ROOT) ? $oldwd : false;
}
system($command, $status);
if ($oldwd !== false) {
\chdir($oldwd);
}
return $status;
}
protected function initialiseGit()
{
if (!($this->git instanceof Git)) {
$this->git = new Git();
}
}
/**
* Invokes the `Help` command.
* The invoked Help command will take over request and response objects of
* the originally invoked command. Thus the response of the Help command
* becomes the response of the original one.
*
* @return boolean
*/
protected function _help()
{
$help = new Help([
'request' => $this->request,
'response' => $this->response,
'classes' => $this->_classes
]);
return $help->run(get_class($this));
}
/**
* Class initializer. Parses template and sets up params that need to be filled.
*
* @return void
*/
protected function _init()
{
parent::_init();
if ($this->_config['git'] instanceof Git) {
$this->git =& $this->_config['git'];
}
if (file_exists(SELF::UPDATES_FILE)) {
$this->updates = json_decode(file_get_contents(UPDATES_FILE), true);
}
}
/**
* Fetches and executes scripts for customised updating tasks.
*/
protected function scripts()
{
// TODO make this do something useful ;-)
if (![$this->updates]) {
$this->updates = ['script' => '0000-00-00 00:00:00'];
}
}
}

162
nZEDb_data/nZEDb/app/extensions/command/Usenet.php

@ -0,0 +1,162 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\extensions\command;
use app\extensions\util\Yenc;
use app\models\Settings;
use nzedb\db\DB;
use nzedb\NNTP;
/**
* Lets you manually fetch data from your U.S.P.
*
*
*
* @package app\extensions\command
*/
class Usenet extends \app\extensions\console\Command
{
public $group = 'alt.binaries.moovee';
public $msgid = '<0c-A40009D167$y23340x3Gi4781d@I40$O3b586991.Y1al3kC5>';
public $showBody = false;
public $showHeader = false;
/**
* @var \nzedb\NNTP object
*/
private $usp = null;
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config = [])
{
$defaults = [
'classes' => $this->_classes,
'request' => null,
'response' => [],
];
parent::__construct($config + $defaults);
$this->usp = new NNTP(['Settings' => new DB()]);
$result = $this->usp->doConnect(Settings::value('..compressedheaders'));
if ($result === true) {
$this->out("{:green}Connected to USP{:end}");
} else {
$this->out("{:green}Damnit an error!!{:end}");
throw new \ErrorException($result->getMessage());
}
}
public function fetch()
{
if (empty($this->msgid)) {
$this->error("{:red}No message-id (--msgid=) supplied.{:end}");
$this->msgid = $this->in("message-id (complex ids [most] will need single-quoting)?");
}
if (empty($this->group)) {
$this->error("{:red}No group name (--group=) supplied.{:end}");
$this->group = $this->in("group name?");
}
$this->out("{:cyan}Using\nmessage-id: '{$this->msgid}'\nGroup: {$this->group}{:end}");
$path = nZEDb_TMP . trim($this->msgid, '<>');
if (!file_exists($path)) {
mkdir($path);
}
$result = $this->getHeader($this->msgid, true);
if ($this->usp->isError($result) === false) {
file_put_contents($path . DS . 'headers.txt', $result . "\r\n");
if ($this->showHeader) {
$this->out("{:green}Headers{:end}");
$this->out( $result);
} else {
$this->out("{:green}Fetched headers{:end}");
}
} else {
$this->out("{:green}Damnit an error!!{:end}");
throw new \ErrorException($result->getMessage());
}
$result = $this->getBody($this->msgid, true);
if ($this->usp->isError($result) === false) {
file_put_contents($path . DS . 'body.txt', $result . "\r\n");
if ($this->showBody) {
$this->out("{:green}Body{:end}");
$this->out($result);
} else {
$this->out("{:green}Fetched body{:end}");
}
file_put_contents($path . DS . 'body.decoded', $this->decodeBody($result));
} else {
$this->out("{:green}Damnit an error!!{:end}");
throw new \ErrorException($result->getMessage());
}
/*
} else {
$this->out("{:green}Damnit an error!!{:end}");
throw new \ErrorException($article->getMessage());
}
*/
}
public function run()
{
if ($this->request->args() === null) {
return $this->_help();
}
return false;
}
protected function getBody($identifier = null, $implode = false)
{
// Download the header.
$header = $this->usp->getBody($identifier, $implode);
return $header;
}
protected function getHeader($identifier = null, $implode = false)
{
// Download the header.
$header = $this->usp->getHeader($identifier, $implode);
return $header;
}
private function decodeBody(&$text)
{
return Yenc::decode($text);
//return Yenc::decodeIgnore($text, ['name' => 'php']);
//return false;
}
}

159
nZEDb_data/nZEDb/app/extensions/command/Verify.php

@ -0,0 +1,159 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\command;
use app\extensions\command\verify\Permissions;
use app\extensions\command\verify\Tables;
use lithium\core\ClassNotFoundException;
/**
* Verifies various parts of your indexer.
* Actions:
* * permissions [ db | dirs ]
* Checks that path and/or db permissions for crucial locations in nZEDb for the
* user running the command.
* If an incorrect permission is encountered, a message will be printed.
* IT IS STRONGLY RECOMMENDED that you run this against your apache/nginx user, in
* addition to your normal CLI user.
* On linux you can run it against the apache/nginx user this way:
* sudo -u www-data ./zed verify permissions
* See this page for a quick guide on setting up your permissions in linux:
* https://github.com/nZEDb/nZEDb/wiki/Setting-permissions-on-linux
* * table <list> Run checks against specific table(sets). <list> is a series of table names (case
* sensitive) or sets.
* - tpg: Collections, Parts, Binaries set of tables.
* - Settings: Check that settings in the 10~settings.tsv file exist in your Db.
*/
class Verify extends \app\extensions\console\Command
{
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config = [])
{
$defaults = [
'classes' => $this->_classes,
'request' => null,
'response' => [],
];
parent::__construct($config + $defaults);
}
public function run()
{
if ($this->request->args() === null) {
return $this->_help();
}
return false;
}
/**
* Run the Permissions sub-command.
*
* @return boolean
*/
public function permissions(): bool
{
$request = $this->request;
$perms = new Permissions(['request' => $request]);
return $perms->run();
}
/**
* Run the Table sub-command
*
* @return bool
*/
public function table(): bool
{
$request = $this->request;
$tables = new Tables(['request' => $request]);
return $tables->run();
}
/**
* Execute the given sub-command for the current request.
*
* @param string $command The sub-command name. example: Permissions, Tables.
*
* @return boolean
*/
protected function execute($command)
{
try {
if (!$class = $this->instance($command)) {
return false;
}
} catch (ClassNotFoundException $e) {
return false;
}
$data = [];
$params = $class->invokeMethod('_params');
foreach ($params as $param) {
$data[$param] = $class->invokeMethod("_{$param}", [$this->request]);
}
if ($message = $class->invokeMethod('_save', [$data])) {
$this->out($message);
return true;
}
return false;
}
/**
* Class initializer. Parses template and sets up params that need to be filled.
*
* @return void
*/
protected function _init()
{
parent::_init();
}
/**
* Get an instance of a sub-command
*
* @param string $name the name of the sub-command to instantiate
* @param array $config
*
* @return object
*/
protected function instance($name, array $config = [])
{
if ($class = Libraries::locate('command.create', Inflector::camelize($name))) {
$this->request->params['template'] = $this->template;
return new $class([
'request' => $this->request,
'classes' => $this->_classes
]);
}
return $this->_instance($name, $config);
}
}

148
nZEDb_data/nZEDb/app/extensions/command/Version.php

@ -0,0 +1,148 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\command;
use \app\extensions\util\Versions;
use \lithium\console\command\Help;
/**
* Returns the current version (or branch) of the indexer.
*
* Actions:
* * all Show all of following info.
* * branch Show git branch name.
* * git Show git tag for current version.
* * sql Show SQL patch level
*
* @package app\extensions\command
*/
class Version extends \app\extensions\console\Command
{
/**
* @var \app\extensions\util\Versions;
*/
protected $versions = null;
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config = [])
{
$defaults = [
'classes' => $this->_classes,
'request' => null,
'response' => [],
];
parent::__construct($config + $defaults);
}
public function run()
{
if ($this->request->args() === null) {
return $this->_help();
}
return false;
}
protected function all()
{
$this->git();
$this->sql();
}
protected function branch()
{
$this->primary('Git branch: ' . $this->versions->getGitBranch());
}
/**
* Fetch git tag for latest version.
*
* @param string|null $path Optional path to the versions XML file.
*/
protected function git()
{
if (!$this->plain) {
$this->primary('Looking up Git tag version(s)');
}
$this->out('Hash: ' . $this->versions->getGitHeadHash(), 0);
$this->out('XML version: ' . $this->versions->getGitTagInFile());
$this->out('Git version: ' . $this->versions->getGitTagInRepo());
}
/**
* Fetch SQL latest patch version.
*/
protected function sql()
{
if (!$this->plain) {
$this->primary('Looking up SQL patch version(s)');
}
if (in_array($this->request->params['args']['sqlcheck'], ['xml', 'both', 'all'])) {
$latest = $this->versions->getSQLPatchFromFile();
$this->out("XML version: $latest");
}
if (in_array($this->request->params['args']['sqlcheck'], ['db', 'both', 'all'])) {
try {
$dbVersion = $this->versions->getSQLPatchFromDB();
$this->out(" DB version: " . $dbVersion);
} catch (\Exception $e) {
$this->error($e->getMessage());
}
}
}
/**
* Invokes the `Help` command.
* The invoked Help command will take over request and response objects of
* the originally invoked command. Thus the response of the Help command
* becomes the response of the original one.
*
* @return boolean
*/
protected function _help()
{
$help = new Help([
'request' => $this->request,
'response' => $this->response,
'classes' => $this->_classes
]);
return $help->run(get_class($this));
}
/**
* Class initializer. Parses template and sets up params that need to be filled.
*
* @return void
*/
protected function _init()
{
parent::_init();
$this->request->params['args'] += ['sqlcheck' => 'all']; // Default to all versions/
$this->versions = new Versions();
}
}

0
nZEDb_data/nZEDb/app/extensions/command/empty

107
nZEDb_data/nZEDb/app/extensions/command/verify/Permissions.php

@ -0,0 +1,107 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\extensions\command\verify;
/**
* Verifies permissions of various parts of the indexer.
* Actions:
* * db TODO
* * dirs Directories
*/
class Permissions extends \app\extensions\console\Command
{
public function __construct(array $config = [])
{
parent::__construct($config);
}
public function run()
{
if (empty($this->request->params['args'])) {
return $this->_help();
}
foreach ($this->request->params['args'] as $arg) {
switch ($arg) {
case 'db':
$this->database();
break;
case 'dirs':
$this->dirs();
break;
default:
$this->out("Unknown action: '$arg'", ['style' =>'error']);
}
}
}
protected function database()
{
$this->primary("Db permission checking, is not implemented yet!");
}
protected function dirs()
{
$this->primary("Checking permissions on directories...");
$error = false;
// Check All folders up to nZEDb root folder.
$path = DS;
foreach (explode(DS, nZEDb_ROOT) as $folder) {
if ($folder) {
$path .= $folder . DS;
$error |= !$this->isReadable($path);
$error |= !$this->isExecutable($path);
}
}
if ($error) {
$this->primary("Fix the above errors and rerun the command.");
} else {
$this->primary("Congratulations, file permissions look good!");
}
}
protected function _init()
{
parent::_init();
}
protected function isExecutable($path)
{
$check = is_executable($path);
if (!$check) {
$this->error("This path is not executable/traversable: '$path'.");
}
return $check;
}
protected function isReadable($path)
{
$check = is_readable($path);
if (!$check) {
$this->error("This path is not readable: '$path'.");
}
return $check;
}
}

259
nZEDb_data/nZEDb/app/extensions/command/verify/Tables.php

@ -0,0 +1,259 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
*
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\extensions\command\verify;
use app\models\Groups as Group;
use app\models\Settings;
use app\models\Tables as Schema;
use lithium\data\Connections;
use nzedb\Groups;
class Tables extends \app\extensions\console\Command
{
public function __construct(array $config = [])
{
parent::__construct($config);
}
public static function getCBPTables(string $prefix): array
{
$tables = [];
$data = static::find('tpg', ['prefix' => $prefix])->data();
/* @var $data string[][] */
foreach ($data as $table) {
$tables[] = $table['TABLE_NAME'];
}
return $tables;
}
public function run()
{
if (empty($this->request)) {
return $this->_help();
}
foreach ($this->request->params['args'] as $arg) {
switch ($arg) {
case 'Settings':
case 'settings':
$this->tableSettings();
break;
case 'cpb':
$this->tableSetCPB();
break;
// case '':
// $this->();
// break;
default:
$this->out("Unknown table: '$arg'", ['style' => 'error']);
}
}
}
protected function _init()
{
parent::_init();
}
/**
* Check the set of tables: collections, binaries, parts, and missed parts for enabled groups
* without corresponding table(s).
*
* @return array All group IDs that had problems, empty if no problems were discovered.
*/
protected function tableSetCPB() : array
{
$active = Group::find('all',
[
'conditions' => [
'active' => true,
],
'fields' => [
'id',
'name',
],
'order' => 'name ASC',
]
);
if (\count($active->data()) < 1) {
$this->out('No active groups found to verify!');
} else {
$groups = Group::find('all',
[
'fields' => 'id',
'conditions' => ['active' => true],
])->data();
/* @var $groups string[][] */
foreach ($groups as $group) {
$ids[] = $group['id'];
}
$binaries = Schema::tpg('binaries');
$collections = Schema::tpg('collections');
$parts = Schema::tpg('parts');
$errors = [];
//$groups = new Groups();
/* @var $ids string[][] */
foreach ($ids as $groupID) {
if (! \in_array('binaries_' . $groupID, $binaries, false) ||
! \in_array('collections_' . $groupID, $collections, false) ||
! \in_array('parts_' . $groupID, $parts, false)
) {
echo "Creating missing tables for group id: $groupID" . PHP_EOL;
$errors[] = $groupID;
//$groups->createNewTPGTables($groupID);
Schema::createTPGTablesForId($groupID);
} else {
echo "Group id '$groupID' has all its tables." . PHP_EOL;
}
}
return $errors;
}
}
protected function tableSettings()
{
$output = function($row, $header, &$firstLine, $result) {
if ($firstLine === true) {
$this->out('section, subsection, name', ['style' => 'info']);
$firstLine = false;
}
if ($result === false) {
$this->out(" {$row['section']}, {$row['subsection']}, {$row['name']}: MISSING!",
['style' => 'error']);
}
};
$validate = static function($row) {
$result = Settings::value(
[
'section' => $row['section'],
'subsection' => $row['subsection'],
'name' => $row['name'],
],
true);
return $result !== null;
};
$dummy = $this->validate(
[
'file' => nZEDb_RES . 'db/schema/data/10-settings.tsv',
'output' => $output,
'silent' => false,
'table' => 'Settings',
'test' => $validate,
]
);
return $dummy;
}
protected function defaultOutput($row, $header, &$error)
{
if ($error === false) {
$this->out($header, ['style' => 'primary']);
$error = true;
}
$this->out($row, ['style' => 'info']);
}
/**
* @param array $options Settings for the validation. Some more optional than others. Entries
* include:
* `file` - filename of data file to use
* `fix` - whether to fix failures (false|closure)
* `output`- closure to format text output.
* `silent - disable output (boolean)
* `test` - closure to use for validation.
*
* @return bool true if no errors found, false otherwise
*/
private function validate(array $options = [])
{
$fix = $output = $test = '';
\extract($options, EXTR_IF_EXISTS | EXTR_REFS); // create short-name variable refs
if (! \is_callable($test)) {
throw new \InvalidArgumentException('The option "test" must be a closure to perform the test!');
}
if (! \file_exists($options['file'])) {
throw new \InvalidArgumentException("Unable to find {$options['file']}!");
}
$rows = \file($options['file']);
if (! \is_array($rows)) {
throw new \InvalidArgumentException("File {$options['file']} did not return a list of rows!");
}
// Move the column names/order off of the array.
$header = \trim(\array_shift($rows));
$columns = \explode(',', $header);
\array_walk($columns,
function(&$value) {
$value = \trim($value);
}
);
if ($options['silent'] != true) {
$this->out("Verifying `{$options['table']}` table...", ['style' => 'primary']);
}
$result = $firstLine = true;
$error = false;
foreach ($rows as $row) {
$data = \array_combine($columns, \explode("\t", $row));
$check = $test($data, $columns);
if ($options['silent'] === false) {
if (\is_callable($output)) {
$output($data, $header, $firstLine, $check);
} else {
$this->defaultOutput($row, $header, $error);
}
}
if ($check === false) {
if (\is_callable($fix)) {
$fix($data);
}
$error = true;
}
}
if ($error === false) {
$this->out('No problems found.', ['style' => 'primary']);
} elseif ($options['fix'] === false) {
$this->out('Please fix the above problems.', ['style' => 'warning']);
}
return $result;
}
}

66
nZEDb_data/nZEDb/app/extensions/console/Command.php

@ -0,0 +1,66 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2014 nZEDb
*/
namespace app\extensions\console;
class Command extends \lithium\console\Command
{
protected $_classes = [
'response' => 'app\extensions\console\Response'
];
public function __construct(array $config = array())
{
$defaults = ['request' => null, 'response' => [], 'classes' => $this->_classes];
parent::__construct($config + $defaults);
}
public function error($text = null, $options = [])
{
if ($this->silent) {
return;
}
$options['style'] = 'error';
$this->out($text, $options);
}
public function info($text, array $options = [])
{
if ($this->silent) {
return;
}
$options['style'] = 'info';
$this->out($text, $options);
}
public function primary($text, array $options = [])
{
if ($this->silent) {
return;
}
$options['style'] = 'primary';
$this->out($text, $options);
}
}
?>

368
nZEDb_data/nZEDb/app/extensions/console/Response.php

@ -0,0 +1,368 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation,
either version 3 of the License,
or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not,
see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2014 nZEDb
*/
namespace app\extensions\console;
class Response extends \lithium\console\Response
{
public $coloursBackground = [
'black' => '40',
'blue' => '44',
'cyan' => '46',
'green' => '42',
'purple' => '45',
'red' => '41',
'white' => '47',
'yellow' => '43',
];
public $coloursForeground = [
'black' => '30',
'blue' => '34',
'cyan' => '36',
'gray' => '37',
'green' => '32',
'grey' => '37',
'purple' => '35',
'red' => '31',
'white' => '1;37',
'yellow' => '33',
];
public $colours256 = [
'Aquamarine' => '086',
'Aquamarine1' => '122',
'Aquamarine2' => '079',
'Blue' => '012',
'Blue1' => '021',
'Blue2' => '019',
'Blue3' => '020',
'BlueViolet' => '057',
'CadetBlue' => '072',
'CadetBlue1' => '073',
'Chartreuse' => '118',
'Chartreuse1' => '082',
'Chartreuse2' => '112',
'Chartreuse3' => '070',
'Chartreuse4' => '076',
'Chartreuse5' => '064',
'CornflowerBlue' => '069',
'Cornsilk' => '230',
'Cyan' => '014',
'Cyan1' => '051',
'Cyan2' => '050',
'Cyan3' => '043',
'DarkBlue' => '018',
'DarkCyan' => '036',
'DarkGoldenrod' => '136',
'DarkGreen' => '022',
'DarkKhaki' => '143',
'DarkMagenta' => '090',
'DarkMagenta1' => '091',
'DarkOliveGreen' => '191',
'DarkOliveGreen1' => '192',
'DarkOliveGreen2' => '155',
'DarkOliveGreen3' => '107',
'DarkOliveGreen4' => '113',
'DarkOliveGreen5' => '149',
'DeepPink' => '198',
'DeepPink1' => '199',
'DeepPink2' => '197',
'DarkOrange' => '208',
'DarkOrange1' => '130',
'DarkOrange2' => '166',
'DeepPink3' => '161',
'DeepPink4' => '162',
'DeepPink7' => '125',
'DarkRed' => '052',
'DarkSeaGreen' => '108',
'DarkSeaGreen1' => '158',
'DarkSeaGreen2' => '193',
'DarkSeaGreen3' => '151',
'DarkSeaGreen4' => '157',
'DarkSeaGreen5' => '115',
'DarkSeaGreen6' => '150',
'DarkSeaGreen7' => '065',
'DarkSeaGreen8' => '071',
'DarkSlateGray' => '123',
'DarkTurquoise' => '044',
'DarkRed1' => '088',
'DarkSlateGray1' => '087',
'DarkSlateGray2' => '116',
'DarkViolet' => '092',
'DarkViolet1' => '128',
'DeepPink5' => '053',
'DeepPink6' => '089',
'DeepSkyBlue' => '039',
'DeepSkyBlue1' => '038',
'DeepSkyBlue2' => '031',
'DeepSkyBlue3' => '032',
'DeepSkyBlue5' => '023',
'DeepSkyBlue6' => '024',
'DeepSkyBlue7' => '025',
'DodgerBlue' => '033',
'DodgerBlue1' => '027',
'DodgerBlue2' => '026',
'Gold' => '220',
'Gold1' => '142',
'Gold2' => '178',
'Gray' => '008',
'Green' => '010',
'Green1' => '046',
'Green2' => '034',
'Green3' => '040',
'Green4' => '028',
'GreenYellow' => '154',
'Grey1' => '016',
'Grey2' => '059',
'Grey3' => '102',
'Grey4' => '139',
'Grey5' => '145',
'Grey6' => '188',
'Grey7' => '231',
'Grey8' => '232',
'Grey9' => '233',
'Grey10' => '234',
'Grey11' => '235',
'Grey12' => '236',
'Grey13' => '237',
'Grey14' => '238',
'Grey15' => '239',
'Grey16' => '240',
'Grey17' => '241',
'Grey18' => '242',
'Grey19' => '243',
'Grey20' => '244',
'Grey21' => '245',
'Grey22' => '246',
'Grey23' => '247',
'Grey24' => '248',
'Grey25' => '249',
'Grey26' => '250',
'Grey27' => '251',
'Grey28' => '252',
'Grey29' => '253',
'Grey30' => '254',
'Grey31' => '255',
'Honeydew' => '194',
'HotPink' => '205',
'HotPink1' => '206',
'HotPink2' => '169',
'HotPink3' => '132',
'HotPink4' => '168',
'IndianRed' => '131',
'IndianRed1' => '167',
'IndianRed2' => '203',
'IndianRed3' => '204',
'Khaki' => '228',
'Khaki1' => '185',
'LightCoral' => '210',
'LightCyan1' => '195',
'LightCyan2' => '152',
'LightGoldenrod' => '227',
'LightGoldenrod1' => '186',
'LightGoldenrod2' => '221',
'LightGoldenrod3' => '222',
'LightGoldenrod4' => '179',
'LightGreen' => '119',
'LightGreen1' => '120',
'LightPink' => '217',
'LightPink1' => '174',
'LightPink2' => '095',
'LightSalmon' => '216',
'LightSalmon1' => '137',
'LightSalmon2' => '173',
'LightSeaGreen' => '037',
'LightSkyBlue' => '153',
'LightSkyBlue1' => '109',
'LightSkyBlue2' => '110',
'LightSlateBlue' => '105',
'LightSteelBlue' => '147',
'LightSteelBlue1' => '189',
'LightSteelBlue2' => '146',
'LightSlateGrey' => '103',
'LightYellow' => '187',
'Magenta1' => '201',
'Magenta2' => '165',
'Magenta3' => '200',
'Magenta4' => '127',
'Magenta5' => '163',
'Magenta6' => '164',
'MediumOrchid' => '134',
'MediumOrchid1' => '171',
'MediumOrchid2' => '207',
'MediumOrchid3' => '133',
'MediumPurple' => '104',
'MediumPurple1' => '141',
'MediumPurple2' => '135',
'MediumPurple3' => '140',
'MediumPurple4' => '097',
'MediumPurple5' => '098',
'MediumPurple6' => '060',
'MediumSpringGreen' => '049',
'MediumTurquoise' => '080',
'MediumVioletRed' => '126',
'MistyRose' => '224',
'MistyRose1' => '181',
'NavajoWhite' => '223',
'NavajoWhite1' => '144',
'NavyBlue' => '017',
'Orange' => '214',
'Orange1' => '172',
'Orange2' => '058',
'Orange3' => '094',
'OrangeRed' => '202',
'Orchid' => '170',
'Orchid1' => '213',
'Orchid2' => '212',
'PaleGreen' => '121',
'PaleGreen1' => '156',
'PaleGreen2' => '077',
'PaleGreen3' => '114',
'PaleTurquoise' => '159',
'PaleTurquoise1' => '066',
'PaleVioletRed' => '211',
'Pink' => '218',
'Pink1' => '175',
'Plum' => '219',
'Plum1' => '183',
'Plum2' => '176',
'Plum3' => '096',
'Purple' => '013',
'Purple1' => '093',
'Purple2' => '129',
'Purple3' => '056',
'Purple4' => '054',
'Purple5' => '055',
'Red' => '009',
'Red1' => '196',
'Red2' => '124',
'Red3' => '160',
'RoyalBlue1' => '063',
'RosyBrown' => '138',
'Salmon' => '209',
'SandyBrown' => '215',
'SeaGreen' => '084',
'SeaGreen1' => '085',
'SeaGreen2' => '083',
'SeaGreen3' => '078',
'SkyBlue' => '117',
'SkyBlue1' => '111',
'SkyBlue2' => '074',
'SlateBlue' => '099',
'SlateBlue1' => '061',
'SlateBlue2' => '062',
'SpringGreen' => '048',
'SpringGreen1' => '042',
'SpringGreen2' => '047',
'SpringGreen3' => '035',
'SpringGreen4' => '041',
'SpringGreen5' => '029',
'SteelBlue' => '067',
'SteelBlue1' => '075',
'SteelBlue2' => '081',
'SteelBlue3' => '068',
'Tan' => '180',
'Thistle' => '225',
'Thistle1' => '182',
'Turquoise' => '045',
'Turquoise1' => '030',
'Violet' => '177',
'Wheat' => '229',
'Wheat1' => '101',
'White' => '015',
'Yellow' => '011',
'Yellow1' => '226',
'Yellow2' => '190',
'Yellow3' => '148',
'Yellow4' => '184',
'Yellow5' => '100',
'Yellow6' => '106',
];
private $styles = [
'blink' => "\033[5m",
'bright' => "\033[1m",
'command' => "\033[0;35m",
'dim' => "\033[2m",
'gray' => "\033[37m",
'grey' => "\033[37m",
'hidden' => "\033[8m",
'info' => "\033[35m", // replace with updated version of:
// "\033[" . self::coloursForeground['purple'] . "mInfo: $text\033[0m"
// when we switch to PHP 5.6
'normal' => "\033[0m",
'primary' => "\033[38;5;010m",
'reset' => "\033[0m",
'reverse' => "\033[7m",
'strikethrough' => "\033[9m",
'underscore' => "\033[4m",
];
public function __construct(array $options = array())
{
parent::__construct($options);
}
public function __destruct()
{
parent::__destruct();
}
public function clearStyle($style)
{
if ($this->getStyle($style) !== null) {
unset(self::$styles[$style]);
}
return !($this->getStyle($style) === null);
}
public function getColourCode($fgColour, $bgColour = null)
{
$bgColour = empty($bg) && isset(self::$coloursBackground[$bgColour]) ?
";48;5;" . self::$colours256[$bgColour] : '';
return "\033[38;5;" . self::$colours256[$fgColour] . $bgColour . "m";
}
public function getStyle($style)
{
return isset(self::$styles[$style]) ? self::$styles[$style] : null;
}
public function setStyle($style, $value)
{
self::$styles[$style] = $value;
return ($this->getStyle($style) == $value);
}
public function styles($styles = [])
{
return parent::styles($styles + $this->styles);
}
protected function _encode($code)
{
return "\033[" . $code . "m";
}
}

64
nZEDb_data/nZEDb/app/extensions/data/Model.php

@ -0,0 +1,64 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\extensions\data;
use lithium\data\Entity;
/**
* @method static array all(array $options = []) Returns all rows from the model, that match the $options.
* @method static array count(array $optionss = []) Counts the rows, that match the provided options.
* @method static array first(array $optionss = []) Returns the first match for the provided options.
*/
class Model extends \lithium\data\Model
{
/**
* The number of rows found by the last query.
*
* @return int
*/
public static function foundRows()
{
$result = static::Find('first', ['fields' => 'FOUND_ROWS() AS found']);
return $result->data()['found'];
}
public static function isModified($preEntry) : bool
{
if (!($preEntry instanceof Entity)) {
$test = get_class($preEntry);
$test = $test ?: 'non-object';
throw new \InvalidArgumentException('$preEntry must be an object derived from the Lithium Entity class, a "' . $test . '" was passed instead.');
}
$modified = false;
foreach ($preEntry->modified() as $field => $value) {
if ($value) {
if (nZEDb_DEBUG) {
echo "Changed: $field\n";
}
$modified = true;
}
}
return $modified;
}
}

0
nZEDb_data/nZEDb/app/extensions/helper/empty

219
nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/ControlStructuresHaveCorrectFormat.php

@ -0,0 +1,219 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2014 nZEDb
*/
namespace app\extensions\qa\rules\syntax;
use lithium\util\Text;
class ControlStructuresHaveCorrectFormat extends \li3_quality\qa\rules\syntax\ControlStructuresHaveCorrectSpacing
{
/**
* Items that help identify the correct patterns and error messages.
*
* @var array
*/
protected $_tokenMap = [
T_CLASS => [
'message' => 'Unexpected T_CLASS format. Should be: "[abstract ]class Foo[ extends bar][ implements baz]"',
'patterns' => [
"/^({:whitespace})(?:abstract )?class [^\s]+ (extends [\S]+ )?(implements .+ )?[^{]/",
],
],
T_IF => [
'message' => 'Unexpected T_IF format. Should be: "if (...) {" or "} else if () {"',
'patterns' => [
"/^{:whitespace}if {:bracket} \{/",
"/^{:whitespace}\} elseif {:bracket} \{/",
],
],
T_ELSEIF => [
'message' => 'Unexpected T_ELSE format. Should be: "} elseif (...) {"',
'patterns' => [
"/^{:whitespace}\} elseif {:bracket} \{/",
],
],
T_ELSE => [
'message' => 'Unexpected T_ELSE format. Should be: "} else {"',
'patterns' => [
"/^{:whitespace}\} else \{/",
"/^{:whitespace}\} elseif {:bracket} \{/",
],
],
T_DO => [
'message' => 'Unexpected T_DO format. Should be: "do {"',
'patterns' => [
"/^{:whitespace}do \{/",
],
],
T_WHILE => [
'message' => 'Unexpected T_WHILE format. Should be: "while (...) {" or "} while (...);',
'patterns' => [
"/^{:whitespace}while {:bracket} \{/",
"/^{:whitespace}\} while {:bracket};/",
],
],
T_FOR => [
'message' => 'Unexpected T_FOR format. Should be: "for (...; ...; ...) {"',
'patterns' => [
"/^{:whitespace}for {:forBracket} \{/",
],
],
T_FOREACH => [
'message' => 'Unexpected T_FOREACH format. Should be: "foreach (...) {"',
'patterns' => [
"/^{:whitespace}foreach {:bracket} \{/",
],
],
T_SWITCH => [
'message' => 'Unexpected T_SWITCH format. Should be: "switch (...)"',
'patterns' => [
"/^{:whitespace}switch {:bracket}/",
],
],
T_CASE => [
'message' => 'Unexpected T_CASE format. Should be: "case ...:"',
'patterns' => [
"/^{:whitespace}case [^\\n]*:/",
],
],
T_DEFAULT => [
'message' => 'Unexpected T_SWITCH format. Should be: "default:"',
'patterns' => [
"/^{:whitespace}default:/",
],
],
];
/**
* Reusable expressions to make code easier to read and reusable
*
* @var array
*/
protected $_regexMap = [
'whitespace' => '(\s+)?',
'bracket' => '\(([^ ].*[^ ]|[^ ]+)\)',
'forBracket' => '\((?:(?:[^ ](?:[^;]+)?; )+)?(?:[^ ]([^;]+)?)?[^ ]\)',
];
/**
* Will iterate the given tokens finding them based on the keys of self::$_tokenMap.
* Upon finding the matching tokens it will attempt to match the line against a regular
* expression proivded in tokenMap and if none are found add a violation from the message
* provided in tokenMap.
*
* @param Testable $testable The testable object
* @return void
*/
public function apply($testable, array $config = [])
{
$tokens = $testable->tokens();
$filtered = $testable->findAll(array_keys($this->_tokenMap));
foreach ($filtered as $tokenId) {
$token = $tokens[$tokenId];
$tokenMap = $this->_tokenMap[$token['id']];
$patterns = $tokenMap['patterns'];
$body = $this->_extractContent($tokenId, $tokens);
$singleLine = $this->_matchPattern($patterns, $body);
$multiLine = false;
if (!$singleLine) {
foreach ($patterns as $key => $value) {
$patterns[$key] .= 's';
}
$multiLine = $this->_matchPattern($patterns, $body);
}
if (!$singleLine && !$multiLine) {
$this->addViolation([
'message' => $this->_tokenMap[$token['id']]['message'],
'line' => $token['line'],
]);
} elseif (!$singleLine) {
$this->addWarning([
'message' => $this->_tokenMap[$token['id']]['message'] . ' on a signle line.',
'line' => $token['line'],
]);
}
}
}
/**
* Extract the Control content and its prefix
*
* @param array $tokenId The id of the token.
* @param array $tokens The tokens from $testable->tokens()
* @return string The extracted content + prefix
*/
protected function _extractContent($tokenId, $tokens)
{
$token = $tokens[$tokenId];
$body = $this->_controlContent($tokenId, $tokens);
$line = $token['line'];
while (--$tokenId >= 0 && $tokens[$tokenId]['line'] === $line) {
$body = $tokens[$tokenId]['content'] . $body;
}
return $body;
}
/**
* Extract the control content
*
* @param array $tokenId The id of the token.
* @param array $tokens The tokens from $testable->tokens()
* @return string The extracted content
*/
protected function _controlContent($tokenId, $tokens, $root = true)
{
$token = $tokens[$tokenId];
$body = $token['content'];
foreach ($token['children'] as $childrenId) {
if (!$tokens[$childrenId]['children']) {
$body .= $tokens[$childrenId]['content'];
} elseif ($root && $tokens[$childrenId]['content'] === '{') {
$body .= $tokens[$childrenId]['content'];
break;
} else {
$body .= $this->_controlContent($childrenId, $tokens, false);
}
}
return $body;
}
/**
* Abstracts the matching out. Will return true if any of the patterns match correctly.
*
* @param array $patterns The patterns to match overs.
* @param string $body The string body.
* @return bool
*/
protected function _matchPattern($patterns, $body)
{
foreach ($patterns as $pattern) {
if (preg_match(Text::insert($pattern, $this->_regexMap), $body) === 1) {
return true;
}
}
return false;
}
}
?>

43
nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/EndsWithCloseTag.php

@ -0,0 +1,43 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2014 nZEDb
*/
namespace app\extensions\qa\rules\syntax;
class EndsWithCloseTag extends \li3_quality\qa\rules\syntax\EndsWithCloseTag
{
public function apply($testable, array $config = [])
{
$message = "File does not end with ?>";
$lines = $testable->lines();
$cnt = count($lines);
if ($cnt > 1) {
if (!((empty($lines[$cnt - 1]) && $lines[($cnt - 2)] === "?>") || ($lines[($cnt - 1)] === "?>"))) {
$this->addViolation(
[
'message' => $message,
'line' => $cnt - 1
]);
}
}
}
}
?>

58
nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/HasCorrectPermissions.php

@ -0,0 +1,58 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2015 nZEDb
*/
namespace app\extensions\qa\rules\syntax;
class HasCorrectPermissions extends \li3_quality\qa\rules\syntax\HasCorrectPermissions
{
/**
* @var array Specific permissions allowed for specified file suffixes.
*/
public $permsAllowed = [
'php' => '775',
];
/**
* @var string Default permissions for unspecified file suffixes.
*/
public $permsDefault = '644';
public function apply($testable, array $config = [])
{
$suffix = pathinfo($testable->config('path'), PATHINFO_EXTENSION);
$message = "Permissions for '.%s' files should be '%s', found '%s'.";
$permsFound = substr(sprintf('%o', fileperms($testable->config('path'))), -3);
$permsAllowed = array_key_exists($suffix, $this->permsAllowed)
? $this->permsAllowed[$suffix] : $this->permsDefault;
if (!preg_match("#$permsAllowed#", $permsFound)) {
$this->addViolation([
'message' => sprintf(
$message,
$suffix,
$permsAllowed,
$permsFound
)
]);
}
}
}
?>

48
nZEDb_data/nZEDb/app/extensions/qa/rules/syntax/HasNoTrailingWhitespace.php

@ -0,0 +1,48 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2015 nZEDb
*/
namespace app\extensions\qa\rules\syntax;
use lithium\g11n\Multibyte;
class HasNoTrailingWhitespace extends \li3_quality\qa\rules\syntax\HasNoTrailingWhitespace
{
public function apply($testable, array $config = array())
{
$message = "Trailing whitespace found";
$lines = $testable->lines();
foreach ($lines as $i => $line) {
$name = 'li3_quality';
$length = Multibyte::strlen($line, compact('name'));
$lengthTrimmed = Multibyte::strlen(rtrim($line), compact('name'));
if ($length !== $lengthTrimmed) {
$this->addViolation(array(
'message' => $message,
'line' => $i + 1,
'position' => $length
));
}
}
}
}
?>

216
nZEDb_data/nZEDb/app/extensions/util/Git.php

@ -0,0 +1,216 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\util;
use \GitRepo;
class Git extends \lithium\core\ObjectDeprecated
{
/**
* @var \GitRepo object
*/
protected $repo;
protected $gitTagLatest = null;
private $branch;
public function __construct(array $config = [])
{
$defaults = [
'branches' => [
'stable' => ['0.x', 'Latest-testing', '\d+\.\d+\.\d+(\.\d+)?'],
'development' => ['dev', 'dev-test']
],
'create' => false,
'initialise' => false,
'filepath' => nZEDb_ROOT,
];
parent::__construct($config += $defaults);
}
/**
* Run describe command.
*
* @param string $options
*
* @return string
*/
public function describe($options = null)
{
return $this->run("describe $options");
}
/**
* Return the currently active branch
*
* @return string
*/
public function getBranch()
{
return $this->branch;
}
public function getBranchesDevelop()
{
return $this->_config['branches']['development'];
}
/**
* Fetches the array of branch names that are considered to be core.
*
* @return array
*/
public function getBranchesMain()
{
$main = array_merge($this->getBranchesStable(), $this->getBranchesDevelop());
return $main;
}
public function getBranchesStable()
{
return $this->_config['branches']['stable'];
}
public function getHeadHash()
{
return $this->run('rev-parse HEAD');
}
/**
* Determine if the supplied object is commited to the repository or not.
*
* @param $gitObject
*
* @return bool
* @throws \Exception
*/
public function isCommited($gitObject)
{
$cmd = "cat-file -e $gitObject";
try {
$result = $this->run($cmd);
} catch (\Exception $e) {
$message = explode("\n", $e->getMessage());
if ($message[0] === "fatal: Not a valid object name $gitObject") {
$result = false;
} else {
throw new \Exception($message);
}
}
return ($result === '');
}
public function isStable($branch)
{
foreach ($this->getBranchesStable() as $pattern) {
if (!preg_match("#$pattern#", $branch)) {
continue;
} else {
return true;
}
}
return false;
}
/**
* Run the log command.
*
* @param string|null $options
*
* @return string
*/
public function log($options = null)
{
return $this->run("log $options");
}
public function pull(array $options = [])
{
$default = [
'branch' => $this->getBranch(),
'remote' => 'origin',
];
$options += $default;
return $this->repo->pull($options['remote'], $options['branch']);
}
/**
* Run a git command in the git repository
* Accepts a git command to run
*
* @access public
*
* @param string $command Command to run
*
* @return string
*/
public function run($command)
{
return $this->repo->run($command);
}
/**
* Run the tag command.
*
* @param string $options
*
* @return string
*/
public function tag($options = null)
{
return $this->run("tag $options");
}
/**
* Fetch the most recently added tag.
*
* Be aware this might cause problems if tags are added out of order?
*
* @return string
*/
public function tagLatest($cached = true)
{
if (empty($this->gitTagLatest) || $cached === false) {
$this->gitTagLatest = trim($this->describe("--tags --abbrev=0 HEAD"));
if (strtolower($this->gitTagLatest[0]) === 'v') {
$this->gitTagLatest = substr($this->gitTagLatest, 1);
}
}
return $this->gitTagLatest;
}
protected function _init()
{
parent::_init();
$this->repo = new GitRepo(
$this->_config['filepath'],
$this->_config['create'],
$this->_config['initialise']
);
$this->branch = $this->repo->active_branch();
}
}

335
nZEDb_data/nZEDb/app/extensions/util/Versions.php

@ -0,0 +1,335 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\util;
use app\models\Settings;
use lithium\core\ConfigException;
use nzedb\utility\Misc;
class Versions extends \lithium\core\ObjectDeprecated
{
/**
* These constants are bitwise for checking what has changed.
*/
const UPDATED_GIT_TAG = 1;
const UPDATED_SQL_DB_PATCH = 2;
const UPDATED_SQL_FILE_LAST = 4;
/**
* @var integer Bitwise mask of elements that have been changed.
*/
protected $changes = 0;
/**
* @var \app\extensions\util\Git object.
*/
protected $git;
/**
* @var \simpleXMLElement object.
*/
protected $versions = null;
/**
* @var \simpleXMLElement object
*/
protected $xml = null;
public function __construct(array $config = [])
{
$defaults = [
'git' => null,
'path' => nZEDb_VERSIONS,
];
parent::__construct($config += $defaults);
}
/**
* Checks git's latest version tag against the XML's stored value. Version should be
* Major.Minor.Revision[.fix][-dev|-RCx]
*
* @param boolean $update Wether to update the file.
*
* @return string|false version string if matched or false.
*/
public function checkGitTagInFile($update = false)
{
$this->initialiseGit();
$result = preg_match(Misc::VERSION_REGEX, $this->git->tagLatest(), $matches) ? $matches['digits'] : false;
if ($result !== false) {
if (!$this->git->isStable($this->git->getBranch())) {
$this->loadXMLFile();
$result = preg_match(Misc::VERSION_REGEX, $this->versions->git->tag->__toString(),
$matches) ? $matches['digits'] : false;
if ($result !== false) {
if (version_compare($matches['digits'], '0.0.0', '!=')) {
$this->versions->git->tag = '0.0.0-dev';
$this->changes |= self::UPDATED_GIT_TAG;
}
}
$result = $this->versions->git->tag;
} else {
$result = $this->checkGitTagsAreEqual(['update' => $update]);
}
}
return $result;
}
public function checkGitTagsAreEqual(array $options = [])
{
$options += [
'update' => true,
'verbose' => true,
];
$this->loadXMLFile();
$latestTag = $this->git->tagLatest();
// Check if file's entry is the same as current branch's tag
if (version_compare($this->versions->git->tag, $latestTag, '!=')) {
if ($options['update'] === true) {
if ($options['verbose'] === true) {
echo "Updating tag version to $latestTag" . PHP_EOL;
}
$this->versions->git->tag = $latestTag;
$this->changes |= self::UPDATED_GIT_TAG;
return $this->versions->git->tag;
} else { // They're NOT the same but we were told not to update.
if ($options['verbose'] === true) {
echo "Current tag version $latestTag, skipping update!" . PHP_EOL;
}
return false;
}
} else { // They're the same so return true
return true;
}
}
/**
* Checks the database sqlpatch setting against the XML's stored value.
*
* @param boolean $verbose
*
* @return boolean|string The new database sqlpatch version, or false.
*/
public function checkSQLDb($verbose = true)
{
$this->loadXMLFile();
$patch = $this->getSQLPatchFromDB();
if ($this->versions->sql->db->__toString() != $patch) {
if ($verbose) {
echo "Updating Db revision to $patch" . PHP_EOL;
}
$this->versions->sql->db = $patch;
$this->changes |= self::UPDATED_SQL_DB_PATCH;
}
return $this->isChanged(self::UPDATED_SQL_DB_PATCH) ? $patch : false;
}
public function checkSQLFileLatest($verbose = true)
{
$this->loadXMLFile();
$lastFile = $this->getSQLPatchLast();
if ($lastFile !== false && $this->versions->sql->file->__toString() != $lastFile) {
if ($verbose === true) {
echo "Updating latest patch file to $lastFile" . PHP_EOL;
}
$this->versions->sql->file = $lastFile;
$this->changes |= self::UPDATED_SQL_FILE_LAST;
}
/*
if ($this->versions->sql->file->__toString() != $lastFile) {
$this->versions->sql->file = $lastFile;
$this->changes |= self::UPDATED_SQL_DB_PATCH;
}*/
}
public function getGitBranch()
{
$this->initialiseGit();
return $this->git->getBranch();
}
public function getGitHeadHash()
{
$this->initialiseGit();
return $this->git->getHeadHash();
}
public function getGitTagInFile()
{
$this->loadXMLFile();
return ($this->versions === null) ? null : $this->versions->git->tag->__toString();
}
public function getGitTagInRepo()
{
$this->initialiseGit();
return $this->git->tagLatest();
}
public function getSQLPatchFromDB()
{
$dbVersion = Settings::value('..sqlpatch', true);
if (!is_numeric($dbVersion)) {
throw new \Exception('Bad sqlpatch value');
}
return $dbVersion;
}
public function getSQLPatchFromFile()
{
$this->loadXMLFile();
return ($this->versions === null) ? null : $this->versions->sql->file->__toString();
}
public function getSQLPatchLast()
{
$options = [
'data' => nZEDb_RES . 'db' . DS . 'schema' . DS . 'data' . DS,
'ext' => 'sql',
'path' => nZEDb_RES . 'db' . DS . 'patches' . DS . 'mysql',
'regex' => '#^' . Misc::PATH_REGEX . '(?P<patch>\d{4})~(?P<table>\w+)\.sql$#',
'safe' => true,
];
$files = Misc::getDirFiles($options);
natsort($files);
return (preg_match($options['regex'], end($files), $matches)) ? (int)$matches['patch'] : false;
}
public function getTagVersion()
{
$this->deprecated(__METHOD__, 'getGitTagInRepo');
return $this->getGitTagInRepo();
}
public function getValidVersionsFile()
{
$this->loadXMLFile();
return $this->xml;
}
/**
* Check whether the XML has been changed by one of the methods here.
*
* @return boolean True if the XML has been changed.
*/
public function hasChanged()
{
return $this->changes != 0;
}
public function save($verbose = true)
{
if ($this->hasChanged()) {
if ($verbose === true && $this->changes > 0) {
if ($this->isChanged(self::UPDATED_GIT_TAG)) {
echo "Updated git tag version to " . $this->versions->git->tag . PHP_EOL;
}
if ($this->isChanged(self::UPDATED_SQL_DB_PATCH)) {
echo "Updated Db SQL revision to " . $this->versions->sql->db . PHP_EOL;
}
if ($this->isChanged(self::UPDATED_SQL_FILE_LAST)) {
echo "Updated latest SQL file to " . $this->versions->sql->file . PHP_EOL;
}
} else if ($this->changes == 0) {
echo "Version file already up to date." . PHP_EOL;
}
$this->xml->asXML($this->_config['path']);
$this->changes = 0;
}
}
protected function error($message)
{
// TODO handle console error message.
}
protected function initialiseGit()
{
if ($this->_config['git'] instanceof \app\extensions\util\Git) {
$this->git =& $this->_config['git'];
} else if (!($this->git instanceof \app\extensions\util\Git)) {
try {
$this->git = new \app\extensions\util\Git();
} catch (\Exception $e) {
throw new ConfigException("Unable to initialise Git object!");
}
}
}
protected function isChanged($property)
{
return (($this->changes & $property) == $property);
}
protected function loadXMLFile()
{
if (empty($this->versions)) {
$temp = libxml_use_internal_errors(true);
$this->xml = simplexml_load_file($this->_config['path']);
libxml_use_internal_errors($temp);
if ($this->xml === false) {
$this->error(
"Your versions XML file ({$this->_config['path']}) is broken, try updating from git."
);
throw new \Exception("Failed to open versions XML file '{$this->_config['path']}'");
}
if ($this->xml->count() > 0) {
$vers = $this->xml->xpath('/nzedb/versions');
if ($vers[0]->count() == 0) {
$this->error("Your versions XML file ({$this->_config['path']}) does not contain version info, try updating from git.");
throw new \Exception("Failed to find versions node in XML file '{$this->_config['path']}'");
} else {
$this->versions = &$this->xml->versions; // Create a convenience shortcut
}
} else {
throw new \RuntimeException("No elements in file!\n");
}
}
}
protected function _init()
{
return parent::_init();
}
private function deprecated($methodOld, $methodUse)
{
trigger_error("This method ($methodOld) is deprecated. Please use '$methodUse' instead.",
E_USER_NOTICE);
}
}

83
nZEDb_data/nZEDb/app/extensions/util/Yenc.php

@ -0,0 +1,83 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\util;
class Yenc extends \lithium\core\Adaptable
{
/**
* `Libraries::locate()`-compatible path to adapter for this class.
*
* @see \lithium\core\Libraries::locate()
* @var string Dot-delimited path.
*/
protected static $_adapters = 'adapter.extensions.util.yenc';
/**
* Contains adapter configurations for `yEnc` adapter.
*
* @var array
*/
protected static $_configurations = [];
/**
* @param $text yEncoded text to decode back to an 8 bit form.
* @param array $options Options needed for method. Mainly:
* - 'name' of the configuration to use.
* * 'file' whether to create the file or just return the string.
*
* @return string 8 bit decoded version of $text.
*/
public static function decode(&$text, array $options = [])
{
$options += [
'name' => 'default',
'file' => true,
];
return static::adapter($options['name'])->decode($text);
}
public static function decodeIgnore(&$text, array $options = [])
{
$options += [
'name' => 'default',
'file' => true,
];
return static::adapter($options['name'])->decodeIgnore($text);
}
/**
* @param binary $data 8 bit data to convert to yEncoded text.
* @param string $filename Name of file to recreate as.
* @param int $line Maximum number of characters in each line.
* @param boolean $crc32 Whether to add CRC checksum to yend line. This is recommended.
* @param array $options Options needed for method. Mainly the 'name' of the configuration
* to use.
*
* @return string|\Exception The yEncoded version of $data.
*/
public static function encode(&$data, $filename, $line = 128, $crc32 = true, array $options = [])
{
$options += ['name' => 'default'];
return static::adapter($options['name'])->encode($data, $filename, $line, $crc32);
}
}

58
nZEDb_data/nZEDb/app/extensions/util/yenc/adapter/NzedbYenc.php

@ -0,0 +1,58 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\util\yenc\adapter;
use yenc\yenc;
class NzedbYenc extends \lithium\core\ObjectDeprecated
{
public static function decode(&$text)
{
return (new yenc())->decode($text);
}
public static function decodeIgnore(&$text)
{
return (new yenc())->decode($text, true);
}
/**
* Determines if this adapter is enabled by checking if the `yenc` extension is loaded.
*
* @return boolean Returns `true` if enabled, otherwise `false`.
*/
public static function enabled()
{
return extension_loaded('yenc');
}
public static function encode($data, $filename, $lineLength = 128)
{
return (new yenc())->encode($data, $filename, $lineLength);
}
protected function _init()
{
parent::_init();
}
}
?>

209
nZEDb_data/nZEDb/app/extensions/util/yenc/adapter/Php.php

@ -0,0 +1,209 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\extensions\util\yenc\adapter;
/**
* Class Php
*
* @package app\extensions\util\yenc\adapter
*/
class Php extends \lithium\core\ObjectDeprecated
{
public static function decode(&$text)
{
$crc = '';
// Extract the yEnc string itself.
if (preg_match("/=ybegin.*size=([^ $]+).*\\r\\n(.*)\\r\\n=yend.*size=([^ $\\r\\n]+)(.*)/ims",
$text,
$encoded)) {
if (preg_match('/crc32=([^ $\\r\\n]+)/ims', $encoded[4], $trailer)) {
$crc = trim($trailer[1]);
}
$headerSize = $encoded[1];
$trailerSize = $encoded[3];
$encoded = $encoded[2];
} else {
return false;
}
// Remove line breaks from the string.
$encoded = trim(str_replace("\r\n", '', $encoded));
// Make sure the header and trailer file sizes match up.
if ($headerSize != $trailerSize) {
$message = 'Header and trailer file sizes do not match. This is a violation of the yEnc specification.';
if (nZEDb_LOGGING || nZEDb_DEBUG) {
//TODO replace with lithium logger.
// $this->_debugging->log(get_class(), __FUNCTION__, $message, Logger::LOG_NOTICE);
}
throw new \RuntimeException($message);
}
// Decode.
$decoded = '';
$encodedLength = strlen($encoded);
for ($chr = 0; $chr < $encodedLength; $chr++) {
$decoded .= (
$encoded[$chr] == '=' ?
chr((ord($encoded[$chr]) - 42) % 256) :
chr((((ord($encoded[++$chr]) - 64) % 256) - 42) % 256)
);
}
// Make sure the decoded file size is the same as the size specified in the header.
if (strlen($decoded) != $headerSize) {
$message = "Header file size ($headerSize) and actual file size (" . strlen($decoded) .
") do not match. The file is probably corrupt.";
if (nZEDb_LOGGING || nZEDb_DEBUG) {
//TODO replace with lithium logger.
// $this->_debugging->log(get_class(), __FUNCTION__, $message, Logger::LOG_NOTICE);
}
throw new \RuntimeException($message);
}
// Check the CRC value
if ($crc !== '' && (strtolower($crc) !== strtolower(sprintf("%04X", crc32($decoded))))) {
$message = 'CRC32 checksums do not match. The file is probably corrupt.';
if (nZEDb_LOGGING || nZEDb_DEBUG) {
//TODO replace with lithium logger.
// $this->_debugging->log(get_class(), __FUNCTION__, $message, Logger::LOG_NOTICE);
}
throw new \RuntimeException($message);
}
return $decoded;
}
/**
* Decode a string of text encoded with yEnc. Ignores all errors.
*
* @param string $text The encoded text to decode.
*
* @return string The decoded yEnc string, or the input string, if it's not yEnc.
* @access protected
*/
public static function decodeIgnore(&$text)
{
if (preg_match('/^(=yBegin.*=yEnd[^$]*)$/ims', $text, $input)) {
$text = '';
$input =
trim(
preg_replace(
'/\r\n/im',
'',
preg_replace(
'/(^=yEnd.*)/im',
'',
preg_replace(
'/(^=yPart.*\\r\\n)/im',
'',
preg_replace('/(^=yBegin.*\\r\\n)/im', '', $input[1], 1),
1),
1)
)
);
$length = strlen($input);
for ($chr = 0; $chr < $length; $chr++) {
$text .= (
$input[$chr] == '=' ?
chr((((ord($input[++$chr]) - 64) % 256) - 42) % 256) :
chr((ord($input[$chr]) - 42) % 256)
);
}
}
return $text;
}
public static function enabled()
{
return true;
}
public static function encode($data, $filename, $lineLength = 128, $crc32 = true)
{
// yEnc 1.3 draft doesn't allow line lengths of more than 254 bytes.
if ($lineLength > 254) {
$lineLength = 254;
}
if ($lineLength < 1) {
$message = $lineLength . ' is not a valid line length.';
if (nZEDb_LOGGING || nZEDb_DEBUG) {
//TODO replace with lithium logger.
// $this->_debugging->log(get_class(), __FUNCTION__, $message, Logger::LOG_NOTICE);
}
throw new \RuntimeException($message);
}
$encoded = '';
$stringLength = strlen($data);
// Encode each character of the string one at a time.
for ($i = 0; $i < $stringLength; $i++) {
$value = ((ord($data[$i]) + 42) % 256);
// Escape NULL, TAB, LF, CR, space, . and = characters.
switch ($value) {
case 0:
case 10:
case 13:
case 61:
$encoded .= ('=' . chr(($value + 64) % 256));
break;
default:
$encoded .= chr($value);
break;
}
}
$encoded =
'=ybegin line=' .
$lineLength .
' size=' .
$stringLength .
' name=' .
trim($filename) .
"\r\n" .
trim(chunk_split($encoded, $lineLength)) .
"\r\n=yend size=" .
$stringLength;
// Add a CRC32 checksum if desired.
if ($crc32 === true) {
$encoded .= ' crc32=' . strtolower(sprintf("%X", crc32($data)));
}
return $encoded;
}
protected function _init()
{
parent::_init();
}
}
?>

21
nZEDb_data/nZEDb/app/index.php

@ -0,0 +1,21 @@
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2015, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
/**
* This file may act as a forwarder for the actual front-controller within `app/webroot/index.php`.
* This is to make setups work where you have placed the whole project within the webserver's
* docroot. This should be avoided in production environments. Instead point the webserver's
* docroot to `app/webroot` and let just that be served. You may then safely remove this file.
*/
/**
* Include and forward to the actual front-controller.
*/
require 'webroot/index.php';
?>

2
nZEDb_data/nZEDb/app/libraries/.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

27
nZEDb_data/nZEDb/app/models/Countries.php

@ -0,0 +1,27 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\models;
class Countries extends \app\extensions\data\Model
{
public $validates = [];
}
?>

31
nZEDb_data/nZEDb/app/models/Films.php

@ -0,0 +1,31 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\models;
class Films extends \app\extensions\data\Model
{
protected $_meta = [
'source' => 'movies',
];
public $validates = [];
}
?>

441
nZEDb_data/nZEDb/app/models/Groups.php

@ -0,0 +1,441 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\models;
use lithium\data\collection\RecordSet;
class Groups extends \app\extensions\data\Model
{
public $belongsTo = ['Releases', 'ReleasesGroups'];
public $validates = [
'active' => [
'bool' => ['boolean']
],
'backfill' => [
'bool' => ['boolean']
],
'backfill_target' => [
'number' => [ 'numeric' ],
],
'description' => [
'require' =>
['required' => true],
],
'first_record' => [
'number' => [ 'numeric' ],
],
//'id' => [
// 'index' => ['numeric']
//]
'last_record' => [
'number' => [ 'numeric' ],
],
//'minfilestoformrelease' => [
// 'number' => [ 'numeric' ],
//],
//'minsizetoformrelease' => [
// 'number' => [' numeric' ],
//],
'name' => [
[
'required' => true,
'notEmpty',
'message' => 'The group\'s name is required to create a new entry.'
],
],
];
/**
* Create a new Group entry.
*
* @param array $data Column names/value pairs. Valid columns are:
* id
* name
* backfill_target
* first_record
* first_record_postdate
* last_record
* last_record_postdate
* last_updated
* minfilestoformrelease
* minsizetoformrelease
* active
* backfill
* description
* Warning: setting 'id' is allowed, but not recommended unless you can
* be certain that the id is available.
* @param array $options
*
* @return \lithium\data\Entity This *should* return a lithium\data\entity\Record object, but
* it actually returns a RecordSet for some reason.
* @throws \InvalidArgumentException if the new group's name is omitted.
*/
public static function create(array $data = [], array $options = [])
{
// TODO reinstate validation of name field once all lithium's edge cases are resolved.
/*
if ((!empty($data) && !isset($data['name']) || )) {
throw new \InvalidArgumentException("To create a new group entry, you *must* supply the new group's name!\n" . print_r($data, true));
}
*/
if (!empty($data) && \count($data) > 1) {
$defaults = [
'active' => false,
'backfill' => false,
'backfill_target' => 1,
'description' => 'Auto-created by ' . __CLASS__ . '::' . __METHOD__,
'first_record' => 0,
'last_record' => 0,
//'minfilestoformrelease' => 0,
//'minsizetoformrelease' => 0,
];
$data += $defaults;
}
return parent::create($data, $options);
}
/**
* Finds a groups' entry using its name. Optionally creates the group entry if it does not
* exist.
*
* @param $name
* @param array $options
*
* @return int|null
*
* @throws \InvalidArgumentException if a new entry must be created but the 'name' is not set.
*/
public static function findIdFromName($name, array $options = [])
{
$defaults = [
'create' => false,
'description' => 'Auto-created by ' . __CLASS__ . '::' . __METHOD__,
];
$options += $defaults;
$group = self::find('first',
[
'fields' => ['id'],
'conditions' => ['name' => $name],
]
);
if ($group === null && $options['create'] === true) {
try {
$group = static::create(
[
'name' => $name,
'description' => $options['description']
]
);
} catch (\InvalidArgumentException $e) {
throw new \InvalidArgumentException($e->getMessage() . PHP_EOL . 'Thrown in \app\models\Groups.php');
}
$group->save();
}
return $group === null ? null : $group->id;
}
/**
* Returns an array of active groups and their associated data.
*
* @return array
*/
public static function getActive() : array
{
return static::find('all',
[
'fields' => [
'id',
'name',
'backfill_target',
'first_record',
'first_record_postdate',
'last_record',
'last_record_postdate',
'last_updated',
'minfilestoformrelease',
'minsizetoformrelease',
'active',
'backfill',
'description',
],
'conditions' => ['active' => true],
'order' => 'name',
]
)->data();
}
public static function getActiveIDs()
{
return static::find('all',
[
'fields' => ['id'],
'conditions' => ['active' => true],
]
);
}
/**
* Get all fields for given group ID.
*
* @param $id
*
* @return array
*/
public static function getAllByID($id) : array
{
$active = static::find('first',
[
'fields' => [
'id',
'name',
'backfill_target',
'first_record',
'first_record_postdate',
'last_record',
'last_record_postdate',
'last_updated',
'minfilestoformrelease',
'minsizetoformrelease',
'active',
'backfill',
'description',
],
'conditions' => ['id' => $id],
]
);
return $active->data();
}
/**
* Get all fields for given group name.
*
* @param string $name
*
* @return mixed
*/
public static function getAllByName(string $name)
{
$active = static::find('first',
[
'fields' => [
'id',
'name',
'backfill_target',
'first_record',
'first_record_postdate',
'last_record',
'last_record_postdate',
'last_updated',
'minfilestoformrelease',
'minsizetoformrelease',
'active',
'backfill',
'description',
],
'conditions' => ['name' => $name],
]
);
return $active->data();
}
/**
* @param string $order
* @param bool $active
*
* @return array
*/
public static function getBackfilling(string $order, bool $active = true) : array
{
switch (\strtolower($order)) {
case '':
case 'normal':
$order = 'name ASC';
break;
case 'date':
$order = 'first_record_postdate DESC';
break;
default:
throw new \InvalidArgumentException("Order must be 'normal' or 'date'");
}
$results = static::find('all',
[
'fields' => [
'id',
'name',
'backfill_target',
'first_record',
'first_record_postdate',
'last_record',
'last_record_postdate',
'last_updated',
'minfilestoformrelease',
'minsizetoformrelease',
'active',
'backfill',
'description',
],
'conditions' => ['active' => $active, 'backfill' => true],
'order' => $order
]
);
return ($results instanceof RecordSet) ? $results->data() : [];
}
/**
* Get a group ID using its name.
*
* @param string $name
*
* @return string Empty string on failure, groups_id on success.
*/
public static function getIDByName(string $name) : string
{
$entry = static::find('first',
[
'fields' => ['id'],
'conditions' => ['name' => $name],
]
);
return $entry !== null ? $entry->data()['id'] : '';
}
/**
* Get a group name using its ID.
*
* @param int|string $id The group ID.
*
* @return string Empty string on failure, group name on success.
*/
public static function getNameByID($id) : string
{
$entry = static::find('first',
[
'fields' => ['name'],
'conditions' => ['id' => $id],
]
);
return $entry !== null ? $entry->data()['name'] : '';
}
/**
* Fetch a range of groups, taking maximum items per page and pageno into account. Optionally
* limiting by %groupname% matching.
*
* @param int $pageno
* @param int $number
* @param string $groupname
* @param bool|null $active Whether result should be filtered by active/inactive, or
* neither. true/false or null.
*
* @return mixed
*/
public static function getRange(int $pageno = 1, int $number = ITEMS_PER_PAGE, $groupname = '', $active = null)
{
$conditions = empty($groupname) ? [] : ['name' => ['LIKE' => "%$groupname%"]];
$conditions += \is_null($active) ? [] : ['active' => $active];
$results = static::find('all',
[
'fields' => [
'id',
'name',
'backfill_target',
'first_record',
'first_record_postdate',
'last_record',
'last_record_postdate',
'last_updated',
'minfilestoformrelease',
'minsizetoformrelease',
'active',
'backfill',
'description',
],
'conditions' => $conditions,
'limit' => $number,
'order' => 'name ASC',
'page' => $pageno,
]
);
return $results->data();
}
/**
* Checks group name is standard and replaces the shorthand prefix if it exists.
*
* @param string $name The full name of the usenet group being evaluated
*
* @return string|bool The name of the group replacing shorthand prefix or false if groupname was malformed
*/
public static function isValidName(string $name)
{
if (preg_match('/^([\w-]+\.)+[\w-]+$/i', $name)) {
return preg_replace('/^a\.b\./i', 'alt.binaries.', $name, 1);
}
return false;
}
/**
* @param int|string $id id of group to update.
* @param string $column 'active' or 'backfill'
* @param int $status
*
* @return string
*
* @throws \InvalidArgumentException if column is not one of the two permitted.
*/
public static function updateStatus($id, string $column, int $status = 0) : string
{
if (! \in_array($column, ['active', 'backfill'])) {
throw new \InvalidArgumentException("Only 'active' and 'backfill' status can be updated.");
}
$group = static::find('first',
[
'conditions' => ['id' => $id],
'fields' => ['id', $column]
]
);
$group->$column = $status;
$group->save();
$text = $status == 0 ? 'deactivated' : 'activated';
return "Group $id: $column has been $text";
}
}
?>

53
nZEDb_data/nZEDb/app/models/MultigroupPosters.php

@ -0,0 +1,53 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\models;
class MultigroupPosters extends \app\extensions\data\Model
{
protected $_meta = [
'key' => ['poster']
];
public $validates = [
'poster' => [
'notEmpty',
'message' => 'Empty poster value is not permitted.'
]
];
public static function commaSeparatedList()
{
$list = [];
$posters = MultigroupPosters::find('all',
[
'fields' => ['poster'],
'order' => ['poster' => 'ASC'],
]
);
foreach ($posters as $poster) {
$list[] = $poster->poster;
}
return implode("','", $list);
}
}
?>

77
nZEDb_data/nZEDb/app/models/Predb.php

@ -0,0 +1,77 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2017 nZEDb
*/
namespace app\models;
use lithium\data\Entity;
class Predb extends \app\extensions\data\Model
{
public $hasMany = ['Groups'];
public $validates = [
'title' => [
[
'required' => true
],
[
'notEmpty',
'message' => 'You must supply a title for this entry.'
]
]
];
public static function findRange($page = 1, $limit = ITEMS_PER_PAGE, $title = '')
{
$options = [
'limit' => $limit,
'order' => ['created' => 'DESC'],
'page' => (int)$page
];
$options += Predb::getRangeWhere($title);
$result = Predb::find('all', $options);
return $result;
}
public static function findRangeCount($title = '')
{
$options = Predb::getRangeWhere($title);
return Predb::find('count', $options);
}
public static function getRangeWhere($title = '')
{
$where = [];
if ($title != '') {
$where += ['title' => ['LIKE' => "%$title%"]];
}
$options = [];
if (!empty($where)) {
$options += ['conditions' => $where];
}
return $options;
}
}
?>

30
nZEDb_data/nZEDb/app/models/ReleasesGroups.php

@ -0,0 +1,30 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\models;
class ReleasesGroups extends \app\extensions\data\Model
{
public $belongsTo = ['Releases'];
public $hasMany = ['Groups'];
protected $_meta = [
'key' => ['releases_id', 'groups_id'],
];
}

294
nZEDb_data/nZEDb/app/models/Settings.php

@ -0,0 +1,294 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\models;
use nzedb\utility\Text;
/**
* Settings - model for settings table.
*
* li3 app completely ignore the 'setting' column and only uses 'section', 'subsection', and 'name'
* for finding values/hints.
*
*@package app\models
*/
class Settings extends \app\extensions\data\Model
{
const REGISTER_STATUS_OPEN = 0;
const REGISTER_STATUS_INVITE = 1;
const REGISTER_STATUS_CLOSED = 2;
const REGISTER_STATUS_API_ONLY = 3;
const ERR_BADUNRARPATH = -1;
const ERR_BADFFMPEGPATH = -2;
const ERR_BADMEDIAINFOPATH = -3;
const ERR_BADNZBPATH = -4;
const ERR_DEEPNOUNRAR = -5;
const ERR_BADTMPUNRARPATH = -6;
const ERR_BADNZBPATH_UNREADABLE = -7;
const ERR_BADNZBPATH_UNSET = -8;
const ERR_BAD_COVERS_PATH = -9;
const ERR_BAD_YYDECODER_PATH = -10;
public $validates = [
'section' => [
[
'required' => false
]
],
'subsection' => [
[
'required' => false
]
],
'name' => [
[
'required' => true
],
[
'notEmpty',
'message' => 'You must supply a name for this setting.'
]
],
'value' => [
[
'required' => true
]
],
'hint' => [
[
'required' => true
],
[
'notEmpty',
'message' => 'You must supply a hint/description for this setting.'
]
],
'setting' => [
[
'required' => true
],
[
'notEmpty',
'message' => 'You must supply a name for this setting.'
]
],
];
protected $_meta = [
'key' => ['section', 'subsection', 'name']
];
public static function hasAllEntries($console = null)
{
$filepath = Text::pathCombine(['db', 'schema', 'data', '10-settings.tsv'], nZEDb_RES);
if (!file_exists($filepath)) {
throw new \InvalidArgumentException("Unable to find {$filepath}");
}
$settings = file($filepath);
if (!\is_array($settings)) {
throw new \InvalidArgumentException("Settings is not an array!");
}
$setting = [];
$dummy = array_shift($settings);
$result = false;
if ($dummy !== null) {
if ($console !== null) {
$console->primary("Verifying settings table...");
$console->info("(section, subsection, name):");
}
$result = true;
foreach ($settings as $line) {
$message = '';
list($setting['section'], $setting['subsection'], $setting['name']) =
explode("\t", $line);
$value = Settings::value(
[
'section' => $setting['section'],
'subsection' => $setting['subsection'],
'name' => $setting['name']
],
true);
if ($value === null) {
$result = false;
$message = "error";
}
if ($message != '' && $console !== null) {
$console->out(" {$setting['section']}, {$setting['subsection']}, {$setting['name']}: "
. "MISSING!");
}
}
}
return $result;
}
public static function init()
{
static::finder('setting',
function ($params, $next) {
$params['options']['conditions'] = self::settingToArray($params['options']['conditions']);
$params['type'] = 'first';
$array = array_diff_key(
$params['options'],
array_fill_keys(['conditions', 'fields', 'order', 'limit', 'page'], 0)
);
$params['options'] = array_diff_key($params['options'], $array);
$params['options']['fields'] = ['value', 'hint'];
$result = $next($params);
return $result;
}
);
}
/**
* Return a tree-like array of all or selected settings.
*
* @param array $options Options array for Settings::find() i.e. ['conditions' => ...].
* @param bool $excludeUnsectioned If rows with empty 'section' field should be excluded.
* Note this doesn't prevent empty 'subsection' fields.
* @return array
* @throws \RuntimeException
*/
public static function toTree(array $options = [], $excludeUnsectioned = true)
{
$results = empty($options) ?
Settings::find('all') :
Settings::find('all', $options);
$results = $results->data();
$tree = [];
if (is_array($results)) {
foreach ($results as $result) {
if (!empty($result['section']) || !$excludeUnsectioned) {
$tree[$result['section']][$result['subsection']][$result['name']] =
['value' => $result['value'], 'hint' => $result['hint']];
}
}
} else {
throw new \RuntimeException(
"NO results from Settings table! Check your table has been created and populated."
);
}
return $tree;
}
/**
* Checks the supplied parameter is either a string or an array with single element. If
* either the value is passed to Settings::dottedToArray() for conversion. Otherwise the
* value is returned unchanged.
*
* @param string|array $setting Setting array/string to check.
*
* @return array|boolean
*/
public static function settingToArray($setting)
{
if (!is_array($setting)) {
$setting = self::dottedToArray($setting);
} elseif (count($setting) == 1) {
$setting = self::dottedToArray($setting[0]);
}
return $setting;
}
/**
* Return the value of supplied setting.
* The setting can be either a normal condition array for the custom 'setting' finder or a
* dotted string notation setting. Note that dotted notation will be converted to an array by
* the custom finder, so it will be slower: Explicitly use the array format if speed it paramount.
* Be aware that this method only returns the first of any values found, so make sure your
* $setting produces a unique result.
*
* @param $setting
* @param bool $returnAlways Indicates if the method should throw an exception (false) or return
* null on failure. Defaults to throwing an exception.
*
* @return string|null The setting's value, or null on failure IF 'returnAlways' is true.
* @throws \Exception
*/
public static function value($setting, $returnAlways = false)
{
$result = Settings::find('setting', ['conditions' => $setting, 'fields' => ['value']]);
if ($result !== false && $result->count() > 0) {
$value = $result->data()[0]['value'];
} else if ($returnAlways === false) {
throw new \Exception("Unable to fetch setting from Db!");
} else {
$value = null;
}
return $value;
}
protected static function dottedToArray($setting)
{
$result = [];
if (is_string($setting)) {
$array = explode('.', $setting);
$count = count($array);
if ($count > 3) {
return false;
}
while (3 - $count > 0) {
array_unshift($array, '');
$count++;
}
list(
$result['section'],
$result['subsection'],
$result['name'],
) = $array;
} else {
return false;
}
return $result;
}
}
Settings::init();
?>

30
nZEDb_data/nZEDb/app/models/SteamApps.php

@ -0,0 +1,30 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author DariusIII
* @copyright 2016 NNTmux/nZEDb
*/
namespace app\models;
class SteamApps extends \app\extensions\data\Model
{
protected $_meta = [
'key' => [
'name'
],
];
}
?>

151
nZEDb_data/nZEDb/app/models/Tables.php

@ -0,0 +1,151 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\models;
use lithium\data\Connections;
use lithium\storage\Cache;
class Tables extends \app\extensions\data\Model
{
public $validates = [];
protected $_meta = [
//'connection' => 'information_schema',
'connection' => 'default',
'key' => null,
'source' => 'TABLES',
];
protected $pdo;
protected static $tpgTables = ['binaries', 'collections', 'missed_parts', 'parts'];
public static function createTPGTablesForId(int $groupId)
{
$source = static::connection();
$pdo = $source->connection;
$tpgTables =& static::$tpgTables;
$result = true;
/* @var $tpgTables string[][] */
foreach($tpgTables as $prefix) {
$result = $pdo->exec("CREATE TABLE IF NOT EXISTS {$prefix}_{$groupId} LIKE {$prefix}");
if ($result === false) {
break;
}
}
return $result !== false;
}
public static function init()
{
static::finder('tpg',
function ($params, $next) {
if (! isset($params['options']['prefix'])) {
throw new \InvalidArgumentException('The option "prefix" is required for the TPG finder');
}
$params = [
'type' => 'all',
'options' => [
'conditions' => [
'TABLE_NAME' => [
'LIKE' => "{$params['options']['prefix']}_%"
],
'TABLE_SCHEMA' => Connections::get('default',
['config' => true])['database'],
],
'fields' => [
'TABLE_NAME'
],
],
];
$array = array_diff_key(
$params['options'],
array_fill_keys(['conditions', 'fields', 'order', 'limit', 'page'], 0)
);
$params['options'] = array_diff_key($params['options'], $array);
$result = $next($params);
return $result;
}
);
}
/**
* Get the names of the collections/binaries/parts/missed_part tables.
* Try to create new tables for the groups_id if they are missing. If we fail, log the error and
* exit.
*
* @param int|string $groupId
*
* @return array The table names.
* @throws \RuntimeException If a new table could not be created.
*/
public static function getTPGNamesFromId($groupId) : array
{
// Try cache first.
$names = Cache::read('default', 'tpgNames_' . $groupId);
if (!empty($names)) {
return $names;
}
if (nZEDb_ECHOCLI && static::createTPGTablesForId($groupId) === false) {
throw new \RuntimeException(
"There was a problem creating new TPG tables for this group ID: '$groupId'"
);
}
$tables = [
'cname' => 'collections_' . $groupId,
'bname' => 'binaries_' . $groupId,
'pname' => 'parts_' . $groupId,
'prname'=> 'missed_parts_' . $groupId
];
Cache::write('default', 'tpgNames_' . $groupId, $tables, '+5 minutes');
return $tables;
}
public static function tpg(string $prefix): array
{
if (! \in_array($prefix, static::$tpgTables, false)) {
throw new \InvalidArgumentException("Argument must be one of: 'binaries', 'collections', 'missed_parts', or 'parts'");
};
$tables = self::find('tpg', ['prefix' => $prefix])->data();
$list = [];
/* @var $tables string[][] */
foreach ($tables as $table) {
$list[] = $table['TABLE_NAME'];
}
usort($list, 'strnatcmp');
return $list;
}
}
Tables::init();
?>

33
nZEDb_data/nZEDb/app/models/Videos.php

@ -0,0 +1,33 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2018 nZEDb
*/
namespace app\models;
class Videos extends \app\extensions\data\Model
{
// Anime is one of the types below. _TV if serial, _FILM if cinema or OVA, etc.
const TYPE_UNKNOWN = 0;
const TYPE_TV = 1; // TV programme, but not a film.
const TYPE_FILM = 2; // Film of any type, except if made for TV (i.e. TV Movie on IMDb)/
const TYPE_TVFILM = 3; // Made for TV Film
public $validates = [];
}
?>

0
nZEDb_data/nZEDb/app/models/empty

0
nZEDb_data/nZEDb/app/resources/g11n/empty

0
nZEDb_data/nZEDb/app/resources/tmp/cache/templates/empty

0
nZEDb_data/nZEDb/app/resources/tmp/logs/empty

0
nZEDb_data/nZEDb/app/resources/tmp/tests/empty

20
nZEDb_data/nZEDb/app/tests/cases/controllers/CountriesControllerTest.php

@ -0,0 +1,20 @@
<?php
namespace app\tests\cases\controllers;
use app\controllers\CountriesController;
class CountriesControllerTest extends \lithium\test\Unit
{
public function setUp() {}
public function tearDown() {}
public function testIndex() {}
public function testView() {}
public function testAdd() {}
public function testEdit() {}
public function testDelete() {}
}
?>

37
nZEDb_data/nZEDb/app/tests/cases/controllers/MultigroupPostersControllerTest.php

@ -0,0 +1,37 @@
<?php
namespace app\tests\cases\controllers;
use app\controllers\MultigroupPostersController;
class MultigroupPostersControllerTest extends \lithium\test\Unit
{
public function setUp()
{
}
public function tearDown()
{
}
public function testIndex()
{
}
public function testView()
{
}
public function testAdd()
{
}
public function testEdit()
{
}
public function testDelete()
{
}
}
?>

37
nZEDb_data/nZEDb/app/tests/cases/controllers/SettingsControllerTest.php

@ -0,0 +1,37 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\tests\cases\controllers;
use app\controllers\SettingsController;
class SettingsControllerTest extends \lithium\test\Unit {
public function setUp() {}
public function tearDown() {}
public function testIndex() {}
public function testView() {}
public function testAdd() {}
public function testEdit() {}
public function testDelete() {}
}
?>

20
nZEDb_data/nZEDb/app/tests/cases/controllers/VideosControllerTest.php

@ -0,0 +1,20 @@
<?php
namespace app\tests\cases\controllers;
use app\controllers\VideosController;
class VideosControllerTest extends \lithium\test\Unit {
public function setUp() {}
public function tearDown() {}
public function testIndex() {}
public function testView() {}
public function testAdd() {}
public function testEdit() {}
public function testDelete() {}
}
?>

0
nZEDb_data/nZEDb/app/tests/cases/controllers/empty

0
nZEDb_data/nZEDb/app/tests/cases/extensions/adapter/empty

0
nZEDb_data/nZEDb/app/tests/cases/extensions/command/empty

1
nZEDb_data/nZEDb/app/tests/cases/extensions/data/source/empty

@ -0,0 +1 @@

0
nZEDb_data/nZEDb/app/tests/cases/extensions/helper/empty

35
nZEDb_data/nZEDb/app/tests/cases/extensions/util/YencTest.php

@ -0,0 +1,35 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:.
*
* @link <http://www.gnu.org/licenses/>.
*
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\tests\cases\extensions\util;
class YencTest extends \lithium\test\Unit
{
public function setUp()
{
}
public function tearDown()
{
}
public function test()
{
}
}

BIN
nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc-test.txt

Binary file not shown.

5
nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc-test.ync

@ -0,0 +1,5 @@
=ybegin line=128 size=256 name=yenc-test.txt
*+,-./0123456789:;<=}>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~�걗깂뀊뇠뎷땶뜋룓몤뱮븭뿕솞썫씆윝、$ⅵ㎤
øガ��굉낫독렇뭔뻤슭오좌쳐탬픽�盖誥國喫戇倆厘描白繃嗇飡宸臆預隅膺狀穽增彩充坂沆樺詰�=@=I=J =M=`!"#
$%&'()
=yend size=256 crc32=29058c73

BIN
nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc1.zip

Binary file not shown.

BIN
nZEDb_data/nZEDb/app/tests/cases/extensions/util/yenc/yenc2.zip

Binary file not shown.

16
nZEDb_data/nZEDb/app/tests/cases/models/CountriesTest.php

@ -0,0 +1,16 @@
<?php
namespace app\tests\cases\models;
use app\models\Countries;
class CountriesTest extends \lithium\test\Unit
{
public function setUp() {}
public function tearDown() {}
}
?>

17
nZEDb_data/nZEDb/app/tests/cases/models/MultigroupPostersTest.php

@ -0,0 +1,17 @@
<?php
namespace app\tests\cases\models;
use app\models\MultigroupPosters;
class MultigroupPostersTest extends \lithium\test\Unit
{
public function setUp()
{
}
public function tearDown()
{
}
}
?>

36
nZEDb_data/nZEDb/app/tests/cases/models/SettingsTest.php

@ -0,0 +1,36 @@
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program (see LICENSE.txt in the base directory. If
* not, see:
*
* @link <http://www.gnu.org/licenses/>.
* @author niel
* @copyright 2016 nZEDb
*/
namespace app\tests\cases\models;
use app\models\Settings;
class SettingsTest extends \lithium\test\Unit {
public function setUp() {}
public function tearDown() {}
public function testHasAllEntries()
{
$this->assertTrue(Settings::hasAllEntries());
}
}
?>

16
nZEDb_data/nZEDb/app/tests/cases/models/VideosTest.php

@ -0,0 +1,16 @@
<?php
namespace app\tests\cases\models;
use app\models\Videos;
class VideosTest extends \lithium\test\Unit {
public function setUp() {}
public function tearDown() {}
}
?>

0
nZEDb_data/nZEDb/app/tests/cases/models/empty

0
nZEDb_data/nZEDb/app/tests/functional/empty

0
nZEDb_data/nZEDb/app/tests/integration/empty

0
nZEDb_data/nZEDb/app/tests/mocks/empty

110
nZEDb_data/nZEDb/app/views/_errors/development.html.php

@ -0,0 +1,110 @@
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2015, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
use lithium\analysis\Debugger;
use lithium\analysis\Inspector;
$exception = $info['exception'];
$replace = array('&lt;?php', '?&gt;', '<code>', '</code>', "\n");
$context = 5;
/**
* Set Lithium-esque colors for syntax highlighing.
*/
ini_set('highlight.string', '#4DDB4A');
ini_set('highlight.comment', '#D42AAE');
ini_set('highlight.keyword', '#D42AAE');
ini_set('highlight.default', '#3C96FF');
ini_set('highlight.htm', '#FFFFFF');
$stack = Debugger::trace(array('format' => 'array', 'trace' => $exception->getTrace()));
array_unshift($stack, array(
'functionRef' => '[exception]',
'file' => $exception->getFile(),
'line' => $exception->getLine()
));
?>
<h3>Exception</h3>
<div class="lithium-exception-class">
<?=get_class($exception);?>
<?php if ($code = $exception->getCode()): ?>
<span class="lithium-exception-code">(code <?=$code; ?>)</span>
<?php endif ?>
</div>
<div class="lithium-exception-message">
<pre><code><?=$exception->getMessage(); ?></code></pre>
</div>
<h3 id="source">Source</h3>
<div id="code"></div>
<h3>Stack Trace</h3>
<div class="lithium-stack-trace">
<ol>
<?php foreach ($stack as $id => $frame): ?>
<?php
$location = "{$frame['file']}: {$frame['line']}";
$lines = range($frame['line'] - $context, $frame['line'] + $context);
$code = Inspector::lines($frame['file'], $lines);
?>
<li>
<tt><a href="#source" id="<?=$id; ?>" class="display-source-excerpt">
<?=$frame['functionRef']; ?>
</a></tt>
<div id="code-<?=$id; ?>" style="display: none;">
<div class="lithium-exception-location">
<?=$location; ?>
</div>
<div class="lithium-code-dump">
<pre><code><?php
foreach ($code as $num => $content):
$numPad = str_pad($num, 3, ' ');
$content = str_ireplace(array('<?php', '?>'), '', $content);
$content = highlight_string("<?php {$numPad}{$content} ?>", true);
$content = str_replace($replace, '', $content);
if ($frame['line'] === $num):
?><span class="code-highlight"><?php
endif;?><?php echo "{$content}\n"; ?><?php
if ($frame['line'] === $num):
?></span><?php
endif;
endforeach;
?></code></pre>
</div>
</div>
</li>
<?php endforeach; ?>
</ol>
</div>
<script type="text/javascript">
window.onload = function() {
var $ = function() { return document.getElementById.apply(document, arguments); };
var links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++) {
if (links[i].className.indexOf('display-source-excerpt') >= 0) {
links[i].onclick = function() {
$('code').innerHTML = $('code-' + this.id).innerHTML;
}
}
}
$('code').innerHTML = $('code-0').innerHTML;
}
</script>

0
nZEDb_data/nZEDb/app/views/elements/empty

1
nZEDb_data/nZEDb/app/views/hello_world/index.html.php

@ -0,0 +1 @@
Hello World!

54
nZEDb_data/nZEDb/app/views/layouts/default.html.php

@ -0,0 +1,54 @@
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2015, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
?>
<!doctype html>
<html>
<head>
<?php echo $this->html->charset();?>
<title>Application &gt; <?php echo $this->title(); ?></title>
<?php echo $this->html->style(array('bootstrap.min', 'lithified')); ?>
<?php echo $this->scripts(); ?>
<?php echo $this->styles(); ?>
<?php echo $this->html->link('Icon', null, array('type' => 'icon')); ?>
</head>
<body class="lithified">
<div class="container-narrow">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li>
<a href="http://li3.me/docs/manual/quickstart">Quickstart</a>
</li>
<li>
<a href="http://li3.me/docs/manual">Manual</a>
</li>
<li>
<a href="http://li3.me/docs/lithium">API</a>
</li>
<li>
<a href="http://li3.me/">More</a>
</li>
</ul>
<a href="http://li3.me/"><h3>&#10177;</h3></a>
</div>
<hr>
<div class="content">
<?php echo $this->content(); ?>
</div>
<hr>
<div class="footer">
<p>&copy; Union Of RAD <?php echo date('Y') ?></p>
</div>
</div>
</body>
</html>

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save