Showing preview only (437K chars total). Download the full file or copy to clipboard to get everything.
Repository: bcosca/fatfree-core
Branch: master
Commit: 6872dcfb0906
Files: 41
Total size: 420.6 KB
Directory structure:
gitextract_46rrm02n/
├── .github/
│ └── FUNDING.yml
├── CHANGELOG.md
├── COPYING
├── README.md
├── audit.php
├── auth.php
├── base.php
├── basket.php
├── bcrypt.php
├── cli/
│ └── ws.php
├── code.css
├── composer.json
├── db/
│ ├── cursor.php
│ ├── jig/
│ │ ├── mapper.php
│ │ └── session.php
│ ├── jig.php
│ ├── mongo/
│ │ ├── mapper.php
│ │ └── session.php
│ ├── mongo.php
│ ├── sql/
│ │ ├── mapper.php
│ │ └── session.php
│ └── sql.php
├── f3.php
├── image.php
├── log.php
├── magic.php
├── markdown.php
├── matrix.php
├── session.php
├── sessionadapter.php
├── smtp.php
├── template.php
├── test.php
├── utf.php
├── web/
│ ├── geo.php
│ ├── google/
│ │ ├── recaptcha.php
│ │ └── staticmap.php
│ ├── oauth2.php
│ ├── openid.php
│ └── pingback.php
└── web.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
github: ikkez
buy_me_a_coffee: ikkez
================================================
FILE: CHANGELOG.md
================================================
CHANGELOG
3.9.2 (02.12.2025)
---
feat, Audit: Added bot/AI detection, #401
fix: php 8.5 compatibility
3.9.1 (09.08.2025)
---
* fix: return type hint for unserialize, closes [#391](https://github.com/f3-factory/fatfree-core/issues/391)
* feat: Web->slug, specify the separator, [#397](https://github.com/f3-factory/fatfree-core/issues/397)
* feat: added hive pull method, [#395](https://github.com/f3-factory/fatfree-core/issues/395)
* fix: throw exceptions instead of deprecated USER_ERROR [#393](https://github.com/f3-factory/fatfree-core/issues/393)
* fix: error thrown by `read()` for cache, [#392](https://github.com/f3-factory/fatfree-core/issues/392)
* fix: failsafe when passing null to explode parameter
3.9.0 (29.12.2024)
---
* feat [#377], DB\SQL: check TABLE_SCHEMA in fields introspection query
* feat [#379]: Added `REROUTE_TRAILING_SLASH` to optionally disable rerouting
* feat [#380], Audit: Adding new mac address validation
* fix [#372], Audit: `isprivate()`, `FILTER_FLAG_NO_PRIV_RANGE` usage
* fix [#378]: websocket handlers call
* fix: php 8.4 session handler compatibility
* fix: various php 8.4 warnings
* fix [#382]: PHP 8.4 `E_STRICT` deprecation fix
* fix [#371]: trim string based routes handler
* fix [bcosca/fatfree#1285]: multi-line template tags
* fix [#375]: PHP 8.4 Fixes for implicit nullability deprecation
* fix [#374]: http_build_query usage deprecation fix
* fix [#369]: unify key string replacement for cache getter/setter
3.8.2 (24.07.2023)
---
* feat, Base->format: optimize international date formatting for php8.1+
* fix, Base->format: keep php7 compatibility in date formatter [#360](https://github.com/f3-factory/fatfree-core/issues/360)
* fix, Markdown: unicode chars not captured correctly for headline slugs [#363](https://github.com/f3-factory/fatfree-core/issues/363)
* fix, Preview->resolve: PHP8+ error, undefined variable $hash [#359](https://github.com/f3-factory/fatfree-core/issues/359)
* fix, Base->clean: PHP8+ error, strip_tags with null value usage
3.8.1 (05.11.2022)
---
* fix: CORS preflight request fails to find route for ajax-only definitions [bcosca/fatfree#1242](https://github.com/bcosca/fatfree/issues/1242)
* fix: add realpath to captcha font filepath, [#314](https://github.com/bcosca/fatfree-core/issues/314)
* fix: case-insensitive custom tag matching [#353](https://github.com/bcosca/fatfree-core/issues/353)
* fix: php8 error suppression on invalid locale constant access [bcosca/fatfree#1259](https://github.com/bcosca/fatfree/issues/1259)
* fix: iteration over inaccessible object properties, fixes [#350](https://github.com/bcosca/fatfree-core/issues/350)
* feat: let jig handle utf8 issues more gracefully [#352](https://github.com/bcosca/fatfree-core/issues/352)
* fix: BC issue for pre php74
* fix: ensure template->parse does render zero text-node, [#354](https://github.com/bcosca/fatfree-core/issues/354)
* fix: DB\SQL\Mapper: allow to pass an empty array as $filter, fixes [bcosca/fatfree#1257](https://github.com/bcosca/fatfree/issues/1257)
* fix: adhoc null fields in Twig are executed as callable, [#310](https://github.com/bcosca/fatfree-core/issues/310)
* fix: ensure merged default PARAMS are properly encoded when building alias, [#345](https://github.com/bcosca/fatfree-core/issues/345)
* fix: Added CORS defaults that are not initialized
* fix: SQL cache schema for $fields
* fix: adhoc field with null value php81 issue, [#339](https://github.com/bcosca/fatfree-core/issues/339)
* fix: check against correct identity flags when using IDENTITY_INSERT for sql server
* added missing file location in error handler [bcosca/fatfree#1255](https://github.com/bcosca/fatfree/issues/1255)
* Web->request, add option to adjust accept-encoding in curl engine [#355](https://github.com/bcosca/fatfree-core/issues/355)
3.8.0 (15 Feb 2022)
---
* Feat: allow access to previous session data in cache-based session handler
* Feat: pass session information to onSuspect Session handler
* Fix: PHP 8.1 compatibility fixes [#332](https://github.com/bcosca/fatfree-core/issues/332) [#333](https://github.com/bcosca/fatfree-core/issues/333)
* Fix: check for critical schemes in url validation
* Fix: plural format syntax with empty param, [#325](https://github.com/bcosca/fatfree-core/issues/325)
* Fix: DB mapper not able to fetch field scheme in sqlite views
* Fix: capitalization of array key X-Http-Method-Override in headers [#327](https://github.com/bcosca/fatfree-core/issues/327)
* Fix SMTP: allow RFC2047 encoded words in From/To/Cc/Bcc headers
* Fix: use correct ternary value, [#323](https://github.com/bcosca/fatfree-core/issues/323)
* Fix: trace not present in error handler when in CLI mode and !DEBUG, [#323](https://github.com/bcosca/fatfree-core/issues/323)
3.7.3 (13 Dec 2020)
---
* NEW: added auto_increment detection, [bcosca/fatfree#1192](https://github.com/bcosca/fatfree/issues/1192), [bcosca/fatfree#1093](https://github.com/bcosca/fatfree/issues/1093), [bcosca/fatfree#1175](https://github.com/bcosca/fatfree/issues/1175), [#290](https://github.com/bcosca/fatfree-core/issues/290)
* added SMTP dialog error handling, [#317](https://github.com/bcosca/fatfree-core/issues/317)
* Fix: Check active transaction before rollback/commit (PHP8 issue)
* refactored increment/decrement operator to preceed variables
* added error output in CLI mode, [bcosca/fatfree#1185](https://github.com/bcosca/fatfree/issues/1185)
* Set PORT to 80 when SERVER_PORT is an empty string
* Fix: unescape dbname when extracting from dsn, [#316](https://github.com/bcosca/fatfree-core/issues/316)
* Fix: handling of PDO prepare() errors
* Fix: edge case in DB\SQL->schema(): PK not detected in PgSQL when the column is also a FK [bcosca/fatfree#1207](https://github.com/bcosca/fatfree/issues/1207)
* Fix: Escape literal hyphens in regex character classes, [bcosca/fatfree#1206](https://github.com/bcosca/fatfree/issues/1206)
* Fix: error highlighting
* Fix: pagination with order by on virtual fields
* Fixed a couple PHPDOC issues
3.7.2 (28 May 2020)
---
* CHANGED, View->sandbox: disable escaping when rendering as text/plain, [bcosca/fatfree#654](https://github.com/bcosca/fatfree/issues/654)
* update HTTP protocol checks, [bcosca/fatfree#1190](https://github.com/bcosca/fatfree/issues/1190)
* Base->clear: close vulnerability on variable compilation, [bcosca/fatfree#1191](https://github.com/bcosca/fatfree/issues/1191)
* DB\SQL\Mapper: fix empty ID after insert, [bcosca/fatfree#1175](https://github.com/bcosca/fatfree/issues/1175)
* DB\SQL\Mapper: fix using correct key variable for grouped sql pagination sets
* Fix return type of 'count' in Cursor->paginate(), [bcosca/fatfree#1187](https://github.com/bcosca/fatfree/issues/1187)
* Bug fix, Web->minify: fix minification of ES6 template literals, [bcosca/fatfree#1178](https://github.com/bcosca/fatfree/issues/1178)
* Bug fix, config: refactoring custom section parser regex, [bcosca/fatfree#1149](https://github.com/bcosca/fatfree/issues/1149)
* Bug fix: token resolve on non-alias reroute paths, [ref. 221f0c9](https://github.com/bcosca/fatfree-core/commit/221f0c930f8664565c9825faeb9ed9af0f7a01c8)
* Websocket: Improved event handler usage
* optimized internal get calls
* only use cached lexicon when a $ttl was given
* only use money_format up until php7.4, [bcosca/fatfree#1174](https://github.com/bcosca/fatfree/issues/1174)
3.7.1 (30. December 2019)
---
* Base->build: Add support for brace-enclosed route tokens
* Base->reroute, fix duplicate fragment issue on non-alias routes
* DB\SQL\Mapper: fix empty check for pkey when reloading after insert
* Web->minify: fix minification with multiple files, [bcosca/fatfree#1152](https://github.com/bcosca/fatfree/issues/1152), [#bcosca/fatfree#1169](https://github.com/bcosca/fatfree/issues/1169)
3.7.0 (26. November 2019)
---
* NEW: Matrix, added select and walk methods for array processing and validation tools
* NEW: Added configurable file locking via LOCK var
* NEW: json support for dictionary files
* NEW: $die parameter on ONREROUTE hook
* NEW: Added SameSite cookie support for php7.3+ (JAR.samesite), [bcosca/fatfree#1165](https://github.com/bcosca/fatfree/issues/1165)
* NEW, DB\SQL\Mapper: added updateAll method to batch-update multiple records at once
* CHANGED, DB\SQL\Mapper: Throw error on update/erase if the table has no primary key, [#285](https://github.com/bcosca/fatfree-core/issues/285)
* Cache, Redis: Added ability to set a Redis password, [#287](https://github.com/bcosca/fatfree-core/issues/287)
* DB\SQL\Session: make datatype of data column configurable, [bcosca/fatfree#1130](https://github.com/bcosca/fatfree/issues/1130)
* DB\SQL\Mapper: only add adhoc fields in count queries that are used for grouping
* DB\SQL\Mapper: fixed inserting an already loaded record again (duplicating), [bcosca/fatfree#1093](https://github.com/bcosca/fatfree/issues/1093)
* Magic (Mappers): fix isset check on existing properties
* SMTP: added support for Bounce mail recipient ("Sender" header)
* OAuth2: make query string encode type configurable, [#268](https://github.com/bcosca/fatfree-core/issues/268) [#269](https://github.com/bcosca/fatfree-core/issues/269)
* Web: Added more cyrillic letters to diacritics, [bcosca/fatfree#1158](https://github.com/bcosca/fatfree/issues/1158)
* Web: Fixed url string falsely detected as comment section [9ac8e615](https://github.com/bcosca/fatfree-core/commit/9ac8e615ccaf750b49497a3c86161331b24e637f)
* Web: added file inspection for mime-type detection, [#270](https://github.com/bcosca/fatfree-core/issues/270), [bcosca/fatfree#1138](https://github.com/bcosca/fatfree/issues/1138)
* WS: Fixed processing all queued data frames inside the buffer, [#277](https://github.com/bcosca/fatfree-core/issues/277)
* WS: Allow packet size override
* Markdown: Support mixed `strong` and `italic` elements, [#276](https://github.com/bcosca/fatfree-core/issues/276)
* Markdown: Keep spaces around `=` sign in ini code blocks
* Added route alias key name validation, [#243](https://github.com/bcosca/fatfree-core/issues/243)
* Added fragment argument to alias method, [#282](https://github.com/bcosca/fatfree-core/issues/282)
* Allow adding fragment to reroute, [#1156](https://github.com/bcosca/fatfree/issues/1156)
* Added additional HTTP status codes, [#283](https://github.com/bcosca/fatfree-core/issues/283)
* Added X-Forwarded-For IP to log entries, [bcosca/fatfree#1042](https://github.com/bcosca/fatfree/issues/1042)
* Bug fix: broken custom date/time formatting, [bcosca/fatfree#1147](https://github.com/bcosca/fatfree/issues/1147)
* Bug fix: duplicate UI path rendering edge-case in Views and minify, [bcosca/fatfree#1152](https://github.com/bcosca/fatfree/issues/1152)
* Bug fix: unicode chars in custom config section keys, [bcosca/fatfree#1149](https://github.com/bcosca/fatfree/issues/1149)
* Bug fix: ensure valid reroute path in location header, [bcosca/fatfree#1140](https://github.com/bcosca/fatfree/issues/1140)
* Bug fix: use dictionary path for lexicon caching-hash
* Bug fix, php7.3: number format ternary, [bcosca/fatfree#1142](https://github.com/bcosca/fatfree/issues/1142)
* fix PHPdoc and variable inspection, [bcosca/fatfree#865](https://github.com/bcosca/fatfree/issues/865), [bcosca/fatfree#1128](https://github.com/bcosca/fatfree/issues/1128)
3.6.5 (24 December 2018)
---
* NEW: Log, added timestamp to each line
* NEW: Auth, added support for custom compare method, [#116](https://github.com/bcosca/fatfree-core/issues/116)
* NEW: cache tag support for mongo & jig mapper, ref [#166](https://github.com/bcosca/fatfree-core/issues/116)
* NEW: Allow PHP functions as template token filters
* Web: Fix double redirect bug when running cURL with open_basedir disabled
* Web: Cope with responses from HTTP/2 servers
* Web->filler: remove very first space, when $std is false
* Web\OAuth2: Cope with HTTP/2 responses
* Web\OAuth2: take Content-Type header into account for json decoding, [#250](https://github.com/bcosca/fatfree-core/issues/250) [#251](https://github.com/bcosca/fatfree-core/issues/251)
* Web\OAuth2: fixed empty results on some endpoints [#250](https://github.com/bcosca/fatfree-core/issues/250)
* DB\SQL\Mapper: optimize mapper->count memory usage
* DB\SQL\Mapper: New table alias operator
* DB\SQL\Mapper: fix count() performance on non-grouped result sets, [bcosca/fatfree#1114](https://github.com/bcosca/fatfree/issues/1114)
* DB\SQL: Support for CTE in postgreSQL, [bcosca/fatfree#1107](https://github.com/bcosca/fatfree/issues/1107), [bcosca/fatfree#1116](https://github.com/bcosca/fatfree/issues/1116), [bcosca/fatfree#1021](https://github.com/bcosca/fatfree/issues/1021)
* DB\SQL->log: Remove extraneous whitespace
* DB\SQL: Added ability to add inline comments per SQL query
* CLI\WS, Refactoring: Streamline socket server
* CLI\WS: Add option for dropping query in OAuth2 URI
* CLI\WS: Add URL-safe base64 encoding
* CLI\WS: Detect errors in returned JSON values
* CLI\WS: Added support for Sec-WebSocket-Protocol header
* Matrix->calendar: Allow unix timestamp as date argument
* Basket: Access basket item by _id [#260](https://github.com/bcosca/fatfree-core/issues/260)
* SMTP: Added TLS 1.2 support [bcosca/fatfree#1115](https://github.com/bcosca/fatfree/issues/1115)
* SMTP->send: Respect $log argument
* Base->cast: recognize binary and octal numbers in config
* Base->cast: add awareness of hexadecimal literals
* Base->abort: Remove unnecessary Content-Encoding header
* Base->abort: Ensure headers have not been flushed
* Base->format: Differentiate between long- and full-date (with localized weekday) formats
* Base->format: Conform with intl extension's number output
* Enable route handler to override Access-Control headers in response to OPTIONS request, [#257](https://github.com/bcosca/fatfree-core/issues/257)
* Augment filters with a var_export function
* Bug fix php7.3: Fix template parse regex to be compatible with strict PCRE2 rules for hyphen placement in a character class
* Bug fix, Cache->set: update creation time when updating existing cache entries
* Bug fix: incorrect ICU date/time formatting
* Bug fix, Jig: lazy write on empty data
* Bug fix: Method uppercase to avoid route failure [#252](https://github.com/bcosca/fatfree-core/issues/252)
* Fixed error description when (PSR-11) `CONTAINER` fails to resolve a class [#253](https://github.com/bcosca/fatfree-core/issues/253)
* Mitigate CSRF predictability/vulnerability
* Expose Mapper->factory() method
3.6.4 (19 April 2018)
---
* NEW: Added Dependency Injection support with CONTAINER variable [#221](https://github.com/bcosca/fatfree-core/issues/221)
* NEW: configurable LOGGABLE error codes [#1091](https://github.com/bcosca/fatfree/issues/1091#issuecomment-364674701)
* NEW: JAR.lifetime option, [#178](https://github.com/bcosca/fatfree-core/issues/178)
* Template: reduced Prefab calls
* Template: optimized reflection for better derivative support, [bcosca/fatfree#1088](https://github.com/bcosca/fatfree/issues/1088)
* Template: optimized parsing for template attributes and tokens
* DB\Mongo: fixed logging with mongodb extention
* DB\Jig: added lazy-loading [#7e1cd9b9b89](https://github.com/bcosca/fatfree-core/commit/7e1cd9b9b89c4175d0f6b86ced9d9bd49c04ac39)
* DB\Jig\Mapper: Added group feature, bcosca/fatfree#616
* DB\SQL\Mapper: fix PostgreSQL RETURNING ID when no pkey is available, [bcosca/fatfree#1069](https://github.com/bcosca/fatfree/issues/1069), [#230](https://github.com/bcosca/fatfree-core/issues/230)
* DB\SQL\Mapper: disable order clause auto-quoting when it's already been quoted
* Web->location: add failsafe for geoip_region_name_by_code() [#GB:Bxyn9xn9AgAJ](https://groups.google.com/d/msg/f3-framework/APau4wnwNzE/Bxyn9xn9AgAJ)
* Web->request: Added proxy support [#e936361b](https://github.com/bcosca/fatfree-core/commit/e936361bc03010c4c7c38a396562e5e96a8a100d)
* Web->mime: Added JFIF format
* Markdown: handle line breaks in paragraph blocks, [bcosca/fatfree#1100](https://github.com/bcosca/fatfree/issues/1100)
* config: reduced cast calls on parsing config sections
* Patch empty SERVER_NAME [bcosca/fatfree#1084](https://github.com/bcosca/fatfree/issues/1084)
* Bugfix: unreliable request headers in Web->request() response [bcosca/fatfree#1092](https://github.com/bcosca/fatfree/issues/1092)
* Fixed, View->render: utilizing multiple UI paths, [bcosca/fatfree#1083](https://github.com/bcosca/fatfree/issues/1083)
* Fixed URL parsing with PHP 5.4 [#247](https://github.com/bcosca/fatfree-core/issues/247)
* Fixed PHP 7.2 warnings when session is active prematurely, [#238](https://github.com/bcosca/fatfree-core/issues/238)
* Fixed setcookie $expire variable type [#240](https://github.com/bcosca/fatfree-core/issues/240)
* Fixed expiration time when updating an existing cookie
3.6.3 (31 December 2017)
---
* PHP7 fix: remove deprecated (unset) cast
* Web->request: restricted follow_location to 3XX responses only
* CLI mode: refactored arguments parsing
* CLI mode: fixed query string encoding
* SMTP: Refactor parsing of attachments
* SMTP: clean-up mail headers for multipart messages, [#1065](https://github.com/bcosca/fatfree/issues/1065)
* config: fixed performance issues on parsing config files
* config: cast command parameters in config entries to php type & constant, [#1030](https://github.com/bcosca/fatfree/issues/1030)
* config: reduced registry calls
* config: skip hive escaping when resolving dynamic config vars, [#1030](https://github.com/bcosca/fatfree/issues/1030)
* Bug fix: Incorrect cookie lifetime computation, [#1070](https://github.com/bcosca/fatfree/issues/1070), [#1016](https://github.com/bcosca/fatfree/issues/1016)
* DB\SQL\Mapper: use RETURNING option instead of a sequence query to get lastInsertId in PostgreSQL, [#1069](https://github.com/bcosca/fatfree/issues/1069), [#230](https://github.com/bcosca/fatfree-core/issues/230)
* DB\SQL\Session: check if _agent is too long for SQL based sessions [#236](https://github.com/bcosca/fatfree-core/issues/236)
* DB\SQL\Session: fix Session handler table creation issue on SQL Server, [#899](https://github.com/bcosca/fatfree/issues/899)
* DB\SQL: fix oracle db issue with empty error variable, [#1072](https://github.com/bcosca/fatfree/issues/1072)
* DB\SQL\Mapper: fix sorting issues on SQL Server, [#1052](https://github.com/bcosca/fatfree/issues/1052) [#225](https://github.com/bcosca/fatfree-core/issues/225)
* Prevent directory traversal attacks on filesystem based cache [#1073](https://github.com/bcosca/fatfree/issues/1073)
* Bug fix, Template: PHP constants used in include with attribute, [#983](https://github.com/bcosca/fatfree/issues/983)
* Bug fix, Template: Numeric value in expression alters PHP_EOL context
* Template: use existing linefeed instead of PHP_EOL, [#1048](https://github.com/bcosca/fatfree/issues/1048)
* Template: make newline interpolation handling configurable [#223](https://github.com/bcosca/fatfree-core/issues/223)
* Template: add beforerender to Preview
* fix custom FORMATS without modifiers
* Cache: Refactor Cache->reset for XCache
* Cache: loosen reset cache key pattern, [#1041](https://github.com/bcosca/fatfree/issues/1041)
* XCache: suffix reset only works if xcache.admin.enable_auth is disabled
* Added HTTP 103 as recently approved by the IETF
* LDAP changes to for AD flexibility [#227](https://github.com/bcosca/fatfree-core/issues/227)
* Hide debug trace from ajax errors when DEBUG=0 [#1071](https://github.com/bcosca/fatfree/issues/1071)
* fix View->render using potentially wrong cache entry
3.6.2 (26 June 2017)
---
* Return a status code > 0 when dying on error [#220](https://github.com/bcosca/fatfree-core/issues/220)
* fix SMTP line width [#215](https://github.com/bcosca/fatfree-core/issues/215)
* Allow using a custom field for ldap user id checking [#217](https://github.com/bcosca/fatfree-core/issues/217)
* NEW: DB\SQL->exists: generic method to check if SQL table exists
* Pass handler to route handler and hooks [#1035](https://github.com/bcosca/fatfree/issues/1035)
* pass carriage return of multiline dictionary keys
* Better Web->slug customization
* fix incorrect header issue [#211](https://github.com/bcosca/fatfree-core/issues/211)
* fix schema issue on databases with case-sensitive collation, fixes [#209](https://github.com/bcosca/fatfree-core/issues/209)
* Add filter for deriving C-locale equivalent of a number
* Bug fix: @LANGUAGE remains unchanged after override
* abort: added Header pre-check
* Assemble URL after ONREROUTE
* Add reroute argument to skip script termination
* Invoke ONREROUTE after headers are sent
* SQLite switch to backtick as quote
* Bug fix: Incorrect timing in SQL query logs
* DB\SQL\Mapper: Cast return value of count to integer
* Patched $_SERVER['REQUEST_URI'] to ensure it contains a relative URI
* Tweak debug verbosity
* fix php carriage return issue in preview->build [#205](https://github.com/bcosca/fatfree-core/pull/205)
* fixed template string resolution [#205](https://github.com/bcosca/fatfree-core/pull/205)
* Fixed unexpected default seed on CACHE set [#1028](https://github.com/bcosca/fatfree/issues/1028)
* DB\SQL\Mapper: Optimized field escaping on options
* Optimize template conversion to PHP file
3.6.1 (2 April 2017)
---
* NEW: Recaptcha plugin [#194](https://github.com/bcosca/fatfree-core/pull/194)
* NEW: MB variable for detecting multibyte support
* NEW: DB\SQL: Cache parsed schema for the TTL duration
* NEW: quick erase flag on Jig/Mongo/SQL mappers [#193](https://github.com/bcosca/fatfree-core/pull/193)
* NEW: Allow OPTIONS method to return a response body [#171](https://github.com/bcosca/fatfree-core/pull/171)
* NEW: Add support for Memcached (bcosca/fatfree#997)
* NEW: Rudimentary preload resource (HTTP2 server) support via template push()
* NEW: Add support for new MongoDB driver [#177](https://github.com/bcosca/fatfree-core/pull/177)
* Changed: template filter are all lowercase now
* Changed: Fix template lookup inconsistency: removed base dir from UI on render
* Changed: count() method now has an options argument [#192](https://github.com/bcosca/fatfree-core/pull/192)
* Changed: SMTP, Spit out error message if any
* \DB\SQL\Mapper: refactored row count strategy
* DB\SQL\Mapper: Allow non-scalar values to be assigned as mapper property
* DB\SQL::PARAM_FLOAT: remove cast to float (#106 and bcosca/fatfree#984) (#191)
* DB\SQL\mapper->erase: allow empty string
* DB\SQL\mapper->insert: fields reset after successful INSERT
* Add option to debounce Cursor->paginate subset [#195](https://github.com/bcosca/fatfree-core/pull/195)
* View: Don't delete sandboxed variables (#198)
* Preview: Optimize compilation of template expressions
* Preview: Use shorthand tag for direct rendering
* Preview->resolve(): new tweak to allow template persistence as option
* Web: Expose diacritics translation table
* SMTP: Enable logging of message body only when $log argument is 'verbose'
* SMTP: Convert headers to camelcase for consistency
* make cache seed more flexible, #164
* Improve trace details for DEBUG>2
* Enable config() to read from an array of input files
* Improved alias and reroute regex
* Make camelCase and snakeCase Unicode-aware
* format: Provision for optional whitespaces
* Break APCu-BC dependence
* Old PHP 5.3 cleanup
* Debug log must include HTTP query
* Recognize X-Forwarded-Port header (bcosca/fatfree#1002)
* Avoid use of deprecated mcrypt module
* Return only the client's IP when using the `X-Forwarded-For` header to deduce an IP address
* Remove orphan mutex locks on termination (#157)
* Use 80 as default port number to avoid issues when `$_SERVER['SERVER_PORT']` is not existing
* fread replaced with readfile() for simple send() usecase
* Bug fix: request URI with multiple leading slashes, #203
* Bug fix: Query generates wrong adhoc field value
* Bug fix: SMTP stream context issue #200
* Bug fix: child pseudo class selector in minify, bcosca/fatfree#1008
* Bug fix: "Undefined index: CLI" error (#197)
* Bug fix: cast Cache-Control expire time to int, bcosca/fatfree#1004
* Bug fix: Avoid issuance of multiple Content-Type headers for nested templates
* Bug fix: wildcard token issue with digits (bcosca/fatfree#996)
* Bug fix: afterupdate ignored when row does not change
* Bug fix: session handler read() method for PHP7 (need strict string) #184 #185
* Bug fix: reroute mocking in CLI mode (#183)
* Bug fix: Reroute authoritative relative references (#181)
* Bug fix: locales order and charset hyphen
* Bug fix: base stripped twice in router (#176)
3.6.0 (19 November 2016)
---
* NEW: [cli] request type
* NEW: console-friendly CLI mode
* NEW: lexicon caching
* NEW: Silent operator skips startup error check (#125)
* NEW: DB\SQL->trans()
* NEW: custom config section parser, i.e. [conf > Foo::bar]
* NEW: support for cache tags in SQL
* NEW: custom FORMATS
* NEW: Mongo mapper fields whitelist
* NEW: WebSocket server
* NEW: Base->extend method (#158)
* NEW: Implement framework variable caching via config, i.e. FOO = "bar" | 3600
* NEW: Lightweight OAuth2 client
* NEW: SEED variable, configurable app-specific hashing prefix (#149, bcosca/fatfree#951, bcosca/fatfree#884, bcosca/fatfree#629)
* NEW: CLI variable
* NEW: Web->send, specify custom filename (#124)
* NEW: Web->send, added flushing flag (#131)
* NEW: Indexed route wildcards, now exposed in PARAMS['*']
* Changed: PHP 5.4 is now the minimum version requirement
* Changed: Prevent database wrappers from being cloned
* Changed: Router works on PATH instead of URI (#126) NB: PARAMS.0 no longer contains the query string
* Changed: Removed ALIASES autobuilding (#118)
* Changed: Route wildcards match empty strings (#119)
* Changed: Disable default debug highlighting, HIGHLIGHT is false now
* General PHP 5.4 optimizations
* Optimized config parsing
* Optimized Base->recursive
* Optimized header extraction
* Optimized cache/expire headers
* Optimized session_start behaviour (bcosca/fatfree#673)
* Optimized reroute regex
* Tweaked cookie removal
* Better route precedence order
* Performance tweak: reduced cache calls
* Refactored lexicon (LOCALES) build-up, much faster now
* Added turkish locale bug workaround
* Geo->tzinfo Update to UTC
* Added Xcache reset (bcosca/fatfree#928)
* Redis cache: allow db name in dsn
* SMTP: Improve server emulation responses
* SMTP: Optimize transmission envelope
* SMTP: Implement mock transmission
* SMTP: Various bug fixes and feature improvements
* SMTP: quit on failed authentication
* Geo->weather: force metric units
* Base->until: Implement CLI interoperability
* Base->format: looser plural syntax
* Base->format: Force decimal as default number format
* Base->merge: Added $keep flag to save result to the hive key
* Base->reroute: Allow array as URL argument for aliasing
* Base->alias: Allow query string (or array) to be appended to alias
* Permit reroute to named routes with URL query segment
* Sync COOKIE global on set()
* Permit non-hive variables to use JS dot notation
* RFC2616: Use absolute URIs for Location header
* Matrix->calendar: Check if calendar extension is loaded
* Markdown: require start of line/whitespace for text processing (#136)
* DB\[SQL|Jig|Mongo]->log(FALSE) disables logging
* DB\SQL->exec: Added timestamp toggle to db log
* DB\SQL->schema: Remove unnecessary line terminators
* DB\SQL\Mapper: allow array filter with empty string
* DB\SQL\Mapper: optimized handling for key-less tables
* DB\SQL\Mapper: added float support (#106)
* DB\SQL\Session: increased default column sizes (#148, bcosca/fatfree#931, bcosca/fatfree#950)
* Web: Catch cURL errors
* Optimize Web->receive (bcosca/fatfree#930)
* Web->minify: fix arbitrary file download vulnerability
* Web->request: fix cache control max-age detection (bcosca/fatfree#908)
* Web->request: Add request headers & error message to return value (bcosca/fatfree#737)
* Web->request: Refactored response to HTTP request
* Web->send flush while sending big files
* Image->rgb: allow hex strings
* Image->captcha: Check if GD module supports TrueType
* Image->load: Return FALSE on load failure
* Image->resize: keep aspect ratio when only width or height was given
* Updated OpenID lib (bcosca/fatfree#965)
* Audit->card: add new mastercard "2" BIN range (bcosca/fatfree#954)
* Deprecated: Bcrypt class
* Preview->render: optimized detection to remove short open PHP tags and allow xml tags (#133)
* Display file and line number in exception handler (bcosca/fatfree#967)
* Added error reporting level to Base->error and ERROR.level (bcosca/fatfree#957)
* Added optional custom cache instance to Session (#141)
* CLI-aware mock()
* XFRAME and PACKAGE can be switched off now (#128)
* Bug fix: wrong time calculation on memcache reset (#170)
* Bug fix: encode CLI parameters
* Bug fix: Close connection on abort explicitly (#162)
* Bug fix: Image->identicon, Avoid double-size sprite rotation (and possible segfault)
* Bug fix: Image->render and Image->dump, removed unnecessary 2nd argument (#146)
* Bug fix: Magic->offsetset, access property as array element (#147)
* Bug fix: multi-line custom template tag parsing (bcosca/fatfree#935)
* Bug fix: cache headers on errors (bcosca/fatfree#885)
* Bug fix: Web, deprecated CURLOPT_SSL_VERIFYHOST in curl
* Bug fix: Web, Invalid user error constant (bcosca/fatfree#962)
* Bug fix: Web->request, redirections for domain-less location (#135)
* Bug fix: DB\SQL\Mapper, reset changed flag after update (#142, #152)
* Bug fix: DB\SQL\Mapper, fix changed flag when using assignment operator #143 #150 #151
* Bug fix: DB\SQL\Mapper, revival of the HAVING clause
* Bug fix: DB\SQL\Mapper, pgsql with non-integer primary keys (bcosca/fatfree#916)
* Bug fix: DB\SQL\Session, quote table name (bcosca/fatfree#977)
* Bug fix: snakeCase returns word starting with underscore (bcosca/fatfree#927)
* Bug fix: mock does not populate PATH variable
* Bug fix: Geo->weather API key (#129)
* Bug fix: Incorrect compilation of array element with zero index
* Bug fix: Compilation of array construct is incorrect
* Bug fix: Trailing slash redirection on UTF-8 paths (#121)
3.5.1 (31 December 2015)
---
* NEW: ttl attribute in <include> template tag
* NEW: allow anonymous function for template filter
* NEW: format modifier for international and custom currency symbol
* NEW: Image->data() returns image resource
* NEW: extract() get prefixed array keys from an assoc array
* NEW: Optimized and faster Template parser with full support for HTML5 empty tags
* NEW: Added support for {@token} encapsulation syntax in routes definition
* NEW: DB\SQL->exec(), automatically shift to 1-based query arguments
* NEW: abort() flush output
* Added referenced value to devoid()
* Template token filters are now resolved within Preview->token()
* Web->_curl: restrict redirections to HTTP
* Web->minify(), skip importing of external files
* Improved session and error handling in until()
* Get the error trace array with the new $format parameter
* Better support for unicode URLs
* Optimized TZ detection with date_default_timezone_get()
* format() Provide default decimal places
* Optimize code: remove redundant TTL checks
* Optimized timeout handling in Web->request()
* Improved PHPDoc hints
* Added missing russian DIACRITICS letters
* DB\Cursor: allow child implementation of reset()
* DB\Cursor: Copyfrom now does an internal call to set()
* DB\SQL: Provide the ability to disable SQL logging
* DB\SQL: improved query analysis to trigger fetchAll
* DB\SQL\Mapper: added support for binary table columns
* SQL,JIG,MONGO,CACHE Session handlers refactored and optimized
* SMTP Refactoring and optimization
* Bug fix: SMTP, Align quoted_printable_encode() with SMTP specs (dot-stuffing)
* Bug fix: SMTP, Send buffered optional headers to output
* Bug fix: SMTP, Content-Transfer-Encoding for non-TLS connections
* Bug fix: SMTP, Single attachment error
* Bug fix: Cursor->load not always mapping to first record
* Bug fix: dry SQL mapper should not trigger 'load'
* Bug fix: Code highlighting on empty text
* Bug fix: Image->resize, round dimensions instead of cast
* Bug fix: whitespace handling in $f3->compile()
* Bug fix: TTL of `View` and `Preview` (`Template`)
* Bug fix: token filter regex
* Bug fix: Template, empty attributes
* Bug fix: Preview->build() greedy regex
* Bug fix: Web->minify() single-line comment on last line
* Bug fix: Web->request(), follow_location with cURL and open_basedir
* Bug fix: Web->send() Single quotes around filename not interpreted correctly by some browsers
3.5.0 (2 June 2015)
---
* NEW: until() method for long polling
* NEW: abort() to disconnect HTTP client (and continue execution)
* NEW: SQL Mapper->required() returns TRUE if field is not nullable
* NEW: PREMAP variable for allowing prefixes to handlers named after HTTP verbs
* NEW: [configs] section to allow config includes
* NEW: Test->passed() returns TRUE if no test failed
* NEW: SQL mapper changed() function
* NEW: fatfree-core composer support
* NEW: constants() method to expose constants
* NEW: Preview->filter() for configurable token filters
* NEW: CORS variable for Cross-Origin Resource Sharing support, #731
* Change in behavior: Switch to htmlspecialchars for escaping
* Change in behavior: No movement in cursor position after erase(), #797
* Change in behavior: ERROR.trace is a multiline string now
* Change in behavior: Strict token recognition in <include> href attribute
* Router fix: loose method search
* Better route precedence order, #12
* Preserve contents of ROUTES, #723
* Alias: allow array of parameters
* Improvements on reroute method
* Fix for custom Jig session files
* Audit: better mobile detection
* Audit: add argument to test string as browser agent
* DB mappers: abort insert/update/erase from hooks, #684
* DB mappers: Allow array inputs in copyfrom()
* Cache,SQL,Jig,Mongo Session: custom callback for suspect sessions
* Fix for unexpected HIVE values when defining an empty HIVE array
* SQL mapper: check for results from CALL and EXEC queries, #771
* SQL mapper: consider SQL schema prefix, #820
* SQL mapper: write to log before execution to
enable tracking of PDOStatement error
* Add SQL Mapper->table() to return table name
* Allow override of the schema in SQL Mapper->schema()
* Improvement: Keep JIG table as reference, #758
* Expand regex to include whitespaces in SQL DB dsn, #817
* View: Removed reserved variables $fw and $implicit
* Add missing newlines after template expansion
* Web->receive: fix for complex field names, #806
* Web: Improvements in socket engine
* Web: customizable user_agent for all engines, #822
* SMTP: Provision for Content-ID in attachments
* Image + minify: allow absolute paths
* Promote framework error to E_USER_ERROR
* Geo->weather switch to OpenWeather
* Expose mask() and grab() methods for routing
* Expose trace() method to expose the debug backtrace
* Implement recursion strategy using IteratorAggregate, #714
* Exempt whitespace between % and succeeding operator from being minified, #773
* Optimized error detection and ONERROR handler, fatfree-core#18
* Tweak error log output
* Optimized If-Modified-Since cache header usage
* Improved APCu compatibility, #724
* Bug fix: Web::send fails on filename with spaces, #810
* Bug fix: overwrite limit in findone()
* Bug fix: locale-specific edge cases affecting SQL schema, #772
* Bug fix: Newline stripping in config()
* Bug fix: bracket delimited identifier for sybase and dblib driver
* Bug fix: Mongo mapper collection->count driver compatibility
* Bug fix: SQL Mapper->set() forces adhoc value if already defined
* Bug fix: Mapper ignores HAVING clause
* Bug fix: Constructor invocation in call()
* Bug fix: Wrong element returned by ajax/sync request
* Bug fix: handling of non-consecutive compound key members
* Bug fix: Virtual fields not retrieved when group option is present, #757
* Bug fix: group option generates incorrect SQL query, #757
* Bug fix: ONERROR does not receive PARAMS on fatal error
3.4.0 (1 January 2015)
---
* NEW: [redirects] section
* NEW: Custom config sections
* NEW: User-defined AUTOLOAD function
* NEW: ONREROUTE variable
* NEW: Provision for in-memory Jig database (#727)
* Return run() result (#687)
* Pass result of run() to mock() (#687)
* Add port suffix to REALM variable
* New attribute in <include> tag to extend hive
* Adjust unit tests and clean up templates
* Expose header-related methods
* Web->request: allow content array
* Preserve contents of ROUTES (#723)
* Smart detection of PHP functions in template expressions
* Add afterrender() hook to View class
* Implement ArrayAccess and magic properties on hive
* Improvement on mocking of superglobals and request body
* Fix table creation for pgsql handled sessions
* Add QUERY to hive
* Exempt E_NOTICE from default error_reporting()
* Add method to build alias routes from template, fixes #693
* Fix dangerous caching of cookie values
* Fix multiple encoding in nested templates
* Fix node attribute parsing for empty/zero values
* Apply URL encoding on BASE to emulate v2 behavior (#123)
* Improve Base->map performance (#595)
* Add simple backtrace for fatal errors
* Count Cursor->load() results (#581)
* Add form field name to Web->receive() callback arguments
* Fix missing newlines after template expansion
* Fix overwrite of ENCODING variable
* limit & offset workaround for SQL Server, fixes #671
* SQL Mapper->find: GROUP BY SQL compliant statement
* Bug fix: Missing abstract method fields()
* Bug fix: Auto escaping does not work with mapper objects (#710)
* Bug fix: 'with' attribute in <include> tag raise error when no token
inside
* View rendering: optional Content-Type header
* Bug fix: Undefined variable: cache (#705)
* Bug fix: Routing does not work if project base path includes valid
special URI character (#704)
* Bug fix: Template hash collision (#702)
* Bug fix: Property visibility is incorrect (#697)
* Bug fix: Missing Allow header on HTTP 405 response
* Bug fix: Double quotes in lexicon files (#681)
* Bug fix: Space should not be mandatory in ICU pluralization format string
* Bug fix: Incorrect log entry when SQL query contains a question mark
* Bug fix: Error stack trace
* Bug fix: Cookie expiration (#665)
* Bug fix: OR operator (||) parsed incorrectly
* Bug fix: Routing treatment of * wildcard character
* Bug fix: Mapper copyfrom() method doesn't allow class/object callbacks
(#590)
* Bug fix: exists() creates elements/properties (#591)
* Bug fix: Wildcard in routing pattern consumes entire query string (#592)
* Bug fix: Workaround bug in latest MongoDB driver
* Bug fix: Default error handler silently fails for AJAX request with
DEBUG>0 (#599)
* Bug fix: Mocked BODY overwritten (#601)
* Bug fix: Undefined pkey (#607)
3.3.0 (8 August 2014)
---
* NEW: Attribute in <include> tag to extend hive
* NEW: Image overlay with transparency and alignment control
* NEW: Allow redirection of specified route patterns to a URL
* Bug fix: Missing AND operator in SQL Server schema query (Issue #576)
* Count Cursor->load() results (Feature request #581)
* Mapper copyfrom() method doesn't allow class/object callbacks (Issue #590)
* Bug fix: exists() creates elements/properties (Issue #591)
* Bug fix: Wildcard in routing pattern consumes entire query string
(Issue #592)
* Tweak Base->map performance (Issue #595)
* Bug fix: Default error handler silently fails for AJAX request with
DEBUG>0 (Issue #599)
* Bug fix: Mocked BODY overwritten (Issue #601)
* Bug fix: Undefined pkey (Issue #607)
* Bug fix: beforeupdate() position (Issue #633)
* Bug fix: exists() return value for cached keys
* Bug fix: Missing error code in UNLOAD handler
* Bug fix: OR operator (||) parsed incorrectly
* Add input name parameter to custom slug function
* Apply URL encoding on BASE to emulate v2 behavior (Issue #123)
* Reduce mapper update() iterations
* Bug fix: Routing treatment of * wildcard character
* SQL Mapper->find: GROUP BY SQL compliant statement
* Work around bug in latest MongoDB driver
* Work around probable race condition and optimize cache access
* View rendering: Optional Content-Type header
* Fix missing newlines after template expansion
* Add form field name to Web->receive() callback arguments
* Quick reference: add RAW variable
3.2.2 (19 March 2014)
---
* NEW: Locales set automatically (Feature request #522)
* NEW: Mapper dbtype()
* NEW: before- and after- triggers for all mappers
* NEW: Decode HTML5 entities if PHP>5.3 detected (Feature request #552)
* NEW: Send credentials only if AUTH is present in the SMTP extension
response (Feature request #545)
* NEW: BITMASK variable to allow ENT_COMPAT override
* NEW: Redis support for caching
* Enable SMTP feature detection
* Enable extended ICU custom date format (Feature request #555)
* Enable custom time ICU format
* Add option to turn off session table creation (Feature request #557)
* Enhanced template token rendering and custom filters (Feature request
#550)
* Avert multiple loads in DB-managed sessions (Feature request #558)
* Add EXEC to associative fetch
* Bug fix: Building template tokens breaks on inline OR condition (Issue
#573)
* Bug fix: SMTP->send does not use the $log parameter (Issue #571)
* Bug fix: Allow setting sqlsrv primary keys on insert (Issue #570)
* Bug fix: Generated query for obtaining table schema in sqlsrv incorrect
(Bug #565)
* Bug fix: SQL mapper flag set even when value has not changed (Bug #562)
* Bug fix: Add XFRAME config option (Feature request #546)
* Bug fix: Incorrect parsing of comments (Issue #541)
* Bug fix: Multiple Set-Cookie headers (Issue #533)
* Bug fix: Mapper is dry after save()
* Bug fix: Prevent infinite loop when error handler is triggered
(Issue #361)
* Bug fix: Mapper tweaks not passing primary keys as arguments
* Bug fix: Zero indexes in dot-notated arrays fail to compile
* Bug fix: Prevent GROUP clause double-escaping
* Bug fix: Regression of zlib compression bug
* Bug fix: Method copyto() does not include ad hoc fields
* Check existence of OpenID mode (Issue #529)
* Generate a 404 when a tokenized class doesn't exist
* Fix SQLite quotes (Issue #521)
* Bug fix: BASE is incorrect on Windows
3.2.1 (7 January 2014)
---
* NEW: EMOJI variable, UTF->translate(), UTF->emojify(), and UTF->strrev()
* Allow empty strings in config()
* Add support for turning off php://input buffering via RAW
(FALSE by default)
* Add Cursor->load() and Cursor->find() TTL support
* Support Web->receive() large file downloads via PUT
* ONERROR safety check
* Fix session CSRF cookie detection
* Framework object now passed to route handler contructors
* Allow override of DIACRITICS
* Various code optimizations
* Support log disabling (Issue #483)
* Implicit mapper load() on authentication
* Declare abstract methods for Cursor derivatives
* Support single-quoted HTML/XML attributes (Feature request #503)
* Relax property visibility of mappers and derivatives
* Deprecated: {{~ ~}} instructions and {{* *}} comments; Use {~ ~} and
{* *} instead
* Minor fix: Audit->ipv4() return value
* Bug fix: Backslashes in BASE not converted on Windows
* Bug fix: UTF->substr() with negative offset and specified length
* Bug fix: Replace named URL tokens on render()
* Bug fix: BASE is not empty when run from document root
* Bug fix: stringify() recursion
3.2.0 (18 December 2013)
---
* NEW: Automatic CSRF protection (with IP and User-Agent checks) for
sessions mapped to SQL-, Jig-, Mongo- and Cache-based backends
* NEW: Named routes
* NEW: PATH variable; returns the URL relative to BASE
* NEW: Image->captcha() color parameters
* NEW: Ability to access MongoCuror thru the cursor() method
* NEW: Mapper->fields() method returns array of field names
* NEW: Mapper onload(), oninsert(), onupdate(), and onerase() event
listeners/triggers
* NEW: Preview class (a lightweight template engine)
* NEW: rel() method derives path from URL relative to BASE; useful for
rerouting
* NEW: PREFIX variable for prepending a string to a dictionary term;
Enable support for prefixed dictionary arrays and .ini files (Feature
request #440)
* NEW: Google static map plugin
* NEW: devoid() method
* Introduce clean(); similar to scrub(), except that arg is passed by
value
* Use $ttl for cookie expiration (Issue #457)
* Fix needs_rehash() cost comparison
* Add pass-by-reference argument to exists() so if method returns TRUE,
a subsequent get() is unnecessary
* Improve MySQL support
* Move esc(), raw(), and dupe() to View class where they more
appropriately belong
* Allow user-defined fields in SQL mapper constructor (Feature request
#450)
* Re-implement the pre-3.0 template resolve() feature
* Remove redundant instances of session_commit()
* Add support for input filtering in Mapper->copyfrom()
* Prevent intrusive behavior of Mapper->copyfrom()
* Support multiple SQL primary keys
* Support custom tag attributes/inline tokens defined at runtime
(Feature request #438)
* Broader support for HTTP basic auth
* Prohibit Jig _id clear()
* Add support for detailed stringify() output
* Add base directory to UI path as fallback
* Support Test->expect() chaining
* Support __tostring() in stringify()
* Trigger error on invalid CAPTCHA length (Issue #458)
* Bug fix: exists() pass-by-reference argument returns incorrect value
* Bug fix: DB Exec does not return affected row if query contains a
sub-SELECT (Issue #437)
* Improve seed generator and add code for detecting of acceptable
limits in Image->captcha() (Feature request #460)
* Add decimal format ICU extension
* Bug fix: 404-reported URI contains HTTP query
* Bug fix: Data type detection in DB->schema()
* Bug fix: TZ initialization
* Bug fix: paginate() passes incorrect argument to count()
* Bug fix: Incorrect query when reloading after insert()
* Bug fix: SQL preg_match error in pdo_type matching (Issue #447)
* Bug fix: Missing merge() function (Issue #444)
* Bug fix: BASE misdefined in command line mode
* Bug fix: Stringifying hive may run infinite (Issue #436)
* Bug fix: Incomplete stringify() when DEBUG<3 (Issue #432)
* Bug fix: Redirection of basic auth (Issue #430)
* Bug fix: Filter only PHP code (including short tags) in templates
* Bug fix: Markdown paragraph parser does not convert PHP code blocks
properly
* Bug fix: identicon() colors on same keys are randomized
* Bug fix: quotekey() fails on aliased keys
* Bug fix: Missing _id in Jig->find() return value
* Bug fix: LANGUAGE/LOCALES handling
* Bug fix: Loose comparison in stringify()
3.1.2 (5 November 2013)
---
* Abandon .chm help format; Package API documentation in plain HTML;
(Launch lib/api/index.html in your browser)
* Deprecate BAIL in favor of HALT (default: TRUE)
* Revert to 3.1.0 autoload behavior; Add support for lowercase folder
names
* Allow Spring-style HTTP method overrides
* Add support for SQL Server-based sessions
* Capture full X-Forwarded-For header
* Add protection against malicious scripts; Extra check if file was really
uploaded
* Pass-thru page limit in return value of Cursor->paginate()
* Optimize code: Implement single-pass escaping
* Short circuit Jig->find() if source file is empty
* Bug fix: PHP globals passed by reference in hive() result (Issue #424)
* Bug fix: ZIP mime type incorrect behavior
* Bug fix: Jig->erase() filter malfunction
* Bug fix: Mongo->select() group
* Bug fix: Unknown bcrypt constant
3.1.1 (13 October 2013)
---
* NEW: Support OpenID attribute exchange
* NEW: BAIL variable enables/disables continuance of execution on non-fatal
errors
* Deprecate BAIL in favor of HALT (default: FALSE)
* Add support for Oracle
* Mark cached queries in log (Feature Request #405)
* Implement Bcrypt->needs_reshash()
* Add entropy to SQL cache hash; Add uuid() method to DB backends
* Find real document root; Simplify debug paths
* Permit OpenID required fields to be declared as comma-separated string or
array
* Pass modified filename as argument to user-defined function in
Web->receive()
* Quote keys in optional SQL clauses (Issue #408)
* Allow UNLOAD to override fatal error detection (Issue #404)
* Mutex operator precedence error (Issue #406)
* Bug fix: exists() malfunction (Issue #401)
* Bug fix: Jig mapper triggers error when loading from CACHE (Issue #403)
* Bug fix: Array index check
* Bug fix: OpenID verified() return value
* Bug fix: Basket->find() should return a set of results (Issue #407);
Also implemented findone() for consistency with mappers
* Bug fix: PostgreSQL last insert ID (Issue #410)
* Bug fix: $port component URL overwritten by _socket()
* Bug fix: Calculation of elapsed time
3.1.0 (20 August 2013)
---
* NEW: Web->filler() returns a chunk of text from the standard
Lorem Ipsum passage
* Change in behavior: Drop support for JSON serialization
* SQL->exec() now returns value of RETURNING clause
* Add support for $ttl argument in count() (Issue #393)
* Allow UI to be overridden by custom $path
* Return result of PDO primitives: begintransaction(), rollback(), and
commit()
* Full support for PHP 5.5
* Flush buffers only when DEBUG=0
* Support class->method, class::method, and lambda functions as
Web->basic() arguments
* Commit session on Basket->save()
* Optional enlargement in Image->resize()
* Support authentication on hosts running PHP-CGI
* Change visibility level of Cache properties
* Prevent ONERROR recursion
* Work around Apache pre-2.4 VirtualDocumentRoot bug
* Prioritize cURL in HTTP engine detection
* Bug fix: Minify tricky JS
* Bug fix: desktop() detection
* Bug fix: Double-slash on TEMP-relative path
* Bug fix: Cursor mapping of first() and last() records
* Bug fix: Premature end of Web->receive() on multiple files
* Bug fix: German umlaute to its corresponding grammatically-correct
equivalent
3.0.9 (12 June 2013)
---
* NEW: Web->whois()
* NEW: Template <switch> <case> tags
* Improve CACHE consistency
* Case-insensitive MIME type detection
* Support pre-PHP 5.3.4 in Prefab->instance()
* Refactor isdesktop() and ismobile(); Add isbot()
* Add support for Markdown strike-through
* Work around ODBC's lack of quote() support
* Remove useless Prefab destructor
* Support multiple cache instances
* Bug fix: Underscores in OpenId keys mangled
* Refactor format()
* Numerous tweaks
* Bug fix: MongoId object not preserved
* Bug fix: Double-quotes included in lexicon() string (Issue #341)
* Bug fix: UTF-8 formatting mangled on Windows (Issue #342)
* Bug fix: Cache->load() error when CACHE is FALSE (Issue #344)
* Bug fix: send() ternary expression
* Bug fix: Country code constants
3.0.8 (17 May 2013)
---
* NEW: Bcrypt lightweight hashing library\
* Return total number of records in superset in Cursor->paginate()
* ONERROR short-circuit (Enhancement #334)
* Apply quotes/backticks on DB identifiers
* Allow enabling/disabling of SQL log
* Normalize glob() behavior (Issue #330)
* Bug fix: mbstring 2-byte text truncation (Issue #325)
* Bug fix: Unsupported operand types (Issue #324)
3.0.7 (2 May 2013)
---
* NEW: route() now allows an array of routing patterns as first argument;
support array as first argument of map()
* NEW: entropy() for calculating password strength (NIST 800-63)
* NEW: AGENT variable containing auto-detected HTTP user agent string
* NEW: ismobile() and isdesktop() methods
* NEW: Prefab class and descendants now accept constructor arguments
* Change in behavior: Cache->exists() now returns timestamp and TTL of
cache entry or FALSE if not found (Feature request #315)
* Preserve timestamp and TTL when updating cache entry (Feature request
#316)
* Improved currency formatting with C99 compliance
* Suppress unnecessary program halt at startup caused by misconfigured
server
* Add support for dashes in custom attribute names in templates
* Bug fix: Routing precedene (Issue #313)
* Bug fix: Remove Jig _id element from document property
* Bug fix: Web->rss() error when not enough items in the feed (Issue #299)
* Bug fix: Web engine fallback (Issue #300)
* Bug fix: <strong> and <em> formatting
* Bug fix: Text rendering of text with trailing punctuation (Issue #303)
* Bug fix: Incorrect regex in SMTP
3.0.6 (31 Mar 2013)
---
* NEW: Image->crop()
* Modify documentation blocks for PHPDoc interoperability
* Allow user to control whether Base->rerouet() uses a permanent or
temporary redirect
* Allow JAR elements to be set individually
* Refactor DB\SQL\Mapper->insert() to cope with autoincrement fields
* Trigger error when captcha() font is missing
* Remove unnecessary markdown regex recursion
* Check for scalars instead of DB\SQL strings
* Implement more comprehensive diacritics table
* Add option for disabling 401 errors when basic auth() fails
* Add markdown syntax highlighting for Apache configuration
* Markdown->render() deprecated to remove dependency on UI variable;
Feature replaced by Markdown->convert() to enable translation from
markdown string to HTML
* Optimize factory() code of all data mappers
* Apply backticks on MySQL table names
* Bug fix: Routing failure when directory path contains a tilde (Issue #291)
* Bug fix: Incorrect markdown parsing of strong/em sequences and inline HTML
* Bug fix: Cached page not echoed (Issue #278)
* Bug fix: Object properties not escaped when rendering
* Bug fix: OpenID error response ignored
* Bug fix: memcache_get_extended_stats() timeout
* Bug fix: Base->set() doesn't pass TTL to Cache->set()
* Bug fix: Base->scrub() ignores pass-thru * argument (Issue #274)
3.0.5 (16 Feb 2013)
---
* NEW: Markdown class with PHP, HTML, and .ini syntax highlighting support
* NEW: Options for caching of select() and find() results
* NEW: Web->acceptable()
* Add send() argument for forcing downloads
* Provide read() option for applying Unix LF as standard line ending
* Bypass lexicon() call if LANGUAGE is undefined
* Load fallback language dictionary if LANGUAGE is undefined
* map() now checks existence of class/methods for non-tokenized URLs
* Improve error reporting of non-existent Template methods
* Address output buffer issues on some servers
* Bug fix: Setting DEBUG to 0 won't suppress the stack trace when the
content type is application/json (Issue #257)
* Bug fix: Image dump/render additional arguments shifted
* Bug fix: ob_clean() causes buffer issues with zlib compression
* Bug fix: minify() fails when commenting CSS @ rules (Issue #251)
* Bug fix: Handling of commas inside quoted strings
* Bug fix: Glitch in stringify() handling of closures
* Bug fix: dry() in mappers returns TRUE despite being hydrated by
factory() (Issue #265)
* Bug fix: expect() not handling flags correctly
* Bug fix: weather() fails when server is unreachable
3.0.4 (29 Jan 2013)
---
* NEW: Support for ICU/CLDR pluralization
* NEW: User-defined FALLBACK language
* NEW: minify() now recognizes CSS @import directives
* NEW: UTF->bom() returns byte order mark for UTF-8 encoding
* Expose SQL\Mapper->schema()
* Change in behavior: Send error response as JSON string if AJAX request is
detected
* Deprecated: afind*() methods
* Discard output buffer in favor of debug output
* Make _id available to Jig queries
* Magic class now implements ArrayAccess
* Abort execution on startup errors
* Suppress stack trace on DEBUG level 0
* Allow single = as equality operator in Jig query expressions
* Abort OpenID discovery if Web->request() fails
* Mimic PHP *RECURSION* in stringify()
* Modify Jig parser to allow wildcard-search using preg_match()
* Abort execution after error() execution
* Concatenate cached/uncached minify() iterations; Prevent spillover
caching of previous minify() result
* Work around obscure PHP session id regeneration bug
* Revise algorithm for Jig filter involving undefined fields (Issue #230)
* Use checkdnsrr() instead of gethostbyname() in DNSBL check
* Auto-adjust pagination to cursor boundaries
* Add Romanian diacritics
* Bug fix: Root namespace reference and sorting with undefined Jig fields
* Bug fix: Greedy receive() regex
* Bug fix: Default LANGUAGE always 'en'
* Bug fix: minify() hammers cache backend
* Bug fix: Previous values of primary keys not saved during factory()
instantiation
* Bug fix: Jig find() fails when search key is not present in all records
* Bug fix: Jig SORT_DESC (Issue #233)
* Bug fix: Error reporting (Issue #225)
* Bug fix: language() return value
3.0.3 (29 Dec 2013)
---
* NEW: [ajax] and [sync] routing pattern modifiers
* NEW: Basket class (session-based pseudo-mapper, shopping cart, etc.)
* NEW: Test->message() method
* NEW: DB profiling via DB->log()
* NEW: Matrix->calendar()
* NEW: Audit->card() and Audit->mod10() for credit card verification
* NEW: Geo->weather()
* NEW: Base->relay() accepts comma-separated callbacks; but unlike
Base->chain(), result of previous callback becomes argument of the next
* Numerous performance tweaks
* Interoperability with new MongoClient class
* Web->request() now recognizes gzip and deflate encoding
* Differences in behavior of Web->request() engines rectified
* mutex() now uses an ID as argument (instead of filename to make it clear
that specified file is not the target being locked, but a primitive
cross-platform semaphore)
* DB\SQL\Mapper field _id now returned even in the absence of any
auto-increment field
* Magic class spinned off as a separate file
* ISO 3166-1 alpha-2 table updated
* Apache redirect emulation for PHP 5.4 CLI server mode
* Framework instance now passed as argument to any user-defined shutdown
function
* Cache engine now used as storage for Web->minify() output
* Flag added for enabling/disabling Image class filter history
* Bug fix: Trailing routing token consumes HTTP query
* Bug fix: LANGUAGE spills over to LOCALES setting
* Bug fix: Inconsistent dry() return value
* Bug fix: URL-decoding
3.0.2 (23 Dec 2013)
---
* NEW: Syntax-highlighted stack traces via Base->highlight(); boolean
HIGHLIGHT global variable can be used to enable/disable this feature
* NEW: Template engine <ignore> tag
* NEW: Image->captcha()
* NEW: DNSBL-based spammer detection (ported from 2.x)
* NEW: paginate(), first(), and last() methods for data mappers
* NEW: X-HTTP-Method-Override header now recognized
* NEW: Base->chain() method for executing callbacks in succession
* NEW: HOST global variable; derived from either $_SERVER['SERVER_NAME'] or
gethostname()
* NEW: REALM global variable representing full canonical URI
* NEW: Auth plug-in
* NEW: Pingback plug-in (implements both Pingback 1.0 protocol client and
server)
* NEW: DEBUG verbosity can now reach up to level 3; Base->stringify() drills
down to object properties at this setting
* NEW: HTTP PATCH method added to recognized HTTP ReST methods
* Web->slug() now trims trailing dashes
* Web->request() now allows relative local URLs as argument
* Use of PARAMS in route handlers now unnecessary; framework now passes two
arguments to route handlers: the framework object instance and an array
containing the captured values of tokens in route patterns
* Standardized timeout settings among Web->request() backends
* Session IDs regenerated for additional security
* Automatic HTTP 404 responses by Base->call() now restricted to route
handlers
* Empty comments in ini-style files now parsed properly
* Use file_get_contents() in methods that don't involve high concurrency
3.0.1 (14 Dec 2013)
---
* Major rewrite of much of the framework's core features
================================================
FILE: COPYING
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
================================================
FILE: README.md
================================================
# fatfree-core
Fat-Free Framework core library
### Usage:
First make sure to add a proper url rewrite configuration to your server, see https://fatfreeframework.com/3.6/routing-engine#DynamicWebSites
**without composer:**
```php
$f3 = require('lib/base.php');
```
**with composer:**
```
composer require bcosca/fatfree-core
```
```php
require("vendor/autoload.php");
$f3 = \Base::instance();
```
---
For the main repository (demo package), see https://github.com/bcosca/fatfree
For the test bench and unit tests, see https://github.com/f3-factory/fatfree-dev
For the user guide, see https://fatfreeframework.com/user-guide
For the documentation, see https://fatfreeframework.com/api-reference
================================================
FILE: audit.php
================================================
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Data validator
class Audit extends Prefab {
//@{ User agents
const
UA_Mobile='android|blackberry|phone|ipod|palm|windows\s+ce',
UA_Desktop='bsd|linux|os\s+[x9]|solaris|windows',
UA_AI='gpt|claude|mistral|oai|google-extended|perplexity|anthropic|cohere|duckassist|amazonbot|bingbot|-ai|ai-',
UA_Bot='bot|crawl|slurp|spider|agent|omgili|external';
//@}
/**
* Return TRUE if string is a valid URL
* @return bool
* @param $str string
**/
function url($str) {
return is_string(filter_var($str,FILTER_VALIDATE_URL))
&& !preg_match('/^(javascript|php):\/\/.*$/i', $str);
}
/**
* Return TRUE if string is a valid e-mail address;
* Check DNS MX records if specified
* @return bool
* @param $str string
* @param $mx boolean
**/
function email($str,$mx=TRUE) {
$hosts=[];
return is_string(filter_var($str,FILTER_VALIDATE_EMAIL)) &&
(!$mx || getmxrr(substr($str,strrpos($str,'@')+1),$hosts));
}
/**
* Return TRUE if string is a valid IPV4 address
* @return bool
* @param $addr string
**/
function ipv4($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_IP,FILTER_FLAG_IPV4);
}
/**
* Return TRUE if string is a valid IPV6 address
* @return bool
* @param $addr string
**/
function ipv6($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_IP,FILTER_FLAG_IPV6);
}
/**
* Return TRUE if IP address is within private range
* @return bool
* @param $addr string
**/
function isprivate($addr) {
return (bool)filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)
&& !(bool)filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
/**
* Return TRUE if IP address is within reserved range
* @return bool
* @param $addr string
**/
function isreserved($addr) {
return !(bool)filter_var($addr,FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4|FILTER_FLAG_IPV6|FILTER_FLAG_NO_RES_RANGE);
}
/**
* Return TRUE if IP address is neither private nor reserved
* @return bool
* @param $addr string
**/
function ispublic($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4|FILTER_FLAG_IPV6|
FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE);
}
/**
* Return TRUE if user agent is a desktop browser
* @return bool
* @param $agent string
**/
function isdesktop($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_Desktop.')/i',$agent) &&
!$this->ismobile($agent);
}
/**
* Return TRUE if user agent is a mobile device
* @return bool
* @param $agent string
**/
function ismobile($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_Mobile.')/i',$agent);
}
/**
* Return TRUE if user agent is a Web bot
* @return bool
* @param $agent string
**/
function isbot($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_Bot.')/i',$agent);
}
/**
* Return TRUE if user agent is an AI
* @return bool
* @param $agent string
**/
function isai($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_AI.')/i',$agent);
}
/**
* Return TRUE if user agent is a Web bot or an AI
* @return bool
* @param $agent string
**/
function isbotorai($agent=NULL) {
return $this->isbot($agent) || $this->isai($agent);
}
/**
* Return TRUE if specified ID has a valid (Luhn) Mod-10 check digit
* @return bool
* @param $id string
**/
function mod10($id) {
if (!ctype_digit($id))
return FALSE;
$id=strrev($id);
$sum=0;
for ($i=0,$l=strlen($id);$i<$l;++$i)
$sum+=$id[$i]+$i%2*(($id[$i]>4)*-4+$id[$i]%5);
return !($sum%10);
}
/**
* Return credit card type if number is valid
* @return string|FALSE
* @param $id string
**/
function card($id) {
$id=preg_replace('/[^\d]/','',$id);
if ($this->mod10($id)) {
if (preg_match('/^3[47][0-9]{13}$/',$id))
return 'American Express';
if (preg_match('/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',$id))
return 'Diners Club';
if (preg_match('/^6(?:011|5[0-9][0-9])[0-9]{12}$/',$id))
return 'Discover';
if (preg_match('/^(?:2131|1800|35\d{3})\d{11}$/',$id))
return 'JCB';
if (preg_match('/^5[1-5][0-9]{14}$|'.
'^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)\d{12}$/',$id))
return 'MasterCard';
if (preg_match('/^4[0-9]{12}(?:[0-9]{3})?$/',$id))
return 'Visa';
}
return FALSE;
}
/**
* Return entropy estimate of a password (NIST 800-63)
* @return int|float
* @param $str string
**/
function entropy($str) {
$len=strlen($str);
return 4*min($len,1)+($len>1?(2*(min($len,8)-1)):0)+
($len>8?(1.5*(min($len,20)-8)):0)+($len>20?($len-20):0)+
6*(bool)(preg_match(
'/[A-Z].*?[0-9[:punct:]]|[0-9[:punct:]].*?[A-Z]/',$str));
}
/**
* Return TRUE if string is a valid MAC address including EUI-64 format
* @return bool
* @param $addr string
**/
function mac($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_MAC)
|| preg_match('/^([0-9a-f]{2}:){3}ff:fe(:[0-9a-f]{2}){3}$/i', $addr);
}
}
================================================
FILE: auth.php
================================================
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Authorization/authentication plug-in
class Auth {
//@{ Error messages
const
E_LDAP='LDAP connection failure',
E_SMTP='SMTP connection failure';
//@}
protected
//! Auth storage
$storage,
//! Mapper object
$mapper,
//! Storage options
$args,
//! Custom compare function
$func;
/**
* Jig storage handler
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
protected function _jig($id,$pw,$realm) {
$success = (bool)
call_user_func_array(
[$this->mapper,'load'],
[
array_merge(
[
'@'.$this->args['id'].'==?'.
($this->func?'':' AND @'.$this->args['pw'].'==?').
(isset($this->args['realm'])?
(' AND @'.$this->args['realm'].'==?'):''),
$id
],
($this->func?[]:[$pw]),
(isset($this->args['realm'])?[$realm]:[])
)
]
);
if ($success && $this->func)
$success = call_user_func($this->func,$pw,$this->mapper->get($this->args['pw']));
return $success;
}
/**
* MongoDB storage handler
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
protected function _mongo($id,$pw,$realm) {
$success = (bool)
$this->mapper->load(
[$this->args['id']=>$id]+
($this->func?[]:[$this->args['pw']=>$pw])+
(isset($this->args['realm'])?
[$this->args['realm']=>$realm]:[])
);
if ($success && $this->func)
$success = call_user_func($this->func,$pw,$this->mapper->get($this->args['pw']));
return $success;
}
/**
* SQL storage handler
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
protected function _sql($id,$pw,$realm) {
$success = (bool)
call_user_func_array(
[$this->mapper,'load'],
[
array_merge(
[
$this->args['id'].'=?'.
($this->func?'':' AND '.$this->args['pw'].'=?').
(isset($this->args['realm'])?
(' AND '.$this->args['realm'].'=?'):''),
$id
],
($this->func?[]:[$pw]),
(isset($this->args['realm'])?[$realm]:[])
)
]
);
if ($success && $this->func)
$success = call_user_func($this->func,$pw,$this->mapper->get($this->args['pw']));
return $success;
}
/**
* LDAP storage handler
* @return bool
* @param $id string
* @param $pw string
**/
protected function _ldap($id,$pw) {
$port=(int)($this->args['port']?:389);
$filter=$this->args['filter']=$this->args['filter']?:"uid=".$id;
$this->args['attr']=$this->args['attr']?:["uid"];
array_walk($this->args['attr'],
function($attr)use(&$filter,$id) {
$filter=str_ireplace($attr."=*",$attr."=".$id,$filter);});
$dc=@ldap_connect($this->args['dc'],$port);
if ($dc &&
ldap_set_option($dc,LDAP_OPT_PROTOCOL_VERSION,3) &&
ldap_set_option($dc,LDAP_OPT_REFERRALS,0) &&
ldap_bind($dc,$this->args['rdn'],$this->args['pw']) &&
($result=ldap_search($dc,$this->args['base_dn'],
$filter,$this->args['attr'])) &&
ldap_count_entries($dc,$result) &&
($info=ldap_get_entries($dc,$result)) &&
$info['count']==1 &&
@ldap_bind($dc,$info[0]['dn'],$pw) &&
@ldap_close($dc)) {
return in_array($id,(array_map(function($value){return $value[0];},
array_intersect_key($info[0],
array_flip($this->args['attr'])))),TRUE);
}
throw new \Exception(self::E_LDAP);
}
/**
* SMTP storage handler
* @return bool
* @param $id string
* @param $pw string
**/
protected function _smtp($id,$pw) {
$socket=@fsockopen(
(strtolower($this->args['scheme'])=='ssl'?
'ssl://':'').$this->args['host'],
$this->args['port']);
$dialog=function($cmd=NULL) use($socket) {
if (!is_null($cmd))
fputs($socket,$cmd."\r\n");
$reply='';
while (!feof($socket) &&
($info=stream_get_meta_data($socket)) &&
!$info['timed_out'] && $str=fgets($socket,4096)) {
$reply.=$str;
if (preg_match('/(?:^|\n)\d{3} .+\r\n/s',
$reply))
break;
}
return $reply;
};
if ($socket) {
stream_set_blocking($socket,TRUE);
$dialog();
$fw=Base::instance();
$dialog('EHLO '.$fw->HOST);
if (strtolower($this->args['scheme'])=='tls') {
$dialog('STARTTLS');
stream_socket_enable_crypto(
$socket,TRUE,STREAM_CRYPTO_METHOD_TLS_CLIENT);
$dialog('EHLO '.$fw->HOST);
}
// Authenticate
$dialog('AUTH LOGIN');
$dialog(base64_encode($id));
$reply=$dialog(base64_encode($pw));
$dialog('QUIT');
fclose($socket);
return (bool)preg_match('/^235 /',$reply);
}
throw new \Exception(self::E_SMTP);
}
/**
* Login auth mechanism
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
function login($id,$pw,$realm=NULL) {
return $this->{'_'.$this->storage}($id,$pw,$realm);
}
/**
* HTTP basic auth mechanism
* @return bool
* @param $func callback
**/
function basic($func=NULL) {
$fw=Base::instance();
$realm=$fw->REALM;
$hdr=NULL;
if (isset($_SERVER['HTTP_AUTHORIZATION']))
$hdr=$_SERVER['HTTP_AUTHORIZATION'];
elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
$hdr=$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
if (!empty($hdr))
list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])=
explode(':',base64_decode(substr($hdr,6)));
if (isset($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) &&
$this->login(
$_SERVER['PHP_AUTH_USER'],
$func?
$fw->call($func,$_SERVER['PHP_AUTH_PW']):
$_SERVER['PHP_AUTH_PW'],
$realm
))
return TRUE;
if (PHP_SAPI!='cli')
header('WWW-Authenticate: Basic realm="'.$realm.'"');
$fw->status(401);
return FALSE;
}
/**
* Instantiate class
* @return object
* @param $storage string|object
* @param $args array
* @param $func callback
**/
function __construct($storage,?array $args=NULL,$func=NULL) {
if (is_object($storage) && is_a($storage,'DB\Cursor')) {
$this->storage=$storage->dbtype();
$this->mapper=$storage;
unset($ref);
}
else
$this->storage=$storage;
$this->args=$args;
$this->func=$func;
}
}
================================================
FILE: base.php
================================================
<?php
/*
Copyright (c) 2009-2023 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Factory class for single-instance objects
abstract class Prefab {
/**
* Return class instance
* @return static
**/
static function instance() {
if (!Registry::exists($class=get_called_class())) {
$ref=new ReflectionClass($class);
$args=func_get_args();
Registry::set($class,
$args?$ref->newinstanceargs($args):new $class);
}
return Registry::get($class);
}
}
/**
* @property string ALIAS
* @property array ALIASES
* @property string|array AUTOLOAD
* @property bool|string CACHE
* @property bool CASELESS
* @property callable|\Prefab|\Psr\Container\ContainerInterface CONTAINER
* @property array COOKIE
* @property array GET
* @property array POST
* @property array REQUEST
* @property array SESSION
* @property array FILES
* @property array SERVER
* @property array ENV
* @property array CORS
* @property int DEBUG
* @property array DIACRITICS
* @property string DNSBL
* @property array EMOJI
* @property string ENCODING
* @property bool ESCAPE
* @property string EXEMPT
* @property object EXCEPTION
* @property string FALLBACK
* @property array FORMATS
* @property string FRAGMENT
* @property bool HALT
* @property bool HIGHLIGHT
* @property array JAR
* @property string LANGUAGE
* @property string LOCALES
* @property string|array LOGGABLE
* @property string LOGS
* @property mixed ONERROR
* @property mixed ONREROUTE
* @property string|null PACKAGE
* @property array PARAMS
* @property string PLUGINS
* @property string PREFIX
* @property string PREMAP
* @property bool QUIET
* @property bool RAW
* @property array ROUTES
* @property string SEED
* @property string SERIALIZER
* @property string TEMP
* @property float TIME
* @property bool REROUTE_TRAILING_SLASH
* @property string TZ
* @property string UI
* @property callback UNLOAD
* @property string UPLOADS
* @property string URI
* @property string VERB
* @property string VERSION
* @property string|null XFRAME
* @property-read string AGENT
* @property-read bool AJAX
* @property-read string BASE
* @property-read string BODY
* @property-read bool CLI
* @property-read array ERROR
* @property-read array HEADERS
* @property-read string HOST
* @property-read string IP
* @property-read string PATH
* @property-read string PATTERN
* @property-read int PORT
* @property-read string QUERY
* @property-read string REALM
* @property-read string RESPONSE
* @property-read string ROOT
* @property-read string SCHEME
*/
//! Base structure
final class Base extends Prefab implements ArrayAccess {
//@{ Framework details
const
PACKAGE='Fat-Free Framework',
VERSION='3.9.2-Release';
//@}
//@{ HTTP status codes (RFC 2616)
const
HTTP_100='Continue',
HTTP_101='Switching Protocols',
HTTP_103='Early Hints',
HTTP_200='OK',
HTTP_201='Created',
HTTP_202='Accepted',
HTTP_203='Non-Authorative Information',
HTTP_204='No Content',
HTTP_205='Reset Content',
HTTP_206='Partial Content',
HTTP_300='Multiple Choices',
HTTP_301='Moved Permanently',
HTTP_302='Found',
HTTP_303='See Other',
HTTP_304='Not Modified',
HTTP_305='Use Proxy',
HTTP_307='Temporary Redirect',
HTTP_308='Permanent Redirect',
HTTP_400='Bad Request',
HTTP_401='Unauthorized',
HTTP_402='Payment Required',
HTTP_403='Forbidden',
HTTP_404='Not Found',
HTTP_405='Method Not Allowed',
HTTP_406='Not Acceptable',
HTTP_407='Proxy Authentication Required',
HTTP_408='Request Timeout',
HTTP_409='Conflict',
HTTP_410='Gone',
HTTP_411='Length Required',
HTTP_412='Precondition Failed',
HTTP_413='Request Entity Too Large',
HTTP_414='Request-URI Too Long',
HTTP_415='Unsupported Media Type',
HTTP_416='Requested Range Not Satisfiable',
HTTP_417='Expectation Failed',
HTTP_421='Misdirected Request',
HTTP_422='Unprocessable Entity',
HTTP_423='Locked',
HTTP_429='Too Many Requests',
HTTP_451='Unavailable For Legal Reasons',
HTTP_500='Internal Server Error',
HTTP_501='Not Implemented',
HTTP_502='Bad Gateway',
HTTP_503='Service Unavailable',
HTTP_504='Gateway Timeout',
HTTP_505='HTTP Version Not Supported',
HTTP_507='Insufficient Storage',
HTTP_511='Network Authentication Required';
//@}
const
//! Mapped PHP globals
GLOBALS='GET|POST|COOKIE|REQUEST|SESSION|FILES|SERVER|ENV',
//! HTTP verbs
VERBS='GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|OPTIONS',
//! Default directory permissions
MODE=0755,
//! Syntax highlighting stylesheet
CSS='code.css';
//@{ Request types
const
REQ_SYNC=1,
REQ_AJAX=2,
REQ_CLI=4;
//@}
//@{ Error messages
const
E_Pattern='Invalid routing pattern: %s',
E_Named='Named route does not exist: %s',
E_Alias='Invalid named route alias: %s',
E_Fatal='Fatal error: %s',
E_Open='Unable to open %s',
E_Routes='No routes specified',
E_Class='Invalid class %s',
E_Method='Invalid method %s',
E_Hive='Invalid hive key %s';
//@}
private
//! Globals
$hive,
//! Initial settings
$init,
//! Language lookup sequence
$languages,
//! Mutex locks
$locks=[],
//! Default fallback language
$fallback='en';
/**
* Sync PHP global with corresponding hive key
* @return array
* @param $key string
**/
function sync($key) {
return $this->hive[$key]=&$GLOBALS['_'.$key];
}
/**
* Return the parts of specified hive key
* @return array
* @param $key string
**/
private function cut($key) {
return preg_split('/\[\h*[\'"]?(.+?)[\'"]?\h*\]|(->)|\./',
$key,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
}
/**
* Replace tokenized URL with available token values
* @return string
* @param $url array|string
* @param $addParams boolean merge default PARAMS from hive into args
* @param $args array
**/
function build($url, $args=[], $addParams=TRUE) {
if ($addParams)
$args+=$this->recursive($this->hive['PARAMS'], function($val) {
return implode('/', array_map('urlencode', explode('/', $val ?? '')));
});
if (is_array($url))
foreach ($url as &$var) {
$var=$this->build($var,$args, false);
unset($var);
}
else {
$i=0;
$url=preg_replace_callback('/(\{)?@(\w+)(?(1)\})|(\*)/',
function($match) use(&$i,$args) {
if (isset($match[2]) &&
array_key_exists($match[2],$args))
return $args[$match[2]];
if (isset($match[3]) &&
array_key_exists($match[3],$args)) {
if (!is_array($args[$match[3]]))
return $args[$match[3]];
++$i;
return $args[$match[3]][$i-1];
}
return $match[0];
},$url);
}
return $url;
}
/**
* Parse string containing key-value pairs
* @return array
* @param $str string
**/
function parse($str) {
preg_match_all('/(\w+|\*)\h*=\h*(?:\[(.+?)\]|(.+?))(?=,|$)/',
$str,$pairs,PREG_SET_ORDER);
$out=[];
foreach ($pairs as $pair)
if ($pair[2]) {
$out[$pair[1]]=[];
foreach (explode(',',$pair[2]) as $val)
array_push($out[$pair[1]],$val);
}
else
$out[$pair[1]]=trim($pair[3]);
return $out;
}
/**
* Cast string variable to PHP type or constant
* @param $val
* @return mixed
*/
function cast($val) {
if ($val && preg_match('/^(?:0x[0-9a-f]+|0[0-7]+|0b[01]+)$/i',$val))
return intval($val,0);
if (is_numeric($val))
return $val+0;
$val=trim($val?:'');
if (preg_match('/^\w+$/i',$val) && defined($val))
return constant($val);
return $val;
}
/**
* Convert JS-style token to PHP expression
* @return string
* @param $str string
* @param $evaluate bool compile expressions as well or only convert variable access
**/
function compile($str, $evaluate=TRUE) {
return (!$evaluate)
? preg_replace_callback(
'/^@(\w+)((?:\..+|\[(?:(?:[^\[\]]*|(?R))*)\])*)/',
function($expr) {
$str='$'.$expr[1];
if (isset($expr[2]))
$str.=preg_replace_callback(
'/\.([^.\[\]]+)|\[((?:[^\[\]\'"]*|(?R))*)\]/',
function($sub) {
$val=isset($sub[2]) ? $sub[2] : $sub[1];
if (ctype_digit($val))
$val=(int)$val;
$out='['.$this->export($val).']';
return $out;
},
$expr[2]
);
return $str;
},
$str
)
: preg_replace_callback(
'/(?<!\w)@(\w+(?:(?:\->|::)\w+)?)'.
'((?:\.\w+|\[(?:(?:[^\[\]]*|(?R))*)\]|(?:\->|::)\w+|\()*)/',
function($expr) {
$str='$'.$expr[1];
if (isset($expr[2]))
$str.=preg_replace_callback(
'/\.(\w+)(\()?|\[((?:[^\[\]]*|(?R))*)\]/',
function($sub) {
if (empty($sub[2])) {
if (ctype_digit($sub[1]))
$sub[1]=(int)$sub[1];
$out='['.
(isset($sub[3])?
$this->compile($sub[3]):
$this->export($sub[1])).
']';
}
else
$out=function_exists($sub[1])?
$sub[0]:
('['.$this->export($sub[1]).']'.$sub[2]);
return $out;
},
$expr[2]
);
return $str;
},
$str
);
}
/**
* Get hive key reference/contents; Add non-existent hive keys,
* array elements, and object properties by default
* @return mixed
* @param $key string
* @param $add bool
* @param $var mixed
**/
function &ref($key,$add=TRUE,&$var=NULL) {
$null=NULL;
$parts=$this->cut($key);
if ($parts[0]=='SESSION') {
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
$this->sync('SESSION');
}
elseif (!preg_match('/^\w+$/',$parts[0]))
throw new \Exception(\sprintf(self::E_Hive,$this->stringify($key)));
if (is_null($var)) {
if ($add)
$var=&$this->hive;
else
$var=$this->hive;
}
$obj=FALSE;
foreach ($parts as $part)
if ($part=='->')
$obj=TRUE;
elseif ($obj) {
$obj=FALSE;
if (!is_object($var))
$var=new stdClass;
if ($add || property_exists($var,$part))
$var=&$var->$part;
else {
$var=&$null;
break;
}
}
else {
if (!is_array($var))
$var=[];
if ($add || array_key_exists($part,$var))
$var=&$var[$part];
else {
$var=&$null;
break;
}
}
return $var;
}
/**
* Return TRUE if hive key is set
* (or return timestamp and TTL if cached)
* @return bool
* @param $key string
* @param $val mixed
**/
function exists($key,&$val=NULL) {
$val=$this->ref($key,FALSE);
return isset($val)?
TRUE:
(Cache::instance()->exists($this->hash($key).'.var',$val)?:FALSE);
}
/**
* Return TRUE if hive key is empty and not cached
* @param $key string
* @param $val mixed
* @return bool
**/
function devoid($key,&$val=NULL) {
$val=$this->ref($key,FALSE);
return empty($val) &&
(!Cache::instance()->exists($this->hash($key).'.var',$val) ||
!$val);
}
/**
* Bind value to hive key
* @return mixed
* @param $key string
* @param $val mixed
* @param $ttl int
**/
function set($key,$val,$ttl=0) {
$time=(int)$this->hive['TIME'];
if (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
$this->set('REQUEST'.$expr[2],$val);
if ($expr[1]=='COOKIE') {
$parts=$this->cut($key);
$jar=$this->unserialize($this->serialize($this->hive['JAR']));
unset($jar['lifetime']);
if (version_compare(PHP_VERSION, '7.3.0') >= 0) {
unset($jar['expire']);
if (isset($_COOKIE[$parts[1]]))
setcookie($parts[1],'',['expires'=>0]+$jar);
if ($ttl)
$jar['expires']=$time+$ttl;
setcookie($parts[1],$val?:'',$jar);
} else {
unset($jar['samesite']);
if (isset($_COOKIE[$parts[1]]))
call_user_func_array('setcookie',
array_merge([$parts[1],''],['expire'=>0]+$jar));
if ($ttl)
$jar['expire']=$time+$ttl;
call_user_func_array('setcookie',[$parts[1],$val?:'']+$jar);
}
$_COOKIE[$parts[1]]=$val;
return $val;
}
}
else switch ($key) {
case 'CACHE':
$val=Cache::instance()->load($val);
break;
case 'ENCODING':
ini_set('default_charset',$val);
if (extension_loaded('mbstring'))
mb_internal_encoding($val);
break;
case 'FALLBACK':
$this->fallback=$val;
$lang=$this->language($this->hive['LANGUAGE']);
case 'LANGUAGE':
if (!isset($lang))
$val=$this->language($val);
$lex=$this->lexicon($this->hive['LOCALES'],$ttl);
case 'LOCALES':
if (isset($lex) || $lex=$this->lexicon($val,$ttl))
foreach ($lex as $dt=>$dd) {
$ref=&$this->ref($this->hive['PREFIX'].$dt);
$ref=$dd;
unset($ref);
}
break;
case 'TZ':
date_default_timezone_set($val);
break;
}
$ref=&$this->ref($key);
$ref=$val;
if (preg_match('/^JAR\b/',$key)) {
if ($key=='JAR.lifetime')
$this->set('JAR.expire',$val==0?0:
(is_int($val)?$time+$val:strtotime($val)));
else {
if ($key=='JAR.expire')
$this->hive['JAR']['lifetime']=max(0,$val-$time);
$jar=$this->unserialize($this->serialize($this->hive['JAR']));
unset($jar['expire']);
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
if (version_compare(PHP_VERSION, '7.3.0') >= 0)
session_set_cookie_params($jar);
else {
unset($jar['samesite']);
call_user_func_array('session_set_cookie_params',$jar);
}
}
}
if ($ttl)
// Persist the key-value pair
Cache::instance()->set($this->hash($key).'.var',$val,$ttl);
return $ref;
}
/**
* Retrieve contents of hive key
* @return mixed
* @param $key string
* @param $args string|array
**/
function get($key,$args=NULL) {
if (is_string($val=$this->ref($key,FALSE)) && !is_null($args))
return call_user_func_array(
[$this,'format'],
array_merge([$val],is_array($args)?$args:[$args])
);
if (is_null($val)) {
// Attempt to retrieve from cache
if (Cache::instance()->exists($this->hash($key).'.var',$data))
return $data;
}
return $val;
}
/**
* Unset hive key
* @param $key string
**/
function clear($key) {
// Normalize array literal
$cache=Cache::instance();
$parts=$this->cut($key);
if ($key=='CACHE')
// Clear cache contents
$cache->reset();
elseif (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
$this->clear('REQUEST'.$expr[2]);
if ($expr[1]=='COOKIE') {
$parts=$this->cut($key);
$jar=$this->hive['JAR'];
unset($jar['lifetime']);
$jar['expire']=0;
if (version_compare(PHP_VERSION, '7.3.0') >= 0) {
$jar['expires']=$jar['expire'];
unset($jar['expire']);
setcookie($parts[1],'',$jar);
} else {
unset($jar['samesite']);
call_user_func_array('setcookie',
array_merge([$parts[1],''],$jar));
}
unset($_COOKIE[$parts[1]]);
}
}
elseif ($parts[0]=='SESSION') {
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
if (empty($parts[1])) {
// End session
session_unset();
session_destroy();
$this->clear('COOKIE.'.session_name());
}
$this->sync('SESSION');
}
if (!isset($parts[1]) && array_key_exists($parts[0],$this->init))
// Reset global to default value
$this->hive[$parts[0]]=$this->init[$parts[0]];
else {
$val=preg_replace('/^(\$hive)/','$this->hive',
$this->compile('@hive.'.$key, FALSE));
eval('unset('.$val.');');
if ($parts[0]=='SESSION') {
session_commit();
session_start();
}
if ($cache->exists($hash=$this->hash($key).'.var'))
// Remove from cache
$cache->clear($hash);
}
}
/**
* Return TRUE if hive variable is 'on'
* @return bool
* @param $key string
**/
function checked($key) {
$ref=&$this->ref($key);
return $ref=='on';
}
/**
* Return TRUE if property has public visibility
* @return bool
* @param $obj object
* @param $key string
**/
function visible($obj,$key) {
if (property_exists($obj,$key)) {
$ref=new ReflectionProperty(get_class($obj),$key);
$out=$ref->ispublic();
unset($ref);
return $out;
}
return FALSE;
}
/**
* Multi-variable assignment using associative array
* @param $vars array
* @param $prefix string
* @param $ttl int
**/
function mset(array $vars,$prefix='',$ttl=0) {
foreach ($vars as $key=>$val)
$this->set($prefix.$key,$val,$ttl);
}
/**
* Publish hive contents
* @return array
**/
function hive() {
return $this->hive;
}
/**
* Copy contents of hive variable to another
* @return mixed
* @param $src string
* @param $dst string
**/
function copy($src,$dst) {
$ref=&$this->ref($dst);
return $ref=$this->ref($src,FALSE);
}
/**
* Concatenate string to hive string variable
* @return string
* @param $key string
* @param $val string
**/
function concat($key,$val) {
$ref=&$this->ref($key);
$ref.=$val;
return $ref;
}
/**
* Swap keys and values of hive array variable
* @return array
* @param $key string
* @public
**/
function flip($key) {
$ref=&$this->ref($key);
return $ref=array_combine(array_values($ref),array_keys($ref));
}
/**
* Add element to the end of hive array variable
* @return mixed
* @param $key string
* @param $val mixed
**/
function push($key,$val) {
$ref=&$this->ref($key);
$ref[]=$val;
return $val;
}
/**
* Remove last element of hive array variable
* @return mixed
* @param $key string
**/
function pop($key) {
$ref=&$this->ref($key);
return array_pop($ref);
}
/**
* Add element to the beginning of hive array variable
* @return mixed
* @param $key string
* @param $val mixed
**/
function unshift($key,$val) {
$ref=&$this->ref($key);
array_unshift($ref,$val);
return $val;
}
/**
* Remove first element of hive array variable
* @return mixed
* @param $key string
**/
function shift($key) {
$ref=&$this->ref($key);
return array_shift($ref);
}
/**
* Merge array with hive array variable
* @return array
* @param $key string
* @param $src string|array
* @param $keep bool
**/
function merge($key,$src,$keep=FALSE) {
$ref=&$this->ref($key);
if (!$ref)
$ref=[];
$out=array_merge($ref,is_string($src)?$this->hive[$src]:$src);
if ($keep)
$ref=$out;
return $out;
}
/**
* Extend hive array variable with default values from $src
* @return array
* @param $key string
* @param $src string|array
* @param $keep bool
**/
function extend($key,$src,$keep=FALSE) {
$ref=&$this->ref($key);
if (!$ref)
$ref=[];
$out=array_replace_recursive(
is_string($src)?$this->hive[$src]:$src,$ref);
if ($keep)
$ref=$out;
return $out;
}
/**
* fetch a hive key result, then clear the key
* @param string $key
* @return mixed
*/
function pull($key): mixed
{
$value = $this->get($key);
$this->clear($key);
return $value;
}
/**
* Convert backslashes to slashes
* @return string
* @param $str string
**/
function fixslashes($str) {
return $str?strtr($str,'\\','/'):$str;
}
/**
* Split comma-, semi-colon, or pipe-separated string
* @return array
* @param $str string
* @param $noempty bool
**/
function split($str,$noempty=TRUE) {
return array_map('trim',
preg_split('/[,;|]/',$str?:'',0,$noempty?PREG_SPLIT_NO_EMPTY:0));
}
/**
* Convert PHP expression/value to compressed exportable string
* @return string
* @param $arg mixed
* @param $stack array
**/
function stringify($arg,?array $stack=NULL) {
if ($stack) {
foreach ($stack as $node)
if ($arg===$node)
return '*RECURSION*';
}
else
$stack=[];
switch (gettype($arg)) {
case 'object':
$str='';
foreach (get_object_vars($arg) as $key=>$val)
$str.=($str?',':'').
$this->export($key).'=>'.
$this->stringify($val,
array_merge($stack,[$arg]));
return get_class($arg).'::__set_state(['.$str.'])';
case 'array':
$str='';
$num=isset($arg[0]) &&
ctype_digit(implode('',array_keys($arg)));
foreach ($arg as $key=>$val)
$str.=($str?',':'').
($num?'':($this->export($key).'=>')).
$this->stringify($val,array_merge($stack,[$arg]));
return '['.$str.']';
default:
return $this->export($arg);
}
}
/**
* Flatten array values and return as CSV string
* @return string
* @param $args array
**/
function csv(array $args) {
return implode(',',array_map('stripcslashes',
array_map([$this,'stringify'],$args)));
}
/**
* Convert snakecase string to camelcase
* @return string
* @param $str string
**/
function camelcase($str) {
return preg_replace_callback(
'/_(\pL)/u',
function($match) {
return strtoupper($match[1]);
},
$str
);
}
/**
* Convert camelcase string to snakecase
* @return string
* @param $str string
**/
function snakecase($str) {
return strtolower(preg_replace('/(?!^)\p{Lu}/u','_\0',$str));
}
/**
* Return -1 if specified number is negative, 0 if zero,
* or 1 if the number is positive
* @return int
* @param $num mixed
**/
function sign($num) {
return $num?($num/abs($num)):0;
}
/**
* Extract values of array whose keys start with the given prefix
* @return array
* @param $arr array
* @param $prefix string
**/
function extract($arr,$prefix) {
$out=[];
foreach (preg_grep('/^'.preg_quote($prefix,'/').'/',array_keys($arr))
as $key)
$out[substr($key,strlen($prefix))]=$arr[$key];
return $out;
}
/**
* Convert class constants to array
* @return array
* @param $class object|string
* @param $prefix string
**/
function constants($class,$prefix='') {
$ref=new ReflectionClass($class);
return $this->extract($ref->getconstants(),$prefix);
}
/**
* Generate 64bit/base36 hash
* @return string
* @param $str
**/
function hash($str) {
return str_pad(base_convert(
substr(sha1($str?:''),-16),16,36),11,'0',STR_PAD_LEFT);
}
/**
* Return Base64-encoded equivalent
* @return string
* @param $data string
* @param $mime string
**/
function base64($data,$mime) {
return 'data:'.$mime.';base64,'.base64_encode($data);
}
/**
* Convert special characters to HTML entities
* @return string
* @param $str string
**/
function encode($str) {
return @htmlspecialchars($str,$this->hive['BITMASK'],
$this->hive['ENCODING'])?:$this->scrub($str);
}
/**
* Convert HTML entities back to characters
* @return string
* @param $str string
**/
function decode($str) {
return htmlspecialchars_decode($str,$this->hive['BITMASK']);
}
/**
* Invoke callback recursively for all data types
* @return mixed
* @param $arg mixed
* @param $func callback
* @param $stack array
**/
function recursive($arg,$func,$stack=[]) {
if ($stack) {
foreach ($stack as $node)
if ($arg===$node)
return $arg;
}
switch (gettype($arg)) {
case 'object':
$ref=new ReflectionClass($arg);
if ($ref->iscloneable()) {
$arg=clone($arg);
$cast=($it=is_a($arg,'IteratorAggregate'))?
iterator_to_array($arg):get_object_vars($arg);
foreach ($cast as $key=>$val) {
// skip inaccessible properties #350
if (!$it && !isset($arg->$key))
continue;
$arg->$key=$this->recursive(
$val,$func,array_merge($stack,[$arg]));
}
}
return $arg;
case 'array':
$copy=[];
foreach ($arg as $key=>$val)
$copy[$key]=$this->recursive($val,$func,
array_merge($stack,[$arg]));
return $copy;
}
return $func($arg);
}
/**
* Remove HTML tags (except those enumerated) and non-printable characters
* NB: This method doesn't mitigate XSS/code injection attacks.
* @return mixed
* @param $arg mixed
* @param $tags string
**/
function clean($arg,$tags=NULL) {
return $this->recursive($arg,
function($val) use($tags) {
if ($tags!='*')
$val=trim(strip_tags($val??'',
'<'.implode('><',$this->split($tags)).'>'));
return trim(preg_replace(
'/[\x00-\x08\x0B\x0C\x0E-\x1F]/','',$val));
}
);
}
/**
* Similar to clean(), except that variable is passed by reference
* @return mixed
* @param $var mixed
* @param $tags string
**/
function scrub(&$var,$tags=NULL) {
return $var=$this->clean($var,$tags);
}
/**
* Return locale-aware formatted string
* @return string
**/
function format() {
$args=func_get_args();
$val=array_shift($args);
// Get formatting rules
$conv=localeconv();
return preg_replace_callback(
'/\{\s*(?P<pos>\d+)\s*(?:,\s*(?P<type>\w+)\s*'.
'(?:,\s*(?P<mod>(?:\w+(?:\s*\{.+?\}\s*,?\s*)?)*)'.
'(?:,\s*(?P<prop>.+?))?)?)?\s*\}/',
function($expr) use($args,$conv) {
/**
* @var string $pos
* @var string $mod
* @var string $type
* @var string $prop
*/
extract($expr);
/**
* @var string $thousands_sep
* @var string $negative_sign
* @var string $positive_sign
* @var string $frac_digits
* @var string $decimal_point
* @var string $int_curr_symbol
* @var string $currency_symbol
*/
extract($conv);
if (!array_key_exists($pos,$args))
return $expr[0];
if (isset($type)) {
if (isset($this->hive['FORMATS'][$type]))
return $this->call(
$this->hive['FORMATS'][$type],
[
$args[$pos],
isset($mod)?$mod:null,
isset($prop)?$prop:null
]
);
$php81=version_compare(PHP_VERSION, '8.1.0')>=0;
switch ($type) {
case 'plural':
preg_match_all('/(?<tag>\w+)'.
'(?:\s*\{\s*(?<data>.*?)\s*\})/',
$mod,$matches,PREG_SET_ORDER);
$ord=['zero','one','two'];
foreach ($matches as $match) {
/** @var string $tag */
/** @var string $data */
extract($match);
if (isset($ord[$args[$pos]]) &&
$tag==$ord[$args[$pos]] || $tag=='other')
return str_replace('#',$args[$pos],$data);
}
case 'number':
if (isset($mod))
switch ($mod) {
case 'integer':
return number_format(
$args[$pos],0,'',$thousands_sep);
case 'currency':
$int=$cstm=FALSE;
if (isset($prop) &&
$cstm=!$int=($prop=='int'))
$currency_symbol=$prop;
if (!$cstm &&
function_exists('money_format') &&
version_compare(PHP_VERSION,'7.4.0')<0)
return money_format(
'%'.($int?'i':'n'),$args[$pos]);
$fmt=[
0=>'(nc)',1=>'(n c)',
2=>'(nc)',10=>'+nc',
11=>'+n c',12=>'+ nc',
20=>'nc+',21=>'n c+',
22=>'nc +',30=>'n+c',
31=>'n +c',32=>'n+ c',
40=>'nc+',41=>'n c+',
42=>'nc +',100=>'(cn)',
101=>'(c n)',102=>'(cn)',
110=>'+cn',111=>'+c n',
112=>'+ cn',120=>'cn+',
121=>'c n+',122=>'cn +',
130=>'+cn',131=>'+c n',
132=>'+ cn',140=>'c+n',
141=>'c+ n',142=>'c +n'
];
if ($args[$pos]<0) {
$sgn=$negative_sign;
$pre='n';
}
else {
$sgn=$positive_sign;
$pre='p';
}
return str_replace(
['+','n','c'],
[$sgn,number_format(
abs($args[$pos]),
$frac_digits,
$decimal_point,
$thousands_sep),
$int?$int_curr_symbol
:$currency_symbol],
$fmt[(int)(
(${$pre.'_cs_precedes'}%2).
(${$pre.'_sign_posn'}%5).
(${$pre.'_sep_by_space'}%3)
)]
);
case 'percent':
return number_format(
$args[$pos]*100,0,$decimal_point,
$thousands_sep).'%';
}
$frac=$args[$pos]-(int)$args[$pos];
return number_format(
$args[$pos],
isset($prop)?
$prop:
($frac?strlen($frac)-2:0),
$decimal_point,$thousands_sep);
case 'date':
if ($php81) {
$lang = $this->split($this->LANGUAGE);
// requires intl extension
$dateType=(empty($mod) || $mod=='short') ? IntlDateFormatter::SHORT :
($mod=='full' ? IntlDateFormatter::FULL : IntlDateFormatter::LONG);
$pattern = $dateType === IntlDateFormatter::SHORT
? (($ptn=IntlDatePatternGenerator::create($lang[0]))
? $ptn->getBestPattern('yyyyMMdd') : null) : null;
$formatter = new IntlDateFormatter($lang[0],$dateType,
IntlDateFormatter::NONE, null,null, $pattern);
return $formatter->format($args[$pos]);
} else {
if (empty($mod) || $mod=='short')
$prop='%x';
elseif ($mod=='full')
$prop='%A, %d %B %Y';
elseif ($mod!='custom')
$prop='%d %B %Y';
return strftime($prop,$args[$pos]);
}
case 'time':
if ($php81) {
$lang = $this->split($this->LANGUAGE);
// requires intl extension
$formatter = new IntlDateFormatter($lang[0],
IntlDateFormatter::NONE,
(empty($mod) || $mod=='short')
? IntlDateFormatter::SHORT :
($mod=='full' ? IntlDateFormatter::LONG : IntlDateFormatter::MEDIUM),
IntlTimeZone::createTimeZone($this->hive['TZ']));
return $formatter->format($args[$pos]);
} else {
if (empty($mod) || $mod=='short')
$prop='%X';
elseif ($mod!='custom')
$prop='%r';
return strftime($prop,$args[$pos]);
}
default:
return $expr[0];
}
}
return $args[$pos];
},
$val
);
}
/**
* Return string representation of expression
* @return string
* @param $expr mixed
**/
function export($expr) {
return var_export($expr,TRUE);
}
/**
* Assign/auto-detect language
* @return string
* @param $code string
**/
function language($code) {
$code=preg_replace('/\h+|;q=[0-9.]+/','',$code?:'');
$code.=($code?',':'').$this->fallback;
$this->languages=[];
foreach (array_reverse(explode(',',$code)) as $lang)
if (preg_match('/^(\w{2})(?:-(\w{2}))?\b/i',$lang,$parts)) {
// Generic language
array_unshift($this->languages,$parts[1]);
if (isset($parts[2])) {
// Specific language
$parts[0]=$parts[1].'-'.($parts[2]=strtoupper($parts[2]));
array_unshift($this->languages,$parts[0]);
}
}
$this->languages=array_unique($this->languages);
$locales=[];
$windows=preg_match('/^win/i',PHP_OS);
// Work around PHP's Turkish locale bug
foreach (preg_grep('/^(?!tr)/i',$this->languages) as $locale) {
if ($windows) {
$parts=explode('-',$locale);
if (!defined('ISO::LC_'.$parts[0]))
continue;
$locale=constant('ISO::LC_'.$parts[0]);
if (isset($parts[1]) &&
defined($cc='ISO::CC_'.strtolower($parts[1])))
$locale.='-'.constant($cc);
}
$locale=str_replace('-','_',$locale);
$locales[]=$locale.'.'.ini_get('default_charset');
$locales[]=$locale;
}
setlocale(LC_ALL,$locales);
return $this->hive['LANGUAGE']=implode(',',$this->languages);
}
/**
* Return lexicon entries
* @return array
* @param $path string
* @param $ttl int
**/
function lexicon($path,$ttl=0) {
$languages=$this->languages?:explode(',',$this->fallback);
$cache=Cache::instance();
if ($ttl && $cache->exists(
$hash=$this->hash(implode(',',$languages).$path).'.dic',$lex))
return $lex;
$lex=[];
foreach ($languages as $lang)
foreach ($this->split($path) as $dir)
if ((is_file($file=($base=$dir.$lang).'.php') ||
is_file($file=$base.'.php')) &&
is_array($dict=require($file)))
$lex+=$dict;
elseif (is_file($file=$base.'.json') &&
is_array($dict=json_decode(file_get_contents($file), true)))
$lex+=$dict;
elseif (is_file($file=$base.'.ini')) {
preg_match_all(
'/(?<=^|\n)(?:'.
'\[(?<prefix>.+?)\]|'.
'(?<lval>[^\h\r\n;].*?)\h*=\h*'.
'(?<rval>(?:\\\\\h*\r?\n|.+?)*)'.
')(?=\r?\n|$)/',
$this->read($file),$matches,PREG_SET_ORDER);
if ($matches) {
$prefix='';
foreach ($matches as $match)
if ($match['prefix'])
$prefix=$match['prefix'].'.';
elseif (!array_key_exists(
$key=$prefix.$match['lval'],$lex))
$lex[$key]=trim(preg_replace(
'/\\\\\h*\r?\n/',"\n",$match['rval']));
}
}
if ($ttl)
$cache->set($hash,$lex,$ttl);
return $lex;
}
/**
* Return string representation of PHP value
* @return string
* @param $arg mixed
**/
function serialize($arg) {
switch (strtolower($this->hive['SERIALIZER'])) {
case 'igbinary':
return igbinary_serialize($arg);
default:
return serialize($arg);
}
}
/**
* Return PHP value derived from string
* @return mixed
* @param $arg mixed
**/
function unserialize($arg) {
switch (strtolower($this->hive['SERIALIZER'])) {
case 'igbinary':
return igbinary_unserialize($arg);
default:
return unserialize($arg);
}
}
/**
* Send HTTP status header; Return text equivalent of status code
* @return string
* @param $code int
**/
function status($code) {
$reason=@constant('self::HTTP_'.$code);
if (!$this->hive['CLI'] && !headers_sent())
header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$reason);
return $reason;
}
/**
* Send cache metadata to HTTP client
* @param $secs int
**/
function expire($secs=0) {
if (!$this->hive['CLI'] && !headers_sent()) {
$secs=(int)$secs;
if ($this->hive['PACKAGE'])
header('X-Powered-By: '.$this->hive['PACKAGE']);
if ($this->hive['XFRAME'])
header('X-Frame-Options: '.$this->hive['XFRAME']);
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
if ($this->hive['VERB']=='GET' && $secs) {
$time=microtime(TRUE);
header_remove('Pragma');
header('Cache-Control: max-age='.$secs);
header('Expires: '.gmdate('r',round($time+$secs)));
header('Last-Modified: '.gmdate('r'));
}
else {
header('Pragma: no-cache');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: '.gmdate('r',0));
}
}
}
/**
* Return HTTP user agent
* @return string
**/
function agent() {
$headers=$this->hive['HEADERS'];
return isset($headers['X-Operamini-Phone-UA'])?
$headers['X-Operamini-Phone-UA']:
(isset($headers['X-Skyfire-Phone'])?
$headers['X-Skyfire-Phone']:
(isset($headers['User-Agent'])?
$headers['User-Agent']:''));
}
/**
* Return TRUE if XMLHttpRequest detected
* @return bool
**/
function ajax() {
$headers=$this->hive['HEADERS'];
return isset($headers['X-Requested-With']) &&
$headers['X-Requested-With']=='XMLHttpRequest';
}
/**
* Sniff IP address
* @return string
**/
function ip() {
$headers=$this->hive['HEADERS'];
return isset($headers['Client-IP'])?
$headers['Client-IP']:
(isset($headers['X-Forwarded-For'])?
explode(',',$headers['X-Forwarded-For'])[0]:
(isset($_SERVER['REMOTE_ADDR'])?
$_SERVER['REMOTE_ADDR']:''));
}
/**
* Return filtered stack trace as a formatted string (or array)
* @return string|array
* @param $trace array|NULL
* @param $format bool
**/
function trace(?array $trace=NULL,$format=TRUE) {
if (!$trace) {
$trace=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$frame=$trace[0];
if (isset($frame['file']) && $frame['file']==__FILE__)
array_shift($trace);
}
$debug=$this->hive['DEBUG'];
$trace=array_filter(
$trace,
function($frame) use($debug) {
return isset($frame['file']) &&
($debug>1 ||
(($frame['file']!=__FILE__ || $debug) &&
(empty($frame['function']) ||
!preg_match('/^(?:(?:trigger|user)_error|'.
'__call|call_user_func)/',$frame['function']))));
}
);
if (!$format)
return $trace;
$out='';
$eol="\n";
// Analyze stack trace
foreach ($trace as $frame) {
$line='';
if (isset($frame['class']))
$line.=$frame['class'].$frame['type'];
if (isset($frame['function']))
$line.=$frame['function'].'('.
($debug>2 && isset($frame['args'])?
$this->csv($frame['args']):'').')';
$src=$this->fixslashes(str_replace($_SERVER['DOCUMENT_ROOT'].
'/','',$frame['file'])).':'.$frame['line'];
$out.='['.$src.'] '.$line.$eol;
}
return $out;
}
/**
* Log error; Execute ONERROR handler if defined, else display
* default error page (HTML for synchronous requests, JSON string
* for AJAX requests)
* @param $code int
* @param $text string
* @param $trace array
* @param $level int
**/
function error($code,$text='',?array $trace=NULL,$level=0) {
$prior=$this->hive['ERROR'];
$header=$this->status($code);
$req=$this->hive['VERB'].' '.$this->hive['PATH'];
if ($this->hive['QUERY'])
$req.='?'.$this->hive['QUERY'];
if (!$text)
$text='HTTP '.$code.' ('.$req.')';
$trace=$this->trace($trace);
$loggable=$this->hive['LOGGABLE'];
if (!is_array($loggable))
$loggable=$this->split($loggable);
foreach ($loggable as $status)
if ($status=='*' ||
preg_match('/^'.preg_replace('/\D/','\d',$status).'$/',(string) $code)) {
error_log($text);
foreach (explode("\n",$trace) as $nexus)
if ($nexus)
error_log($nexus);
break;
}
if ($highlight=(!$this->hive['CLI'] && !$this->hive['AJAX'] &&
$this->hive['HIGHLIGHT'] && is_file($css=__DIR__.'/'.self::CSS)))
$trace=$this->highlight($trace);
$this->hive['ERROR']=[
'status'=>$header,
'code'=>$code,
'text'=>$text,
'trace'=>$trace,
'level'=>$level
];
$this->expire(-1);
$handler=$this->hive['ONERROR'];
$this->hive['ONERROR']=NULL;
$eol="\n";
if ((!$handler ||
$this->call($handler,[$this,$this->hive['PARAMS']],
'beforeroute,afterroute')===FALSE) &&
!$prior && !$this->hive['QUIET']) {
$error=array_diff_key(
$this->hive['ERROR'],
$this->hive['DEBUG']?
[]:
['trace'=>1]
);
if ($this->hive['CLI'])
echo PHP_EOL.'==================================='.PHP_EOL.
'ERROR '.$error['code'].' - '.$error['status'].PHP_EOL.
$error['text'].PHP_EOL.PHP_EOL.(isset($error['trace']) ? $error['trace'] : '');
else
echo $this->hive['AJAX']?
json_encode($error):
('<!DOCTYPE html>'.$eol.
'<html>'.$eol.
'<head>'.
'<title>'.$code.' '.$header.'</title>'.
($highlight?
('<style>'.$this->read($css).'</style>'):'').
'</head>'.$eol.
'<body>'.$eol.
'<h1>'.$header.'</h1>'.$eol.
'<p>'.$this->encode($text?:$req).'</p>'.$eol.
($this->hive['DEBUG']?('<pre>'.$trace.'</pre>'.$eol):'').
'</body>'.$eol.
'</html>');
}
if ($this->hive['HALT'])
die(1);
}
/**
* Mock HTTP request
* @return mixed
* @param $pattern string
* @param $args array
* @param $headers array
* @param $body string
**/
function mock($pattern,
?array $args=NULL,?array $headers=NULL,$body=NULL) {
if (!$args)
$args=[];
$types=['sync','ajax','cli'];
preg_match('/([\|\w]+)\h+(?:@(\w+)(?:(\(.+?)\))*|([^\h]+))'.
'(?:\h+\[('.implode('|',$types).')\])?/',$pattern,$parts);
$verb=strtoupper($parts[1]);
if ($parts[2]) {
if (empty($this->hive['ALIASES'][$parts[2]]))
throw new \Exception(sprintf(self::E_Named,$parts[2]));
$parts[4]=$this->hive['ALIASES'][$parts[2]];
$parts[4]=$this->build($parts[4],
isset($parts[3])?$this->parse($parts[3]):[]);
}
if (empty($parts[4]))
throw new \Exception(sprintf(self::E_Pattern,$pattern));
$url=parse_url($parts[4]);
parse_str(isset($url['query'])?$url['query']:'',$GLOBALS['_GET']);
if (preg_match('/GET|HEAD/',$verb))
$GLOBALS['_GET']=array_merge($GLOBALS['_GET'],$args);
$GLOBALS['_POST']=$verb=='POST'?$args:[];
$GLOBALS['_REQUEST']=array_merge($GLOBALS['_GET'],$GLOBALS['_POST']);
foreach ($headers?:[] as $key=>$val)
$_SERVER['HTTP_'.strtr(strtoupper($key),'-','_')]=$val;
$this->hive['VERB']=$verb;
$this->hive['PATH']=$url['path'];
$this->hive['URI']=$this->hive['BASE'].$url['path'];
if ($GLOBALS['_GET'])
$this->hive['URI'].='?'.http_build_query($GLOBALS['_GET']);
$this->hive['BODY']='';
if (!preg_match('/GET|HEAD/',$verb))
$this->hive['BODY']=$body?:http_build_query($args);
$this->hive['AJAX']=isset($parts[5]) &&
preg_match('/ajax/i',$parts[5]);
$this->hive['CLI']=isset($parts[5]) &&
preg_match('/cli/i',$parts[5]);
return $this->run();
}
/**
* Assemble url from alias name
* @return string
* @param $name string
* @param $params array|string
* @param $query string|array
* @param $fragment string
**/
function alias($name,$params=[],$query=NULL,$fragment=NULL) {
if (!is_array($params))
$params=$this->parse($params);
if (empty($this->hive['ALIASES'][$name]))
throw new \Exception(sprintf(self::E_Named,$name));
$url=$this->build($this->hive['ALIASES'][$name],$params);
if (is_array($query))
$query=http_build_query($query);
return $url.($query?('?'.$query):'').($fragment?'#'.$fragment:'');
}
/**
* Bind handler to route pattern
* @return NULL
* @param $pattern string|array
* @param $handler callback
* @param $ttl int
* @param $kbps int
**/
function route($pattern,$handler,$ttl=0,$kbps=0) {
$types=['sync','ajax','cli'];
$alias=null;
if (is_array($pattern)) {
foreach ($pattern as $item)
$this->route($item,$handler,$ttl,$kbps);
return;
}
preg_match('/([\|\w]+)\h+(?:(?:@?(.+?)\h*:\h*)?(@(\w+)|[^\h]+))'.
'(?:\h+\[('.implode('|',$types).')\])?/u',$pattern,$parts);
if (isset($parts[2]) && $parts[2]) {
if (!preg_match('/^\w+$/',$parts[2]))
throw new \Exception(sprintf(self::E_Alias,$parts[2]));
$this->hive['ALIASES'][$alias=$parts[2]]=$parts[3];
}
elseif (!empty($parts[4])) {
if (empty($this->hive['ALIASES'][$parts[4]]))
throw new \Exception(sprintf(self::E_Named,$parts[4]));
$parts[3]=$this->hive['ALIASES'][$alias=$parts[4]];
}
if (empty($parts[3]))
throw new \Exception(sprintf(self::E_Pattern,$pattern));
$type=empty($parts[5])?0:constant('self::REQ_'.strtoupper($parts[5]));
foreach ($this->split($parts[1]) as $verb) {
if (!preg_match('/'.self::VERBS.'/',$verb))
$this->error(501,$verb.' '.$this->hive['URI']);
$this->hive['ROUTES'][$parts[3]][$type][strtoupper($verb)]=
[is_string($handler) ? trim($handler) : $handler,$ttl,$kbps,$alias];
}
}
/**
* Reroute to specified URI
* @return NULL
* @param $url array|string
* @param $permanent bool
* @param $die bool
**/
function reroute($url=NULL,$permanent=FALSE,$die=TRUE) {
if (!$url)
$url=$this->hive['REALM'];
if (is_array($url))
$url=call_user_func_array([$this,'alias'],$url);
elseif (preg_match('/^(?:@([^\/()?#]+)(?:\((.+?)\))*(\?[^#]+)*(#.+)*)/',
$url,$parts) && isset($this->hive['ALIASES'][$parts[1]]))
$url=$this->build($this->hive['ALIASES'][$parts[1]],
isset($parts[2])?$this->parse($parts[2]):[]).
(isset($parts[3])?$parts[3]:'').(isset($parts[4])?$parts[4]:'');
else
$url=$this->build($url);
if (($handler=$this->hive['ONREROUTE']) &&
$this->call($handler,[$url,$permanent,$die])!==FALSE)
return;
if ($url[0]!='/' && !preg_match('/^\w+:\/\//i',$url))
$url='/'.$url;
if ($url[0]=='/' && (empty($url[1]) || $url[1]!='/')) {
$port=$this->hive['PORT'];
$port=in_array($port,[80,443])?'':(':'.$port);
$url=$this->hive['SCHEME'].'://'.
$this->hive['HOST'].$port.$this->hive['BASE'].$url;
}
if ($this->hive['CLI'])
$this->mock('GET '.$url.' [cli]');
else {
header('Location: '.$url);
$this->status($permanent?301:302);
if ($die)
die;
}
}
/**
* Provide ReST interface by mapping HTTP verb to class method
* @return NULL
* @param $url string
* @param $class string|object
* @param $ttl int
* @param $kbps int
**/
function map($url,$class,$ttl=0,$kbps=0) {
if (is_array($url)) {
foreach ($url as $item)
$this->map($item,$class,$ttl,$kbps);
return;
}
foreach (explode('|',self::VERBS) as $method)
$this->route($method.' '.$url,is_string($class)?
$class.'->'.$this->hive['PREMAP'].strtolower($method):
[$class,$this->hive['PREMAP'].strtolower($method)],
$ttl,$kbps);
}
/**
* Redirect a route to another URL
* @return NULL
* @param $pattern string|array
* @param $url string
* @param $permanent bool
*/
function redirect($pattern,$url,$permanent=TRUE) {
if (is_array($pattern)) {
foreach ($pattern as $item)
$this->redirect($item,$url,$permanent);
return;
}
$this->route($pattern,function($fw) use($url,$permanent) {
$fw->reroute($url,$permanent);
});
}
/**
* Return TRUE if IPv4 address exists in DNSBL
* @return bool
* @param $ip string
**/
function blacklisted($ip) {
if ($this->hive['DNSBL'] &&
!in_array($ip,
is_array($this->hive['EXEMPT'])?
$this->hive['EXEMPT']:
$this->split($this->hive['EXEMPT']))) {
// Reverse IPv4 dotted quad
$rev=implode('.',array_reverse(explode('.',$ip)));
foreach (is_array($this->hive['DNSBL'])?
$this->hive['DNSBL']:
$this->split($this->hive['DNSBL']) as $server)
// DNSBL lookup
if (checkdnsrr($rev.'.'.$server,'A'))
return TRUE;
}
return FALSE;
}
/**
* Applies the specified URL mask and returns parameterized matches
* @return $args array
* @param $pattern string
* @param $url string|NULL
**/
function mask($pattern,$url=NULL) {
if (!$url)
$url=$this->rel($this->hive['URI']);
$case=$this->hive['CASELESS']?'i':'';
$wild=preg_quote($pattern,'/');
$i=0;
while (is_int($pos=strpos($wild,'\*'))) {
$wild=substr_replace($wild,'(?P<_'.$i.'>[^\?]*)',$pos,2);
++$i;
}
preg_match('/^'.
preg_replace(
'/((\\\{)?@(\w+\b)(?(2)\\\}))/',
'(?P<\3>[^\/\?]+)',
$wild).'\/?$/'.$case.'um',$url,$args);
foreach (array_keys($args) as $key) {
if (preg_match('/^_\d+$/',$key)) {
if (empty($args['*']))
$args['*']=$args[$key];
else {
if (is_string($args['*']))
$args['*']=[$args['*']];
array_push($args['*'],$args[$key]);
}
unset($args[$key]);
}
elseif (is_numeric($key) && $key)
unset($args[$key]);
}
return $args;
}
/**
* Match routes against incoming URI
* @return mixed
**/
function run() {
if ($this->blacklisted($this->hive['IP']))
// Spammer detected
$this->error(403);
if (!$this->hive['ROUTES'])
// No routes defined
throw new \Exception(self::E_Routes);
// Match specific routes first
$paths=[];
foreach ($keys=array_keys($this->hive['ROUTES']) as $key) {
$path=preg_replace('/@\w+/','*@',$key);
if (substr($path,-1)!='*')
$path.='+';
$paths[]=$path;
}
$vals=array_values($this->hive['ROUTES']);
array_multisort($paths,SORT_DESC,$keys,$vals);
$this->hive['ROUTES']=array_combine($keys,$vals);
// Convert to BASE-relative URL
$req=urldecode($this->hive['PATH']);
$preflight=FALSE;
if ($cors=(isset($this->hive['HEADERS']['Origin']) &&
$this->hive['CORS']['origin'])) {
$cors=$this->hive['CORS'];
header('Access-Control-Allow-Origin: '.$cors['origin']);
header('Access-Control-Allow-Credentials: '.
$this->export($cors['credentials']));
$preflight=
isset($this->hive['HEADERS']['Access-Control-Request-Method']);
}
$allowed=[];
foreach ($this->hive['ROUTES'] as $pattern=>$routes) {
if (!$args=$this->mask($pattern,$req))
continue;
ksort($args);
$route=NULL;
$ptr=$this->hive['CLI']?self::REQ_CLI:$this->hive['AJAX']+1;
if (isset($routes[$ptr][$this->hive['VERB']]) ||
($preflight && isset($routes[$ptr])) ||
isset($routes[$ptr=0]))
$route=$routes[$ptr];
if (!$route)
continue;
if (isset($route[$this->hive['VERB']]) && !$preflight) {
if ($this->hive['REROUTE_TRAILING_SLASH']===TRUE &&
$this->hive['VERB']=='GET' &&
preg_match('/.+\/$/',$this->hive['PATH']))
$this->reroute(substr($this->hive['PATH'],0,-1).
($this->hive['QUERY']?('?'.$this->hive['QUERY']):''));
list($handler,$ttl,$kbps,$alias)=$route[$this->hive['VERB']];
// Capture values of route pattern tokens
$this->hive['PARAMS']=$args;
// Save matching route
$this->hive['ALIAS']=$alias;
$this->hive['PATTERN']=$pattern;
if ($cors && $cors['expose'])
header('Access-Control-Expose-Headers: '.
(is_array($cors['expose'])?
implode(',',$cors['expose']):$cors['expose']));
if (is_string($handler)) {
// Replace route pattern tokens in handler if any
$handler=preg_replace_callback('/({)?@(\w+\b)(?(1)})/',
function($id) use($args) {
$pid=count($id)>2?2:1;
return isset($args[$id[$pid]])?
$args[$id[$pid]]:
$id[0];
},
$handler
);
if (preg_match('/(.+)\h*(?:->|::)/',$handler,$match) &&
!class_exists($match[1]))
$this->error(404);
}
// Process request
$result=NULL;
$body='';
$now=microtime(TRUE);
if (preg_match('/GET|HEAD/',$this->hive['VERB']) && $ttl) {
// Only GET and HEAD requests are cacheable
$headers=$this->hive['HEADERS'];
$cache=Cache::instance();
$cached=$cache->exists(
$hash=$this->hash($this->hive['VERB'].' '.
$this->hive['URI']).'.url',$data);
if ($cached) {
if (isset($headers['If-Modified-Since']) &&
strtotime($headers['If-Modified-Since'])+
$ttl>$now) {
$this->status(304);
die;
}
// Retrieve from cache backend
list($headers,$body,$result)=$data;
if (!$this->hive['CLI'])
array_walk($headers,'header');
$this->expire($cached[0]+$ttl-$now);
}
else
// Expire HTTP client-cached page
$this->expire($ttl);
}
else
$this->expire(0);
if (!strlen($body)) {
if (!$this->hive['RAW'] && !$this->hive['BODY'])
$this->hive['BODY']=file_get_contents('php://input');
ob_start();
// Call route handler
$result=$this->call($handler,[$this,$args,$handler],
'beforeroute,afterroute');
$body=ob_get_clean();
if (isset($cache) && !error_get_last()) {
// Save to cache backend
$cache->set($hash,[
// Remove cookies
preg_grep('/Set-Cookie\:/',headers_list(),
PREG_GREP_INVERT),$body,$result],$ttl);
}
}
$this->hive['RESPONSE']=$body;
if (!$this->hive['QUIET']) {
if ($kbps) {
$ctr=0;
foreach (str_split($body,1024) as $part) {
// Throttle output
++$ctr;
if ($ctr/$kbps>($elapsed=microtime(TRUE)-$now) &&
!connection_aborted())
usleep(round(1e6*($ctr/$kbps-$elapsed)));
echo $part;
}
}
else
echo $body;
}
if ($result || $this->hive['VERB']!='OPTIONS')
return $result;
}
$allowed=array_merge($allowed,array_keys($route));
}
if (!$allowed)
// URL doesn't match any route
$this->error(404);
elseif (!$this->hive['CLI']) {
if (!preg_grep('/Allow:/',$headers_send=headers_list()))
// Unhandled HTTP method
header('Allow: '.implode(',',array_unique($allowed)));
if ($cors) {
if (!preg_grep('/Access-Control-Allow-Methods:/',$headers_send))
header('Access-Control-Allow-Methods: OPTIONS,'.
implode(',',$allowed));
if ($cors['headers'] &&
!preg_grep('/Access-Control-Allow-Headers:/',$headers_send))
header('Access-Control-Allow-Headers: '.
(is_array($cors['headers'])?
implode(',',$cors['headers']):
$cors['headers']));
if ($cors['ttl']>0)
header('Access-Control-Max-Age: '.$cors['ttl']);
}
if ($this->hive['VERB']!='OPTIONS')
$this->error(405);
}
return FALSE;
}
/**
* Loop until callback returns TRUE (for long polling)
* @return mixed
* @param $func callback
* @param $args array
* @param $timeout int
**/
function until($func,$args=NULL,$timeout=60) {
if (!$args)
$args=[];
$time=time();
$max=ini_get('max_execution_time');
$limit=max(0,($max?min($timeout,$max):$timeout)-1);
$out='';
// Turn output buffering on
ob_start();
// Not for the weak of heart
while (
// No error occurred
!$this->hive['ERROR'] &&
// Got time left?
time()-$time+1<$limit &&
// Still alive?
!connection_aborted() &&
// Restart session
!headers_sent() &&
(session_status()==PHP_SESSION_ACTIVE || session_start()) &&
// CAUTION: Callback will kill host if it never becomes truthy!
!$out=$this->call($func,$args)) {
if (!$this->hive['CLI'])
session_commit();
// Hush down
sleep(1);
}
ob_flush();
flush();
return $out;
}
/**
* Disconnect HTTP client;
* Set FcgidOutputBufferSize to zero if server uses mod_fcgid;
* Disable mod_deflate when rendering text/html output
**/
function abort() {
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
$out='';
while (ob_get_level())
$out=ob_get_clean().$out;
if (!headers_sent()) {
header('Content-Length: '.strlen($out));
header('Connection: close');
}
session_commit();
echo $out;
flush();
if (function_exists('fastcgi_finish_request'))
fastcgi_finish_request();
}
/**
* Grab the real route handler behind the string expression
* @return string|array
* @param $func string
* @param $args array
**/
function grab($func,$args=NULL) {
if (preg_match('/(.+)\h*(->|::)\h*(.+)/s',$func,$parts)) {
// Convert string to executable PHP callback
if (!class_exists($parts[1]))
throw new \Exception(sprintf(self::E_Class,$parts[1]));
if ($parts[2]=='->') {
if (is_subclass_of($parts[1],'Prefab'))
$parts[1]=call_user_func($parts[1].'::instance');
elseif (isset($this->hive['CONTAINER'])) {
$container=$this->hive['CONTAINER'];
if (is_object($container) && is_callable([$container,'has'])
&& $container->has($parts[1])) // PSR11
$parts[1]=call_user_func([$container,'get'],$parts[1]);
elseif (is_callable($container))
$parts[1]=call_user_func($container,$parts[1],$args);
elseif (is_string($container) &&
is_subclass_of($container,'Prefab'))
$parts[1]=call_user_func($container.'::instance')->
get($parts[1]);
else
throw new \Exception(sprintf(self::E_Class,
$this->stringify($parts[1])));
}
else {
$ref=new ReflectionClass($parts[1]);
$parts[1]=method_exists($parts[1],'__construct') && $args?
$ref->newinstanceargs($args):
$ref->newinstance();
}
}
$func=[$parts[1],$parts[3]];
}
return $func;
}
/**
* Execute callback/hooks (supports 'class->method' format)
* @return mixed|FALSE
* @param $func callback
* @param $args mixed
* @param $hooks string
**/
function call($func,$args=NULL,$hooks='') {
if (!is_array($args))
$args=[$args];
// Grab the real handler behind the string representation
if (is_string($func))
$func=$this->grab($func,$args);
// Execute function; abort if callback/hook returns FALSE
if (!is_callable($func))
// No route handler
if ($hooks=='beforeroute,afterroute') {
$allowed=[];
if (is_array($func))
$allowed=array_intersect(
array_map('strtoupper',get_class_methods($func[0])),
explode('|',self::VERBS)
);
header('Allow: '.implode(',',$allowed));
$this->error(405);
}
else
throw new \Exception(sprintf(self::E_Method,
is_string($func)?$func:$this->stringify($func)));
$obj=FALSE;
if (is_array($func)) {
$hooks=$this->split($hooks);
$obj=TRUE;
}
// Execute pre-route hook if any
if ($obj && $hooks && in_array($hook='beforeroute',$hooks) &&
method_exists($func[0],$hook) &&
call_user_func_array([$func[0],$hook],$args)===FALSE)
return FALSE;
// Execute callback
$out=call_user_func_array($func,$args?:[]);
if ($out===FALSE)
return FALSE;
// Execute post-route hook if any
if ($obj && $hooks && in_array($hook='afterroute',$hooks) &&
method_exists($func[0],$hook) &&
call_user_func_array([$func[0],$hook],$args)===FALSE)
return FALSE;
return $out;
}
/**
* Execute specified callbacks in succession; Apply same arguments
* to all callbacks
* @return array
* @param $funcs array|string
* @param $args mixed
**/
function chain($funcs,$args=NULL) {
$out=[];
foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func)
$out[]=$this->call($func,$args);
return $out;
}
/**
* Execute specified callbacks in succession; Relay result of
* previous callback as argument to the next callback
* @return array
* @param $funcs array|string
* @param $args mixed
**/
function relay($funcs,$args=NULL) {
foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func)
$args=[$this->call($func,$args)];
return array_shift($args);
}
/**
* Configure framework according to .ini-style file settings;
* If optional 2nd arg is provided, template strings are interpreted
* @return object
* @param $source string|array
* @param $allow bool
**/
function config($source,$allow=FALSE) {
if (is_string($source))
$source=$this->split($source);
if ($allow)
$preview=Preview::instance();
foreach ($source as $file) {
preg_match_all(
'/(?<=^|\n)(?:'.
'\[(?<section>.+?)\]|'.
'(?<lval>[^\h\r\n;].*?)\h*=\h*'.
'(?<rval>(?:\\\\\h*\r?\n|.+?)*)'.
')(?=\r?\n|$)/',
$this->read($file),
$matches,PREG_SET_ORDER);
if ($matches) {
$sec='globals';
$cmd=[];
foreach ($matches as $match) {
if ($match['section']) {
$sec=$match['section'];
if (preg_match(
'/^(?!(?:global|config|route|map|redirect)s\b)'.
'(.*?)(?:\s*[:>])/i',$sec,$msec) &&
!$this->exists($msec[1]))
$this->set($msec[1],NULL);
preg_match('/^(config|route|map|redirect)s\b|'.
'^(.+?)\s*\>\s*(.*)/i',$sec,$cmd);
continue;
}
if ($allow)
foreach (['lval','rval'] as $ndx)
$match[$ndx]=$preview->
resolve($match[$ndx],NULL,0,FALSE,FALSE);
if (!empty($cmd)) {
isset($cmd[3])?
$this->call($cmd[3],
[$match['lval'],$match['rval'],$cmd[2]]):
call_user_func_array(
[$this,$cmd[1]],
array_merge([$match['lval']],
str_getcsv($cmd[1]=='config'?
$this->cast($match['rval']):
$match['rval'],",",'"', "\\"))
);
}
else {
$rval=preg_replace(
'/\\\\\h*(\r?\n)/','\1',$match['rval']);
$ttl=NULL;
if (preg_match('/^(.+)\|\h*(\d+)$/',$rval,$tmp)) {
array_shift($tmp);
list($rval,$ttl)=$tmp;
}
$args=array_map(
function($val) {
$val=$this->cast($val);
if (is_string($val))
$val=strlen($val)?
preg_replace('/\\\\"/','"',$val):
NULL;
return $val;
},
// Mark quoted strings with 0x00 whitespace
str_getcsv(preg_replace(
'/(?<!\\\\)(")(.*?)\1/',
"\\1\x00\\2\\1",trim($rval)),",",'"', "\\")
);
preg_match('/^(?<section>[^:]+)(?:\:(?<func>.+))?/',
$sec,$parts);
$func=isset($parts['func'])?$parts['func']:NULL;
$custom=(strtolower($parts['section'])!='globals');
if ($func)
$args=[$this->call($func,$args)];
if (count($args)>1)
$args=[$args];
if (isset($ttl))
$args=array_merge($args,[$ttl]);
call_user_func_array(
[$this,'set'],
array_merge(
[
($custom?($parts['section'].'.'):'').
$match['lval']
],
$args
)
);
}
}
}
}
return $this;
}
/**
* Create mutex, invoke callback then drop ownership when done
* @return mixed
* @param $id string
* @param $func callback
* @param $args mixed
**/
function mutex($id,$func,$args=NULL) {
if (!is_dir($tmp=$this->hive['TEMP']))
mkdir($tmp,self::MODE,TRUE);
// Use filesystem lock
if (is_file($lock=$tmp.
$this->hive['SEED'].'.'.$this->hash($id).'.lock') &&
filemtime($lock)+ini_get('max_execution_time')<microtime(TRUE))
// Stale lock
@unlink($lock);
while (!($handle=@fopen($lock,'x')) && !connection_aborted())
usleep(mt_rand(0,100));
$this->locks[$id]=$lock;
$out=$this->call($func,$args);
fclose($handle);
@unlink($lock);
unset($this->locks[$id]);
return $out;
}
/**
* Read file (with option to apply Unix LF as standard line ending)
* @return string
* @param $file string
* @param $lf bool
**/
function read($file, $lf = FALSE)
{
if (!file_exists($file)) {
return false;
}
$out = file_get_contents($file);
return $lf ? preg_replace('/\r\n|\r/', "\n", $out) : $out;
}
/**
* Exclusive file write
* @return int|FALSE
* @param $file string
* @param $data mixed
* @param $append bool
**/
function write($file,$data,$append=FALSE) {
return file_put_contents($file,$data,$this->hive['LOCK']|($append?FILE_APPEND:0));
}
/**
* Apply syntax highlighting
* @return string
* @param $text string
**/
function highlight($text) {
$out='';
$pre=FALSE;
$text=trim($text);
if ($text && !preg_match('/^<\?php/',$text)) {
$text='<?php '.$text;
$pre=TRUE;
}
foreach (token_get_all($text) as $token)
if ($pre)
$pre=FALSE;
else
$out.='<span'.
(is_array($token)?
(' class="'.
substr(strtolower(token_name($token[0])),2).'">'.
$this->encode($token[1]).''):
('>'.$this->encode($token))).
'</span>';
return $out?('<code>'.$out.'</code>'):$text;
}
/**
* Dump expression with syntax highlighting
* @param $expr mixed
**/
function dump($expr) {
echo $this->highlight($this->stringify($expr));
}
/**
* Return path (and query parameters) relative to the base directory
* @return string
* @param $url string
**/
function rel($url) {
return preg_replace('/^(?:https?:\/\/)?'.
preg_quote($this->hive['BASE'],'/').'(\/.*|$)/','\1',$url);
}
/**
* Namespace-aware class autoloader
* @return mixed
* @param $class string
**/
protected function autoload($class) {
$class=$this->fixslashes(ltrim($class,'\\'));
/** @var callable $func */
$func=NULL;
if (is_array($path=$this->hive['AUTOLOAD']) &&
isset($path[1]) && is_callable($path[1]))
list($path,$func)=$path;
foreach ($this->split($this->hive['PLUGINS'].';'.$path) as $auto)
if (($func && is_file($file=$func($auto.$class).'.php')) ||
is_file($file=$auto.$class.'.php') ||
is_file($file=$auto.strtolower($class).'.php') ||
is_file($file=strtolower($auto.$class).'.php'))
return require($file);
}
/**
* Execute framework/application shutdown sequence
* @param $cwd string
**/
function unload($cwd) {
chdir($cwd);
if (!($error=error_get_last()) &&
session_status()==PHP_SESSION_ACTIVE)
session_commit();
foreach ($this->locks as $lock)
@unlink($lock);
$handler=$this->hive['UNLOAD'];
if ((!$handler || $this->call($handler,$this)===FALSE) &&
$error && in_array($error['type'],
[E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR]))
// Fatal error detected
$this->error(500,
sprintf(self::E_Fatal,$error['message']),[$error]);
}
/**
* Convenience method for checking hive key
* @return mixed
* @param $key string
**/
#[\ReturnTypeWillChange]
function offsetexists($key) {
return $this->exists($key);
}
/**
* Convenience method for assigning hive value
* @return mixed
* @param $key string
* @param $val mixed
**/
#[\ReturnTypeWillChange]
function offsetset($key,$val) {
return $this->set($key,$val);
}
/**
* Convenience method for retrieving hive value
* @return mixed
* @param $key string
**/
#[\ReturnTypeWillChange]
function &offsetget($key) {
$val=&$this->ref($key);
return $val;
}
/**
* Convenience method for removing hive key
* @param $key string
**/
#[\ReturnTypeWillChange]
function offsetunset($key) {
$this->clear($key);
}
/**
* Alias for offsetexists()
* @return mixed
* @param $key string
**/
function __isset($key) {
return $this->offsetexists($key);
}
/**
* Alias for offsetset()
* @return mixed
* @param $key string
* @param $val mixed
**/
function __set($key,$val) {
return $this->offsetset($key,$val);
}
/**
* Alias for offsetget()
* @return mixed
* @param $key string
**/
function &__get($key) {
$val=&$this->offsetget($key);
return $val;
}
/**
* Alias for offsetunset()
* @param $key string
**/
function __unset($key) {
$this->offsetunset($key);
}
/**
* Call function identified by hive key
* @return mixed
* @param $key string
* @param $args array
**/
function __call($key,array $args) {
if ($this->exists($key,$val))
return call_user_func_array($val,$args);
throw new \Exception(sprintf(self::E_Method,$key));
}
//! Prohibit cloning
private function __clone() {
}
//! Bootstrap
function __construct() {
// Managed directives
ini_set('default_charset',$charset='UTF-8');
if (extension_loaded('mbstring'))
mb_internal_encoding($charset);
ini_set('display_errors',0);
// Deprecated directives
@ini_set('magic_quotes_gpc',0);
@ini_set('register_globals',0);
// Intercept errors/exceptions; PHP5.3-compatible
if (PHP_VERSION_ID >= 80400) {
$check = error_reporting((E_ALL) & ~(E_NOTICE | E_USER_NOTICE));
} else {
$check = error_reporting((E_ALL | E_STRICT) & ~(E_NOTICE | E_USER_NOTICE));
}
set_exception_handler(
function($obj) {
/** @var Exception $obj */
$this->hive['EXCEPTION']=$obj;
$this->error(500,
$obj->getmessage().' '.
'['.$obj->getFile().':'.$obj->getLine().']',
$obj->gettrace());
}
);
set_error_handler(
function($level,$text,$file,$line) {
if ($level & error_reporting()) {
$trace=$this->trace(null, false);
array_unshift($trace,['file'=>$file,'line'=>$line]);
$this->error(500,$text,$trace,$level);
}
}
);
if (!isset($_SERVER['SERVER_NAME']) || $_SERVER['SERVER_NAME']==='')
$_SERVER['SERVER_NAME']=gethostname();
$headers=[];
if ($cli=(PHP_SAPI=='cli')) {
// Emulate HTTP request
$_SERVER['REQUEST_METHOD']='GET';
if (!isset($_SERVER['argv'][1])) {
++$_SERVER['argc'];
$_SERVER['argv'][1]='/';
}
$req=$query='';
if (substr($_SERVER['argv'][1],0,1)=='/') {
$req=$_SERVER['argv'][1];
$query=parse_url($req,PHP_URL_QUERY);
} else {
foreach($_SERVER['argv'] as $i=>$arg) {
if (!$i) continue;
if (preg_match('/^\-(\-)?(\w+)(?:\=(.*))?$/',$arg,$m)) {
foreach($m[1]?[$m[2]]:str_split($m[2]) as $k)
$query.=($query?'&':'').urlencode($k).'=';
if (isset($m[3]))
$query.=urlencode($m[3]);
} else
$req.='/'.$arg;
}
if (!$req)
$req='/';
if ($query)
$req.='?'.$query;
}
$_SERVER['REQUEST_URI']=$req;
parse_str($query?:'',$GLOBALS['_GET']);
}
elseif (function_exists('getallheaders')) {
foreach (getallheaders() as $key=>$val) {
$tmp=strtoupper(strtr($key,'-','_'));
// TODO: use ucwords delimiters for php 5.4.32+ & 5.5.16+
$key=strtr(ucwords(strtolower(strtr($key,'-',' '))),' ','-');
$headers[$key]=$val;
if (isset($_SERVER['HTTP_'.$tmp]))
$headers[$key]=&$_SERVER['HTTP_'.$tmp];
}
}
else {
if (isset($_SERVER['CONTENT_LENGTH']))
$headers['Content-Length']=&$_SERVER['CONTENT_LENGTH'];
if (isset($_SERVER['CONTENT_TYPE']))
$headers['Content-Type']=&$_SERVER['CONTENT_TYPE'];
foreach (array_keys($_SERVER) as $key)
if (substr($key,0,5)=='HTTP_')
$headers[strtr(ucwords(strtolower(strtr(
substr($key,5),'_',' '))),' ','-')]=&$_SERVER[$key];
}
if (isset($headers['X-Http-Method-Override']))
$_SERVER['REQUEST_METHOD']=$headers['X-Http-Method-Override'];
elseif ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['_method']))
$_SERVER['REQUEST_METHOD']=strtoupper($_POST['_method']);
$scheme=isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ||
isset($headers['X-Forwarded-Proto']) &&
$headers['X-Forwarded-Proto']=='https'?'https':'http';
// Create hive early on to expose header methods
$this->hive=['HEADERS'=>&$headers];
if (function_exists('apache_setenv')) {
// Work around Apache pre-2.4 VirtualDocumentRoot bug
$_SERVER['DOCUMENT_ROOT']=str_replace($_SERVER['SCRIPT_NAME'],'',
$_SERVER['SCRIPT_FILENAME']);
apache_setenv("DOCUMENT_ROOT",$_SERVER['DOCUMENT_ROOT']);
}
$_SERVER['DOCUMENT_ROOT']=realpath($_SERVER['DOCUMENT_ROOT']);
$base='';
if (!$cli)
$base=rtrim($this->fixslashes(
dirname($_SERVER['SCRIPT_NAME'])),'/');
$uri=parse_url((preg_match('/^\w+:\/\//',$_SERVER['REQUEST_URI'])?'':
$scheme.'://'.$_SERVER['SERVER_NAME']).$_SERVER['REQUEST_URI']);
$_SERVER['REQUEST_URI']=$uri['path'].
(isset($uri['query'])?'?'.$uri['query']:'').
(isset($uri['fragment'])?'#'.$uri['fragment']:'');
$path=preg_replace('/^'.preg_quote($base,'/').'/','',$uri['path']);
$jar=[
'expire'=>0,
'lifetime'=>0,
'path'=>$base?:'/',
'domain'=>is_int(strpos($_SERVER['SERVER_NAME'],'.')) &&
!filter_var($_SERVER['SERVER_NAME'],FILTER_VALIDATE_IP)?
$_SERVER['SERVER_NAME']:'',
'secure'=>($scheme=='https'),
'httponly'=>TRUE,
'samesite'=>'Lax',
];
$port=80;
if (!empty($headers['X-Forwarded-Port']))
$port=$headers['X-Forwarded-Port'];
elseif (!empty($_SERVER['SERVER_PORT']))
$port=$_SERVER['SERVER_PORT'];
// Default configuration
$this->hive+=[
'AGENT'=>$this->agent(),
'AJAX'=>$this->ajax(),
'ALIAS'=>NULL,
'ALIASES'=>[],
'AUTOLOAD'=>'./',
'BASE'=>$base,
'BITMASK'=>ENT_COMPAT,
'BODY'=>NULL,
'CACHE'=>FALSE,
'CASELESS'=>TRUE,
'CLI'=>$cli,
'CORS'=>[],
'DEBUG'=>0,
'DIACRITICS'=>[],
'DNSBL'=>'',
'EMOJI'=>[],
'ENCODING'=>$charset,
'ERROR'=>NULL,
'ESCAPE'=>TRUE,
'EXCEPTION'=>NULL,
'EXEMPT'=>NULL,
'FALLBACK'=>$this->fallback,
'FORMATS'=>[],
'FRAGMENT'=>isset($uri['fragment'])?$uri['fragment']:'',
'HALT'=>TRUE,
'HIGHLIGHT'=>FALSE,
'HOST'=>$_SERVER['SERVER_NAME'],
'IP'=>$this->ip(),
'JAR'=>$jar,
'LANGUAGE'=>isset($headers['Accept-Language'])?
$this->language($headers['Accept-Language']):
$this->fallback,
'LOCALES'=>'./',
'LOCK'=>LOCK_EX,
'LOGGABLE'=>'*',
'LOGS'=>'./',
'MB'=>extension_loaded('mbstring'),
'ONERROR'=>NULL,
'ONREROUTE'=>NULL,
'PACKAGE'=>self::PACKAGE,
'PARAMS'=>[],
'PATH'=>$path,
'REROUTE_TRAILING_SLASH'=>TRUE,
'PATTERN'=>NULL,
'PLUGINS'=>$this->fixslashes(__DIR__).'/',
'PORT'=>$port,
'PREFIX'=>NULL,
'PREMAP'=>'',
'QUERY'=>isset($uri['query'])?$uri['query']:'',
'QUIET'=>FALSE,
'RAW'=>FALSE,
'REALM'=>$scheme.'://'.$_SERVER['SERVER_NAME'].
(!in_array($port,[80,443])?(':'.$port):'').
$_SERVER['REQUEST_URI'],
'RESPONSE'=>'',
'ROOT'=>$_SERVER['DOCUMENT_ROOT'],
'ROUTES'=>[],
'SCHEME'=>$scheme,
'SEED'=>$this->hash($_SERVER['SERVER_NAME'].$base),
'SERIALIZER'=>extension_loaded($ext='igbinary')?$ext:'php',
'TEMP'=>'tmp/',
'TIME'=>&$_SERVER['REQUEST_TIME_FLOAT'],
'TZ'=>@date_default_timezone_get(),
'UI'=>'./',
'UNLOAD'=>NULL,
'UPLOADS'=>'./',
'URI'=>&$_SERVER['REQUEST_URI'],
'VERB'=>&$_SERVER['REQUEST_METHOD'],
'VERSION'=>self::VERSION,
'XFRAME'=>'SAMEORIGIN'
];
$this->hive['CORS']+=[
'headers'=>'',
'origin'=>FALSE,
'credentials'=>FALSE,
'expose'=>FALSE,
'ttl'=>0
];
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE) {
unset($jar['expire']);
session_cache_limiter('');
if (version_compare(PHP_VERSION, '7.3.0') >= 0)
session_set_cookie_params($jar);
else {
unset($jar['samesite']);
call_user_func_array('session_set_cookie_params',$jar);
}
}
if (PHP_SAPI=='cli-server' &&
preg_match('/^'.preg_quote($base,'/').'$/',$this->hive['URI']))
$this->reroute('/');
if (ini_get('auto_globals_jit')) {
// Override setting
$GLOBALS['_ENV']=$_ENV;
$GLOBALS['_REQUEST']=$_REQUEST;
}
// Sync PHP globals with corresponding hive keys
$this->init=$this->hive;
foreach (explode('|',self::GLOBALS) as $global) {
$sync=$this->sync($global);
$this->init+=[
$global=>preg_match('/SERVER|ENV/',$global)?$sync:[]
];
}
if ($check && $error=error_get_last())
// Error detected
$this->error(500,
sprintf(self::E_Fatal,$error['message']),[$error]);
date_default_timezone_set($this->hive['TZ']);
// Register framework autoloader
spl_autoload_register([$this,'autoload']);
// Register shutdown handler
register_shutdown_function([$this,'unload'],getcwd());
}
}
//! Cache engine
class Cache extends Prefab {
protected
//! Cache DSN
$dsn,
//! Prefix for cache entries
$prefix,
//! MemCache or Redis object
$ref;
/**
* Return timestamp and TTL of cache entry or FALSE if not found
* @return array|FALSE
* @param $key string
* @param $val mixed
**/
function exists($key,&$val=NULL) {
$fw=Base::instance();
if (!$this->dsn)
return FALSE;
$ndx=$this->prefix.'.'.$key;
$parts=explode('=',$this->dsn,2);
switch ($parts[0]) {
case 'apc':
case 'apcu':
$raw=call_user_func($parts[0].'_fetch',$ndx);
break;
case 'redis':
$raw=$this->ref->get($ndx);
break;
case 'memcache':
$raw=memcache_get($this->ref,$ndx);
break;
case 'memcached':
$raw=$this->ref->get($ndx);
break;
case 'wincache':
$raw=wincache_ucache_get($ndx);
break;
case 'xcache':
$raw=xcache_get($ndx);
break;
case 'folder':
$raw=$fw->read($parts[1]
.str_replace(['/','\\'],'',$ndx));
break;
}
if (!empty($raw)) {
list($val,$time,$ttl)=(array)$fw->unserialize($raw);
if ($ttl===0 || $time+$ttl>microtime(TRUE))
return [$time,$ttl];
$val=null;
$this->clear($key);
}
return FALSE;
}
/**
* Store value in cache
* @return mixed|FALSE
* @param $key string
* @param $val mixed
* @param $ttl int
**/
function set($key,$val,$ttl=0) {
$fw=Base::instance();
if (!$this->dsn)
return TRUE;
$ndx=$this->prefix.'.'.$key;
if ($cached=$this->exists($key))
$ttl=$cached[1];
$data=$fw->serialize([$val,microtime(TRUE),$ttl]);
$parts=explode('=',$this->dsn,2);
switch ($parts[0]) {
case 'apc':
case 'apcu':
return call_user_func($parts[0].'_store',$ndx,$data,$ttl);
case 'redis':
return $this->ref->set($ndx,$data,$ttl?['ex'=>$ttl]:[]);
case 'memcache':
return memcache_set($this->ref,$ndx,$data,0,$ttl);
case 'memcached':
return $this->ref->set($ndx,$data,$ttl);
case 'wincache':
return wincache_ucache_set($ndx,$data,$ttl);
case 'xcache':
return xcache_set($ndx,$data,$ttl);
case 'folder':
return $fw->write($parts[1].
str_replace(['/','\\'],'',$ndx),$data);
}
return FALSE;
}
/**
* Retrieve value of cache entry
* @return mixed|FALSE
* @param $key string
**/
function get($key) {
return $this->dsn && $this->exists($key,$data)?$data:FALSE;
}
/**
* Delete cache entry
* @return bool
* @param $key string
**/
function clear($key) {
if (!$this->dsn)
return;
$ndx=$this->prefix.'.'.$key;
$parts=explode('=',$this->dsn,2);
switch ($parts[0]) {
case 'apc':
case 'apcu':
return call_user_func($parts[0].'_delete',$ndx);
case 'redis':
return $this->ref->del($ndx);
case 'memcache':
return memcache_delete($this->ref,$ndx);
case 'memcached':
return $this->ref->delete($ndx);
case 'wincache':
return wincache_ucache_delete($ndx);
case 'xcache':
return xcache_unset($ndx);
case 'folder':
return @unlink($parts[1].$ndx);
}
return FALSE;
}
/**
* Clear contents of cache backend
* @return bool
* @param $suffix string
**/
function reset($suffix=NULL) {
if (!$this->dsn)
return TRUE;
$regex='/'.preg_quote($this->prefix.'.','/').'.*'.
preg_quote($suffix?:'','/').'/';
$parts=explode('=',$this->dsn,2);
switch ($parts[0]) {
case 'apc':
case 'apcu':
$info=call_user_func($parts[0].'_cache_info',
$parts[0]=='apcu'?FALSE:'user');
if (!empty($info['cache_list'])) {
$key=array_key_exists('info',
$info['cache_list'][0])?'info':'key';
foreach ($info['cache_list'] as $item)
if (preg_match($regex,$item[$key]))
call_user_func($parts[0].'_delete',$item[$key]);
}
return TRUE;
case 'redis':
$keys=$this->ref->keys($this->prefix.'.*'.$suffix);
foreach($keys as $key)
$this->ref->del($key);
return TRUE;
case 'memcache':
foreach (memcache_get_extended_stats(
$this->ref,'slabs') as $slabs)
foreach (array_filter(array_keys($slabs),'is_numeric')
as $id)
foreach (memcache_get_extended_stats(
$this->ref,'cachedump',$id) as $data)
if (is_array($data))
foreach (array_keys($data) as $key)
if (preg_match($regex,$key))
memcache_delete($this->ref,$key);
return TRUE;
case 'memcached':
foreach ($this->ref->getallkeys()?:[] as $key)
if (preg_match($regex,$key))
$this->ref->delete($key);
return TRUE;
case 'wincache':
$info=wincache_ucache_info();
foreach ($info['ucache_entries'] as $item)
if (preg_match($regex,$item['key_name']))
wincache_ucache_delete($item['key_name']);
return TRUE;
case 'xcache':
if ($suffix && !ini_get('xcache.admin.enable_auth')) {
$cnt=xcache_count(XC_TYPE_VAR);
for ($i=0;$i<$cnt;++$i) {
$list=xcache_list(XC_TYPE_VAR,$i);
foreach ($list['cache_list'] as $item)
if (preg_match($regex,$item['name']))
xcache_unset($item['name']);
}
} else
xcache_unset_by_prefix($this->prefix.'.');
return TRUE;
case 'folder':
if ($glob=@glob($parts[1].'*'))
foreach ($glob as $file)
if (preg_match($regex,basename($file)))
@unlink($file);
return TRUE;
}
return FALSE;
}
/**
* Load/auto-detect cache backend
* @return string
* @param $dsn bool|string
* @param $seed bool|string
**/
function load($dsn,$seed=NULL) {
$fw=Base::instance();
if ($dsn=trim($dsn)) {
if (preg_match('/^redis=(.+)/',$dsn,$parts) &&
extension_loaded('redis')) {
list($host,$port,$db,$password)=explode(':',$parts[1])+[1=>6379,2=>NULL,3=>NULL];
$this->ref=new Redis;
if(!$this->ref->connect($host,$port,2))
$this->ref=NULL;
if(!empty($password))
$this->ref->auth($password);
if(isset($db))
$this->ref->select($db);
}
elseif (preg_match('/^memcache=(.+)/',$dsn,$parts) &&
extension_loaded('memcache'))
foreach ($fw->split($parts[1]) as $server) {
list($host,$port)=explode(':',$server)+[1=>11211];
if (empty($this->ref))
$this->ref=@memcache_connect($host,$port)?:NULL;
else
memcache_add_server($this->ref,$host,$port);
}
elseif (preg_match('/^memcached=(.+)/',$dsn,$parts) &&
extension_loaded('memcached'))
foreach ($fw->split($parts[1]) as $server) {
list($host,$port)=explode(':',$server)+[1=>11211];
if (empty($this->ref))
$this->ref=new Memcached();
$this->ref->addServer($host,$port);
}
if (empty($this->ref) && !preg_match('/^folder\h*=/',$dsn))
$dsn=($grep=preg_grep('/^(apc|wincache|xcache)/',
array_map('strtolower',get_loaded_extensions())))?
// Auto-detect
current($grep):
// Use filesystem as fallback
('folder='.$fw->TEMP.'cache/');
if (preg_match('/^folder\h*=\h*(.+)/',$dsn,$parts) &&
!is_dir($parts[1]))
mkdir($parts[1],Base::MODE,TRUE);
}
$this->prefix=$seed?:$fw->SEED;
return $this->dsn=$dsn;
}
/**
* Class constructor
* @param $dsn bool|string
**/
function __construct($dsn=FALSE) {
if ($dsn)
$this->load($dsn);
}
}
//! View handler
class View extends Prefab {
private
//! Temporary hive
$temp;
protected
//! Template file
$file,
//! Post-rendering handler
$trigger,
//! Nesting level
$level=0;
/** @var \Base Framework instance */
protected $fw;
function __construct() {
$this->fw=\Base::instance();
}
/**
* Encode characters to equivalent HTML entities
* @return string
* @param $arg mixed
**/
function esc($arg) {
return $this->fw->recursive($arg,
function($val) {
return is_string($val)?$this->fw->encode($val):$val;
}
);
}
/**
* Decode HTML entities to equivalent characters
* @return string
* @param $arg mixed
**/
function raw($arg) {
return $this->fw->recursive($arg,
function($val) {
return is_string($val)?$this->fw->decode($val):$val;
}
);
}
/**
* Create sandbox for template execution
* @return string
* @param $hive array
* @param $mime string
**/
protected function sandbox(?array $hive=NULL,$mime=NULL) {
$fw=$this->fw;
$implicit=FALSE;
if (is_null($hive)) {
$implicit=TRUE;
$hive=$fw->hive();
}
if ($this->level<1 || $implicit) {
if (!$fw->CLI && $mime && !headers_sent() &&
!preg_grep ('/^Content-Type:/',headers_list()))
header('Content-Type: '.$mime.'; '.
'charset='.$fw->ENCODING);
if ($fw->ESCAPE && (!$mime ||
preg_match('/^(text\/html|(application|text)\/(.+\+)?xml)$/i',$mime)))
$hive=$this->esc($hive);
if (isset($hive['ALIASES']))
$hive['ALIASES']=$fw->build($hive['ALIASES']);
}
$this->temp=$hive;
unset($fw,$hive,$implicit,$mime);
extract($this->temp);
$this->temp=NULL;
++$this->level;
ob_start();
require($this->file);
--$this->level;
return ob_get_clean();
}
/**
* Render template
* @return string
* @param $file string
* @param $mime string
* @param $hive array
* @param $ttl int
**/
function render($file,$mime='text/html',?array $hive=NULL,$ttl=0) {
$fw=$this->fw;
$cache=Cache::instance();
foreach ($fw->split($fw->UI) as $dir) {
if ($cache->exists($hash=$fw->hash($dir.$file),$data))
return $data;
if (is_file($this->file=$fw->fixslashes($dir.$file))) {
if (isset($_COOKIE[session_name()]) &&
!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
$fw->sync('SESSION');
$data=$this->sandbox($hive,$mime);
if (isset($this->trigger['afterrender']))
foreach($this->trigger['afterrender'] as $func)
$data=$fw->call($func,[$data, $dir.$file]);
if ($ttl)
$cache->set($hash,$data,$ttl);
return $data;
}
}
throw new \Exception(sprintf(Base::E_Open,$file));
}
/**
* post rendering handler
* @param $func callback
*/
function afterrender($func) {
$this->trigger['afterrender'][]=$func;
}
}
//! Lightweight template engine
class Preview extends View {
protected
//! token filter
$filter=[
'c'=>'$this->c',
'esc'=>'$this->esc',
'raw'=>'$this->raw',
'export'=>'Base::instance()->export',
'alias'=>'Base::instance()->alias',
'format'=>'Base::instance()->format'
];
protected
//! newline interpolation
$interpolation=true;
/**
* Enable/disable markup parsing interpolation
* mainly used for adding appropriate newlines
* @param $bool bool
*/
function interpolation($bool) {
$this->interpolation=$bool;
}
/**
* Return C-locale equivalent of number
* @return string
* @param $val int|float
**/
function c($val) {
$locale=setlocale(LC_NUMERIC,0);
setlocale(LC_NUMERIC,'C');
$out=(string)(float)$val;
$locale=setlocale(LC_NUMERIC,$locale);
return $out;
}
/**
* Convert token to variable
* @return string
* @param $str string
**/
function token($str) {
$str=trim(preg_replace('/\{\{(.+?)\}\}/s','\1',$this->fw->compile($str)));
if (preg_match('/^(.+)(?<!\|)\|((?:\h*\w+(?:\h*[,;]?))+)$/s',
$str,$parts)) {
$str=trim($parts[1]);
foreach ($this->fw->split(trim($parts[2],"\xC2\xA0")) as $func)
$str=((empty($this->filter[$cmd=$func]) &&
function_exists($cmd)) ||
is_string($cmd=$this->filter($func)))?
$cmd.'('.$str.')':
'Base::instance()->'.
'call($this->filter(\''.$func.'\'),['.$str.'])';
}
return $str;
}
/**
* Register or get (one specific or all) token filters
* @param string $key
* @param string|closure $func
* @return array|closure|string
*/
function filter($key=NULL,$func=NULL) {
if (!$key)
return array_keys($this->filter);
$key=strtolower($key);
if (!$func)
return $this->filter[$key];
$this->filter[$key]=$func;
}
/**
* Assemble markup
* @return string
* @param $node string
**/
protected function build($node) {
return preg_replace_callback(
'/\{~(.+?)~\}|\{\*(.+?)\*\}|\{\-(.+?)\-\}|'.
'\{\{(.+?)\}\}((\r?\n)*)/s',
function($expr) {
if ($expr[1])
$str='<?php '.$this->token($expr[1]).' ?>';
elseif ($expr[2])
return '';
elseif ($expr[3])
$str=$expr[3];
else {
$str='<?= ('.trim($this->token($expr[4])).')'.
($this->interpolation?
(!empty($expr[6])?'."'.$expr[6].'"':''):'').' ?>';
if (isset($expr[5]))
$str.=$expr[5];
}
return $str;
},
$node
);
}
/**
* Render template string
* @return string
* @param $node string|array
* @param $hive array
* @param $ttl int
* @param $persist bool
* @param $escape bool
**/
function resolve($node,?array $hive=NULL,$ttl=0,$persist=FALSE,$escape=NULL) {
$hash=null;
$fw=$this->fw;
$cache=Cache::instance();
if ($escape!==NULL) {
$esc=$fw->ESCAPE;
$fw->ESCAPE=$escape;
}
if ($ttl || $persist)
$hash=$fw->hash($fw->serialize($node));
if ($ttl && $cache->exists($hash,$data))
return $data;
if ($persist) {
if (!is_dir($tmp=$fw->TEMP))
mkdir($tmp,Base::MODE,TRUE);
if (!is_file($this->file=($tmp.
$fw->SEED.'.'.$hash.'.php')))
$fw->write($this->file,$this->build($node));
if (isset($_COOKIE[session_name()]) &&
!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
$fw->sync('SESSION');
$data=$this->sandbox($hive);
}
else {
if (!$hive)
$hive=$fw->hive();
if ($fw->ESCAPE)
$hive=$this->esc($hive);
extract($hive);
unset($hive);
ob_start();
eval(' ?>'.$this->build($node).'<?php ');
$data=ob_get_clean();
}
if ($ttl)
$cache->set($hash,$data,$ttl);
if ($escape!==NULL)
$fw->ESCAPE=$esc;
return $data;
}
/**
* Parse template string
* @return string
* @param $text string
**/
function parse($text) {
// Remove PHP code and comments
return preg_replace(
'/\h*<\?(?!xml)(?:php|\s*=)?.+?\?>\h*|'.
'\{\*.+?\*\}/is','', $text);
}
/**
* Render template
* @return string
* @param $file string
* @param $mime string
* @param $hive array
* @param $ttl int
**/
function render($file,$mime='text/html',?array $hive=NULL,$ttl=0) {
$fw=$this->fw;
$cache=Cache::instance();
if (!is_dir($tmp=$fw->TEMP))
mkdir($tmp,Base::MODE,TRUE);
foreach ($fw->split($fw->UI) as $dir) {
if ($cache->exists($hash=$fw->hash($dir.$file),$data))
return $data;
if (is_file($view=$fw->fixslashes($dir.$file))) {
if (!is_file($this->file=($tmp.
$fw->SEED.'.'.$fw->hash($view).'.php')) ||
filemtime($this->file)<filemtime($view)) {
$contents=$fw->read($view);
if (isset($this->trigger['beforerender']))
foreach ($this->trigger['beforerender'] as $func)
$contents=$fw->call($func, [$contents, $view]);
$text=$this->parse($contents);
$fw->write($this->file,$this->build($text));
}
if (isset($_COOKIE[session_name()]) &&
!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
$fw->sync('SESSION');
$data=$this->sandbox($hive,$mime);
if(isset($this->trigger['afterrender']))
foreach ($this->trigger['afterrender'] as $func)
$data=$fw->call($func, [$data, $view]);
if ($ttl)
$cache->set($hash,$data,$ttl);
return $data;
}
}
throw new \Exception(sprintf(Base::E_Open,$file));
}
/**
* post rendering handler
* @param $func callback
*/
function beforerender($func) {
$this->trigger['beforerender'][]=$func;
}
}
//! ISO language/country codes
class ISO extends Prefab {
//@{ ISO 3166-1 country codes
const
CC_af='Afghanistan',
CC_ax='Åland Islands',
CC_al='Albania',
CC_dz='Algeria',
CC_as='American Samoa',
CC_ad='Andorra',
CC_ao='Angola',
CC_ai='Anguilla',
CC_aq='Antarctica',
CC_ag='Antigua and Barbuda',
CC_ar='Argentina',
CC_am='Armenia',
CC_aw='Aruba',
CC_au='Australia',
CC_at='Austria',
CC_az='Azerbaijan',
CC_bs='Bahamas',
CC_bh='Bahrain',
CC_bd='Bangladesh',
CC_bb='Barbados',
CC_by='Belarus',
CC_be='Belgium',
CC_bz='Belize',
CC_bj='Benin',
CC_bm='Bermuda',
CC_bt='Bhutan',
CC_bo='Bolivia',
CC_bq='Bonaire, Sint Eustatius and Saba',
CC_ba='Bosnia and Herzegovina',
CC_bw='Botswana',
CC_bv='Bouvet Island',
CC_br='Brazil',
CC_io='British Indian Ocean Territory',
CC_bn='Brunei Darussalam',
CC_bg='Bulgaria',
CC_bf='Burkina Faso',
CC_bi='Burundi',
CC_kh='Cambodia',
CC_cm='Cameroon',
CC_ca='Canada',
CC_cv='Cape Verde',
CC_ky='Cayman Islands',
CC_cf='Central African Republic',
CC_td='Chad',
CC_cl='Chile',
CC_cn='China',
CC_cx='Christmas Island',
CC_cc='Cocos (Keeling) Islands',
CC_co='Colombia',
CC_km='Comoros',
CC_cg='Congo',
CC_cd='Congo, The Democratic Republic of',
CC_ck='Cook Islands',
CC_cr='Costa Rica',
CC_ci='Côte d\'ivoire',
CC_hr='Croatia',
CC_cu='Cuba',
CC_cw='Curaçao',
CC_cy='Cyprus',
CC_cz='Czech Republic',
CC_dk='Denmark',
CC_dj='Djibouti',
CC_dm='Dominica',
CC_do='Dominican Republic',
CC_ec='Ecuador',
CC_eg='Egypt',
CC_sv='El Salvador',
CC_gq='Equatorial Guinea',
CC_er='Eritrea',
CC_ee='Estonia',
CC_et='Ethiopia',
CC_fk='Falkland Islands (Malvinas)',
CC_fo='Faroe Islands',
CC_fj='Fiji',
CC_fi='Finland',
CC_fr='France',
CC_gf='French Guiana',
CC_pf='French Polynesia',
CC_tf='French Southern Territories',
CC_ga='Gabon',
CC_gm='Gambia',
CC_ge='Georgia',
CC_de='Germany',
CC_gh='Ghana',
CC_gi='Gibraltar',
CC_gr='Greece',
CC_gl='Greenland',
CC_gd='Grenada',
CC_gp='Guadeloupe',
CC_gu='Guam',
CC_gt='Guatemala',
CC_gg='Guernsey',
CC_gn='Guinea',
CC_gw='Guinea-Bissau',
CC_gy='Guyana',
CC_ht='Haiti',
CC_hm='Heard Island and McDonald Islands',
CC_va='Holy See (Vatican City State)',
CC_hn='Honduras',
CC_hk='Hong Kong',
CC_hu='Hungary',
CC_is='Iceland',
CC_in='India',
CC_id='Indonesia',
CC_ir='Iran, Islamic Republic of',
CC_iq='Iraq',
CC_ie='Ireland',
CC_im='Isle of Man',
CC_il='Israel',
CC_it='Italy',
CC_jm='Jamaica',
CC_jp='Japan',
CC_je='Jersey',
CC_jo='Jordan',
CC_kz='Kazakhstan',
CC_ke='Kenya',
CC_ki='Kiribati',
CC_kp='Korea, Democratic People\'s Republic of',
CC_kr='Korea, Republic of',
CC_kw='Kuwait',
CC_kg='Kyrgyzstan',
CC_la='Lao People\'s Democratic Republic',
CC_lv='Latvia',
CC_lb='Lebanon',
CC_ls='Lesotho',
CC_lr='Liberia',
CC_ly='Libya',
CC_li='Liechtenstein',
CC_lt='Lithuania',
CC_lu='Luxembourg',
CC_mo='Macao',
CC_mk='Macedonia, The Former Yugoslav Republic of',
CC_mg='Madagascar',
CC_mw='Malawi',
CC_my='Malaysia',
CC_mv='Maldives',
CC_ml='Mali',
CC_mt='Malta',
CC_mh='Marshall Islands',
CC_mq='Martinique',
CC_mr='Mauritania',
CC_mu='Mauritius',
CC_yt='Mayotte',
CC_mx='Mexico',
CC_fm='Micronesia, Federated States of',
CC_md='Moldova, Republic of',
CC_mc='Monaco',
CC_mn='Mongolia',
CC_me='Montenegro',
CC_ms='Montserrat',
CC_ma='Morocco',
CC_mz='Mozambique',
CC_mm='Myanmar',
CC_na='Namibia',
CC_nr='Nauru',
CC_np='Nepal',
CC_nl='Netherlands',
CC_nc='New Caledonia',
CC_nz='New Zealand',
CC_ni='Nicaragua',
CC_ne='Niger',
CC_ng='Nigeria',
CC_nu='Niue',
CC_nf='Norfolk Island',
CC_mp='Northern Mariana Islands',
CC_no='Norway',
CC_om='Oman',
CC_pk='Pakistan',
CC_pw='Palau',
CC_ps='Palestinian Territory, Occupied',
CC_pa='Panama',
CC_pg='Papua New Guinea',
CC_py='Paraguay',
CC_pe='Peru',
CC_ph='Philippines',
CC_pn='Pitcairn',
CC_pl='Poland',
CC_pt='Portugal',
CC_pr='Puerto Rico',
CC_qa='Qatar',
CC_re='Réunion',
CC_ro='Romania',
CC_ru='Russian Federation',
CC_rw='Rwanda',
CC_bl='Saint Barthélemy',
CC_sh='Saint Helena, Ascension and Tristan da Cunha',
CC_kn='Saint Kitts and Nevis',
CC_lc='Saint Lucia',
CC_mf='Saint Martin (French Part)',
CC_pm='Saint Pierre and Miquelon',
CC_vc='Saint Vincent and The Grenadines',
CC_ws='Samoa',
CC_sm='San Marino',
CC_st='Sao Tome and Principe',
CC_sa='Saudi Arabia',
CC_sn='Senegal',
CC_rs='Serbia',
CC_sc='Seychelles',
CC_sl='Sierra Leone',
CC_sg='Singapore',
CC_sk='Slovakia',
CC_sx='Sint Maarten (Dutch Part)',
CC_si='Slovenia',
CC_sb='Solomon Islands',
CC_so='Somalia',
CC_za='South Africa',
CC_gs='South Georgia and The South Sandwich Islands',
CC_ss='South Sudan',
CC_es='Spain',
CC_lk='Sri Lanka',
CC_sd='Sudan',
CC_sr='Suriname',
CC_sj='Svalbard and Jan Mayen',
CC_sz='Swaziland',
CC_se='Sweden',
CC_ch='Switzerland',
CC_sy='Syrian Arab Republic',
CC_tw='Taiwan, Province of China',
CC_tj='Tajikistan',
CC_tz='Tanzania, United Republic of',
CC_th='Thailand',
CC_tl='Timor-Leste',
CC_tg='Togo',
CC_tk='Tokelau',
CC_to='Tonga',
CC_tt='Trinidad and Tobago',
CC_tn='Tunisia',
CC_tr='Turkey',
CC_tm='Turkmenistan',
CC_tc='Turks and Caicos Islands',
CC_tv='Tuvalu',
CC_ug='Uganda',
CC_ua='Ukraine',
CC_ae='United Arab Emirates',
CC_gb='United Kingdom',
CC_us='United States',
CC_um='United States Minor Outlying Islands',
CC_uy='Uruguay',
CC_uz='Uzbekistan',
CC_vu='Vanuatu',
CC_ve='Venezuela',
CC_vn='Viet Nam',
CC_vg='Virgin Islands, British',
CC_vi='Virgin Islands, U.S.',
CC_wf='Wallis and Futuna',
CC_eh='Western Sahara',
CC_ye='Yemen',
CC_zm='Zambia',
CC_zw='Zimbabwe';
//@}
//@{ ISO 639-1 language codes (Windows-compatibility subset)
const
LC_af='Afrikaans',
LC_am='Amharic',
LC_ar='Arabic',
LC_as='Assamese',
LC_ba='Bashkir',
LC_be='Belarusian',
LC_bg='Bulgarian',
LC_bn='Bengali',
LC_bo='Tibetan',
LC_br='Breton',
LC_ca='Catalan',
LC_co='Corsican',
LC_cs='Czech',
LC_cy='Welsh',
LC_da='Danish',
LC_de='German',
LC_dv='Divehi',
LC_el='Greek',
LC_en='English',
LC_es='Spanish',
LC_et='Estonian',
LC_eu='Basque',
LC_fa='Persian',
LC_fi='Finnish',
LC_fo='Faroese',
LC_fr='French',
LC_gd='Scottish Gaelic',
LC_gl='Galician',
LC_gu='Gujarati',
LC_he='Hebrew',
LC_hi='Hindi',
LC_hr='Croatian',
LC_hu='Hungarian',
LC_hy='Armenian',
LC_id='Indonesian',
LC_ig='Igbo',
LC_is='Icelandic',
LC_it='Italian',
LC_j
gitextract_46rrm02n/ ├── .github/ │ └── FUNDING.yml ├── CHANGELOG.md ├── COPYING ├── README.md ├── audit.php ├── auth.php ├── base.php ├── basket.php ├── bcrypt.php ├── cli/ │ └── ws.php ├── code.css ├── composer.json ├── db/ │ ├── cursor.php │ ├── jig/ │ │ ├── mapper.php │ │ └── session.php │ ├── jig.php │ ├── mongo/ │ │ ├── mapper.php │ │ └── session.php │ ├── mongo.php │ ├── sql/ │ │ ├── mapper.php │ │ └── session.php │ └── sql.php ├── f3.php ├── image.php ├── log.php ├── magic.php ├── markdown.php ├── matrix.php ├── session.php ├── sessionadapter.php ├── smtp.php ├── template.php ├── test.php ├── utf.php ├── web/ │ ├── geo.php │ ├── google/ │ │ ├── recaptcha.php │ │ └── staticmap.php │ ├── oauth2.php │ ├── openid.php │ └── pingback.php └── web.php
SYMBOL INDEX (597 symbols across 35 files)
FILE: audit.php
class Audit (line 24) | class Audit extends Prefab {
method url (line 39) | function url($str) {
method email (line 51) | function email($str,$mx=TRUE) {
method ipv4 (line 62) | function ipv4($addr) {
method ipv6 (line 71) | function ipv6($addr) {
method isprivate (line 80) | function isprivate($addr) {
method isreserved (line 90) | function isreserved($addr) {
method ispublic (line 100) | function ispublic($addr) {
method isdesktop (line 111) | function isdesktop($agent=NULL) {
method ismobile (line 123) | function ismobile($agent=NULL) {
method isbot (line 134) | function isbot($agent=NULL) {
method isai (line 145) | function isai($agent=NULL) {
method isbotorai (line 157) | function isbotorai($agent=NULL) {
method mod10 (line 166) | function mod10($id) {
method card (line 181) | function card($id) {
method entropy (line 206) | function entropy($str) {
method mac (line 219) | function mac($addr) {
FILE: auth.php
class Auth (line 24) | class Auth {
method _jig (line 49) | protected function _jig($id,$pw,$realm) {
method _mongo (line 79) | protected function _mongo($id,$pw,$realm) {
method _sql (line 99) | protected function _sql($id,$pw,$realm) {
method _ldap (line 128) | protected function _ldap($id,$pw) {
method _smtp (line 160) | protected function _smtp($id,$pw) {
method login (line 208) | function login($id,$pw,$realm=NULL) {
method basic (line 217) | function basic($func=NULL) {
method __construct (line 250) | function __construct($storage,?array $args=NULL,$func=NULL) {
FILE: base.php
class Prefab (line 24) | abstract class Prefab {
method instance (line 30) | static function instance() {
class Base (line 117) | final class Base extends Prefab implements ArrayAccess {
method sync (line 225) | function sync($key) {
method cut (line 234) | private function cut($key) {
method build (line 246) | function build($url, $args=[], $addParams=TRUE) {
method parse (line 281) | function parse($str) {
method cast (line 301) | function cast($val) {
method compile (line 318) | function compile($str, $evaluate=TRUE) {
method ref (line 380) | function &ref($key,$add=TRUE,&$var=NULL) {
method exists (line 431) | function exists($key,&$val=NULL) {
method devoid (line 444) | function devoid($key,&$val=NULL) {
method set (line 458) | function set($key,$val,$ttl=0) {
method get (line 546) | function get($key,$args=NULL) {
method clear (line 564) | function clear($key) {
method checked (line 623) | function checked($key) {
method visible (line 634) | function visible($obj,$key) {
method mset (line 650) | function mset(array $vars,$prefix='',$ttl=0) {
method hive (line 659) | function hive() {
method copy (line 669) | function copy($src,$dst) {
method concat (line 680) | function concat($key,$val) {
method flip (line 692) | function flip($key) {
method push (line 703) | function push($key,$val) {
method pop (line 714) | function pop($key) {
method unshift (line 725) | function unshift($key,$val) {
method shift (line 736) | function shift($key) {
method merge (line 748) | function merge($key,$src,$keep=FALSE) {
method extend (line 765) | function extend($key,$src,$keep=FALSE) {
method pull (line 781) | function pull($key): mixed
method fixslashes (line 793) | function fixslashes($str) {
method split (line 803) | function split($str,$noempty=TRUE) {
method stringify (line 814) | function stringify($arg,?array $stack=NULL) {
method csv (line 850) | function csv(array $args) {
method camelcase (line 860) | function camelcase($str) {
method snakecase (line 875) | function snakecase($str) {
method sign (line 885) | function sign($num) {
method extract (line 895) | function extract($arr,$prefix) {
method constants (line 909) | function constants($class,$prefix='') {
method hash (line 919) | function hash($str) {
method base64 (line 930) | function base64($data,$mime) {
method encode (line 939) | function encode($str) {
method decode (line 949) | function decode($str) {
method recursive (line 960) | function recursive($arg,$func,$stack=[]) {
method clean (line 999) | function clean($arg,$tags=NULL) {
method scrub (line 1017) | function scrub(&$var,$tags=NULL) {
method format (line 1025) | function format() {
method export (line 1201) | function export($expr) {
method language (line 1210) | function language($code) {
method lexicon (line 1252) | function lexicon($path,$ttl=0) {
method serialize (line 1297) | function serialize($arg) {
method unserialize (line 1311) | function unserialize($arg) {
method status (line 1325) | function status($code) {
method expire (line 1336) | function expire($secs=0) {
method agent (line 1364) | function agent() {
method ajax (line 1378) | function ajax() {
method ip (line 1388) | function ip() {
method trace (line 1404) | function trace(?array $trace=NULL,$format=TRUE) {
method error (line 1452) | function error($code,$text='',?array $trace=NULL,$level=0) {
method mock (line 1530) | function mock($pattern,
method alias (line 1578) | function alias($name,$params=[],$query=NULL,$fragment=NULL) {
method route (line 1597) | function route($pattern,$handler,$ttl=0,$kbps=0) {
method reroute (line 1635) | function reroute($url=NULL,$permanent=FALSE,$die=TRUE) {
method map (line 1676) | function map($url,$class,$ttl=0,$kbps=0) {
method redirect (line 1696) | function redirect($pattern,$url,$permanent=TRUE) {
method blacklisted (line 1712) | function blacklisted($ip) {
method mask (line 1736) | function mask($pattern,$url=NULL) {
method run (line 1772) | function run() {
method until (line 1946) | function until($func,$args=NULL,$timeout=60) {
method abort (line 1983) | function abort() {
method grab (line 2006) | function grab($func,$args=NULL) {
method call (line 2048) | function call($func,$args=NULL,$hooks='') {
method chain (line 2099) | function chain($funcs,$args=NULL) {
method relay (line 2113) | function relay($funcs,$args=NULL) {
method config (line 2126) | function config($source,$allow=FALSE) {
method mutex (line 2227) | function mutex($id,$func,$args=NULL) {
method read (line 2252) | function read($file, $lf = FALSE)
method write (line 2270) | function write($file,$data,$append=FALSE) {
method highlight (line 2279) | function highlight($text) {
method dump (line 2305) | function dump($expr) {
method rel (line 2314) | function rel($url) {
method autoload (line 2324) | protected function autoload($class) {
method unload (line 2343) | function unload($cwd) {
method offsetexists (line 2364) | #[\ReturnTypeWillChange]
method offsetset (line 2375) | #[\ReturnTypeWillChange]
method offsetget (line 2385) | #[\ReturnTypeWillChange]
method offsetunset (line 2395) | #[\ReturnTypeWillChange]
method __isset (line 2405) | function __isset($key) {
method __set (line 2415) | function __set($key,$val) {
method __get (line 2424) | function &__get($key) {
method __unset (line 2433) | function __unset($key) {
method __call (line 2443) | function __call($key,array $args) {
method __clone (line 2450) | private function __clone() {
method __construct (line 2454) | function __construct() {
class Cache (line 2703) | class Cache extends Prefab {
method exists (line 2719) | function exists($key,&$val=NULL) {
method set (line 2767) | function set($key,$val,$ttl=0) {
method get (line 2802) | function get($key) {
method clear (line 2811) | function clear($key) {
method reset (line 2841) | function reset($suffix=NULL) {
method load (line 2916) | function load($dsn,$seed=NULL) {
method __construct (line 2966) | function __construct($dsn=FALSE) {
class View (line 2974) | class View extends Prefab {
method __construct (line 2991) | function __construct() {
method esc (line 3000) | function esc($arg) {
method raw (line 3013) | function raw($arg) {
method sandbox (line 3027) | protected function sandbox(?array $hive=NULL,$mime=NULL) {
method render (line 3064) | function render($file,$mime='text/html',?array $hive=NULL,$ttl=0) {
method afterrender (line 3091) | function afterrender($func) {
class Preview (line 3098) | class Preview extends View {
method interpolation (line 3120) | function interpolation($bool) {
method c (line 3129) | function c($val) {
method token (line 3142) | function token($str) {
method filter (line 3164) | function filter($key=NULL,$func=NULL) {
method build (line 3178) | protected function build($node) {
method resolve (line 3211) | function resolve($node,?array $hive=NULL,$ttl=0,$persist=FALSE,$escape...
method parse (line 3258) | function parse($text) {
method render (line 3273) | function render($file,$mime='text/html',?array $hive=NULL,$ttl=0) {
method beforerender (line 3312) | function beforerender($func) {
class ISO (line 3319) | class ISO extends Prefab {
method languages (line 3665) | function languages() {
method countries (line 3673) | function countries() {
class Registry (line 3680) | final class Registry {
method exists (line 3691) | static function exists($key) {
method set (line 3701) | static function set($key,$obj) {
method get (line 3710) | static function get($key) {
method clear (line 3718) | static function clear($key) {
method __clone (line 3724) | private function __clone() {
method __construct (line 3728) | private function __construct() {
FILE: basket.php
class Basket (line 24) | class Basket extends Magic {
method exists (line 44) | function exists($key) {
method set (line 54) | function set($key,$val) {
method get (line 63) | function &get($key) {
method clear (line 76) | function clear($key) {
method find (line 87) | function find($key=NULL,$val=NULL) {
method findone (line 109) | function findone($key,$val) {
method load (line 119) | function load($key,$val) {
method dry (line 132) | function dry() {
method count (line 140) | function count() {
method save (line 148) | function save() {
method erase (line 161) | function erase($key,$val) {
method reset (line 176) | function reset() {
method drop (line 185) | function drop() {
method copyfrom (line 194) | function copyfrom($var) {
method copyto (line 206) | function copyto($key) {
method checkout (line 216) | function checkout() {
method __construct (line 230) | function __construct($key='basket') {
FILE: bcrypt.php
class Bcrypt (line 26) | class Bcrypt extends Prefab {
method hash (line 45) | function hash($pw,$salt=NULL,$cost=self::COST) {
method needs_rehash (line 74) | function needs_rehash($hash,$cost=self::COST) {
method verify (line 85) | function verify($pw,$hash) {
FILE: cli/ws.php
class WS (line 26) | class WS {
method alloc (line 64) | function alloc($socket) {
method close (line 130) | function close($socket) {
method read (line 143) | function read($socket,$len=0) {
method write (line 162) | function write($socket,$buf) {
method agents (line 181) | function agents($uri=NULL) {
method events (line 198) | function events() {
method on (line 208) | function on($event,$func) {
method kill (line 216) | function kill() {
method run (line 223) | function run() {
method __construct (line 312) | function __construct($addr,$ctx=NULL,$wait=60) {
class Agent (line 322) | class Agent {
method server (line 337) | function server() {
method id (line 345) | function id() {
method socket (line 353) | function socket() {
method verb (line 361) | function verb() {
method uri (line 369) | function uri() {
method headers (line 377) | function headers() {
method send (line 387) | function send($op,$data='') {
method fetch (line 412) | function fetch() {
method __destruct (line 461) | function __destruct() {
method __construct (line 474) | function __construct($server,$socket,$verb,$uri,array $hdrs) {
FILE: db/cursor.php
class Cursor (line 26) | abstract class Cursor extends \Magic implements \IteratorAggregate {
method dbtype (line 45) | abstract function dbtype();
method fields (line 51) | abstract function fields();
method cast (line 58) | abstract function cast($obj=NULL);
method find (line 67) | abstract function find($filter=NULL,?array $options=NULL,$ttl=0);
method count (line 76) | abstract function count($filter=NULL,?array $options=NULL,$ttl=0);
method insert (line 82) | abstract function insert();
method update (line 88) | abstract function update();
method copyfrom (line 96) | abstract function copyfrom($var,$func=NULL);
method copyto (line 103) | abstract function copyto($key);
method getiterator (line 110) | #[\ReturnTypeWillChange]
method dry (line 118) | function dry() {
method findone (line 129) | function findone($filter=NULL,?array $options=NULL,$ttl=0) {
method paginate (line 149) | function paginate(
method load (line 177) | function load($filter=NULL,?array $options=NULL,$ttl=0) {
method loaded (line 187) | function loaded() {
method first (line 195) | function first() {
method last (line 203) | function last() {
method skip (line 212) | function skip($ofs=1) {
method next (line 222) | function next() {
method prev (line 230) | function prev() {
method valid (line 237) | function valid() {
method save (line 245) | function save() {
method erase (line 253) | function erase() {
method onload (line 264) | function onload($func) {
method beforeinsert (line 273) | function beforeinsert($func) {
method afterinsert (line 282) | function afterinsert($func) {
method oninsert (line 291) | function oninsert($func) {
method beforeupdate (line 300) | function beforeupdate($func) {
method afterupdate (line 309) | function afterupdate($func) {
method onupdate (line 318) | function onupdate($func) {
method beforesave (line 327) | function beforesave($func) {
method aftersave (line 338) | function aftersave($func) {
method onsave (line 349) | function onsave($func) {
method beforeerase (line 358) | function beforeerase($func) {
method aftererase (line 367) | function aftererase($func) {
method onerase (line 376) | function onerase($func) {
method reset (line 384) | function reset() {
FILE: db/jig.php
class Jig (line 26) | class Jig {
method read (line 53) | function &read($file) {
method write (line 81) | function write($file,?array $data=NULL) {
method dir (line 103) | function dir() {
method uuid (line 111) | function uuid() {
method log (line 120) | function log($flag=TRUE) {
method jot (line 131) | function jot($frame) {
method drop (line 140) | function drop() {
method __clone (line 151) | private function __clone() {
method __construct (line 159) | function __construct($dir=NULL,$format=self::FORMAT_JSON,$lazy=FALSE) {
method __destruct (line 170) | function __destruct() {
FILE: db/jig/mapper.php
class Mapper (line 26) | class Mapper extends \DB\Cursor {
method dbtype (line 44) | function dbtype() {
method exists (line 53) | function exists($key) {
method set (line 63) | function set($key,$val) {
method get (line 72) | function &get($key) {
method clear (line 85) | function clear($key) {
method factory (line 96) | function factory($id,$row) {
method cast (line 113) | function cast($obj=NULL) {
method token (line 124) | function token($str) {
method find (line 159) | function find($filter=NULL,?array $options=NULL,$ttl=0,$log=TRUE) {
method sort (line 312) | protected function sort($data,$cond) {
method reduce (line 344) | function reduce($key,$handler,$finalize=null){
method count (line 355) | function count($filter=NULL,?array $options=NULL,$ttl=0) {
method skip (line 369) | function skip($ofs=1) {
method insert (line 381) | function insert() {
method update (line 411) | function update() {
method erase (line 435) | function erase($filter=NULL,$quick=FALSE) {
method reset (line 481) | function reset() {
method copyfrom (line 493) | function copyfrom($var,$func=NULL) {
method copyto (line 507) | function copyto($key) {
method fields (line 517) | function fields() {
method getiterator (line 525) | function getiterator() {
method __construct (line 535) | function __construct(\DB\Jig $db,$file) {
FILE: db/jig/session.php
class Session (line 29) | class Session extends Mapper {
method open (line 49) | function open(string $path, string $name): bool
method close (line 58) | function close(): bool
method read (line 70) | #[ReturnTypeWillChange]
method write (line 97) | function write(string $id, string $data): bool
method destroy (line 113) | function destroy($id): bool
method gc (line 122) | #[ReturnTypeWillChange]
method sid (line 132) | function sid() {
method csrf (line 140) | function csrf() {
method ip (line 148) | function ip() {
method stamp (line 156) | function stamp() {
method agent (line 166) | function agent() {
method __construct (line 177) | function __construct(\DB\Jig $db,$file='sessions',$onsuspect=NULL,$key...
FILE: db/mongo.php
class Mongo (line 26) | class Mongo {
method dsn (line 49) | function dsn() {
method uuid (line 57) | function uuid() {
method log (line 66) | function log($flag=TRUE) {
method drop (line 94) | function drop() {
method __call (line 111) | function __call($func,array $args) {
method legacy (line 119) | function legacy() {
method __clone (line 124) | private function __clone() {
method __construct (line 133) | function __construct($dsn,$dbname,?array $options=NULL) {
FILE: db/mongo/mapper.php
class Mapper (line 26) | class Mapper extends \DB\Cursor {
method dbtype (line 46) | function dbtype() {
method exists (line 55) | function exists($key) {
method set (line 65) | function set($key,$val) {
method get (line 74) | function &get($key) {
method clear (line 85) | function clear($key) {
method factory (line 94) | function factory($row) {
method cast (line 110) | function cast($obj=NULL) {
method select (line 124) | function select($fields=NULL,$filter=NULL,?array $options=NULL,$ttl=0) {
method find (line 202) | function find($filter=NULL,?array $options=NULL,$ttl=0) {
method count (line 221) | function count($filter=NULL,?array $options=NULL,$ttl=0) {
method skip (line 244) | function skip($ofs=1) {
method insert (line 255) | function insert() {
method update (line 281) | function update() {
method erase (line 304) | function erase($filter=NULL,$quick=TRUE) {
method reset (line 335) | function reset() {
method copyfrom (line 346) | function copyfrom($var,$func=NULL) {
method copyto (line 360) | function copyto($key) {
method fields (line 370) | function fields() {
method cursor (line 378) | function cursor() {
method getiterator (line 386) | function getiterator() {
method __construct (line 397) | function __construct(\DB\Mongo $db,$collection,$fields=NULL) {
FILE: db/mongo/session.php
class Session (line 29) | class Session extends Mapper {
method open (line 49) | function open(string $path, string $name): bool
method close (line 58) | function close(): bool
method read (line 70) | #[ReturnTypeWillChange]
method write (line 97) | function write(string $id, string $data): bool
method destroy (line 113) | function destroy($id): bool
method gc (line 122) | #[ReturnTypeWillChange]
method sid (line 132) | function sid() {
method csrf (line 140) | function csrf() {
method ip (line 148) | function ip() {
method stamp (line 156) | function stamp() {
method agent (line 166) | function agent() {
method __construct (line 177) | function __construct(\DB\Mongo $db,$table='sessions',$onsuspect=NULL,$...
FILE: db/sql.php
class SQL (line 26) | class SQL {
method begin (line 58) | function begin() {
method rollback (line 68) | function rollback() {
method commit (line 80) | function commit() {
method trans (line 92) | function trans() {
method type (line 101) | function type($val) {
method value (line 124) | function value($type,$val) {
method exec (line 151) | function exec($cmds,$args=NULL,$ttl=0,$log=TRUE,$stamp=FALSE) {
method count (line 280) | function count() {
method log (line 289) | function log($flag=TRUE) {
method exists (line 300) | function exists($table) {
method schema (line 316) | function schema($table,$fields=NULL,$ttl=0) {
method quote (line 446) | function quote($val,$type=\PDO::PARAM_STR) {
method uuid (line 458) | function uuid() {
method pdo (line 466) | function pdo() {
method driver (line 474) | function driver() {
method version (line 482) | function version() {
method name (line 490) | function name() {
method quotekey (line 500) | function quotekey($key, $split=TRUE) {
method __call (line 522) | function __call($func,array $args) {
method __clone (line 527) | private function __clone() {
method __construct (line 537) | function __construct($dsn,$user=NULL,$pw=NULL,?array $options=NULL) {
FILE: db/sql/mapper.php
class Mapper (line 26) | class Mapper extends \DB\Cursor {
method dbtype (line 57) | function dbtype() {
method table (line 65) | function table() {
method changed (line 74) | function changed($key=NULL) {
method exists (line 88) | function exists($key) {
method set (line 98) | function set($key,$val) {
method get (line 123) | function &get($key) {
method clear (line 140) | function clear($key) {
method __call (line 154) | function __call($func,$args) {
method factory (line 164) | function factory($row) {
method cast (line 190) | function cast($obj=NULL) {
method stringify (line 208) | function stringify($fields,$filter=NULL,?array $options=NULL) {
method select (line 306) | function select($fields,$filter=NULL,?array $options=NULL,$ttl=0) {
method find (line 332) | function find($filter=NULL,?array $options=NULL,$ttl=0) {
method count (line 358) | function count($filter=NULL,?array $options=NULL,$ttl=0) {
method skip (line 396) | function skip($ofs=1) {
method insert (line 420) | function insert() {
method update (line 516) | function update() {
method updateAll (line 563) | function updateAll($filter=NULL) {
method erase (line 599) | function erase($filter=NULL,$quick=TRUE) {
method reset (line 659) | function reset() {
method copyfrom (line 681) | function copyfrom($var,$func=NULL) {
method copyto (line 696) | function copyto($key) {
method schema (line 707) | function schema($fields=null) {
method fields (line 718) | function fields($adhoc=TRUE) {
method required (line 727) | function required($field) {
method getiterator (line 736) | function getiterator() {
method alias (line 744) | function alias($alias) {
method __construct (line 756) | function __construct(\DB\SQL $db,$table,$fields=NULL,$ttl=60) {
FILE: db/sql/session.php
class Session (line 29) | class Session extends Mapper {
method open (line 49) | function open(string $path, string $name): bool
method close (line 58) | function close(): bool
method read (line 70) | #[ReturnTypeWillChange]
method write (line 96) | function write(string $id, string $data): bool
method destroy (line 112) | function destroy($id): bool
method gc (line 121) | #[ReturnTypeWillChange]
method sid (line 131) | function sid() {
method csrf (line 139) | function csrf() {
method ip (line 147) | function ip() {
method stamp (line 155) | function stamp() {
method agent (line 165) | function agent() {
method __construct (line 178) | function __construct(\DB\SQL $db,$table='sessions',$force=TRUE,$onsusp...
FILE: f3.php
class F3 (line 24) | class F3 {
method __callstatic (line 36) | static function __callstatic($func,array $args) {
FILE: image.php
class Image (line 24) | class Image {
method rgb (line 60) | function rgb($color) {
method invert (line 78) | function invert() {
method brightness (line 88) | function brightness($level) {
method contrast (line 98) | function contrast($level) {
method grayscale (line 107) | function grayscale() {
method smooth (line 117) | function smooth($level) {
method emboss (line 126) | function emboss() {
method sepia (line 135) | function sepia() {
method pixelate (line 146) | function pixelate($size) {
method blur (line 156) | function blur($selective=FALSE) {
method sketch (line 166) | function sketch() {
method hflip (line 175) | function hflip() {
method vflip (line 193) | function vflip() {
method crop (line 215) | function crop($x1,$y1,$x2,$y2) {
method resize (line 237) | function resize($width=NULL,$height=NULL,$crop=TRUE,$enlarge=TRUE) {
method rotate (line 290) | function rotate($angle) {
method overlay (line 304) | function overlay(Image $img,$align=NULL,$alpha=100) {
method identicon (line 352) | function identicon($str,$size=64,$blocks=4) {
method captcha (line 415) | function captcha($font,$size=24,$len=5,
method width (line 475) | function width() {
method height (line 483) | function height() {
method render (line 491) | function render() {
method dump (line 508) | function dump() {
method data (line 523) | function data() {
method save (line 531) | function save() {
method restore (line 549) | function restore($state=1) {
method undo (line 571) | function undo() {
method load (line 585) | function load($str) {
method __construct (line 599) | function __construct($file=NULL,$flag=FALSE,$path=NULL) {
method __destruct (line 618) | function __destruct() {
FILE: log.php
class Log (line 24) | class Log {
method write (line 36) | function write($text,$format='r') {
method erase (line 56) | function erase() {
method __construct (line 64) | function __construct($file) {
FILE: magic.php
class Magic (line 24) | abstract class Magic implements ArrayAccess {
method exists (line 31) | abstract function exists($key);
method set (line 39) | abstract function set($key,$val);
method get (line 46) | abstract function &get($key);
method clear (line 53) | abstract function clear($key);
method offsetexists (line 60) | #[\ReturnTypeWillChange]
method offsetset (line 73) | #[\ReturnTypeWillChange]
method offsetget (line 84) | #[\ReturnTypeWillChange]
method offsetunset (line 98) | #[\ReturnTypeWillChange]
method __isset (line 111) | function __isset($key) {
method __set (line 121) | function __set($key,$val) {
method __get (line 130) | function &__get($key) {
method __unset (line 139) | function __unset($key) {
FILE: markdown.php
class Markdown (line 24) | class Markdown extends Prefab {
method _blockquote (line 37) | protected function _blockquote($str) {
method _pre (line 48) | protected function _pre($str) {
method _fence (line 64) | protected function _fence($hint,$str) {
method _hr (line 184) | protected function _hr() {
method _atx (line 194) | protected function _atx($type,$str) {
method _setext (line 206) | protected function _setext($str,$type) {
method _li (line 217) | protected function _li($str) {
method _raw (line 277) | protected function _raw($str) {
method _p (line 286) | protected function _p($str) {
method _text (line 320) | protected function _text($str) {
method _img (line 346) | protected function _img($str) {
method _a (line 367) | protected function _a($str) {
method _auto (line 386) | protected function _auto($str) {
method _code (line 405) | protected function _code($str) {
method esc (line 421) | function esc($str) {
method snip (line 440) | protected function snip($str) {
method scan (line 449) | function scan($str) {
method build (line 461) | protected function build($str) {
method convert (line 555) | function convert($txt) {
FILE: matrix.php
class Matrix (line 24) | class Matrix extends Prefab {
method pick (line 33) | function pick(array $var,$col) {
method select (line 48) | function select($fields, $data) {
method walk (line 62) | function walk($fields, $data, $callback) {
method transpose (line 73) | function transpose(array &$var) {
method sort (line 88) | function sort(array &$var,$col,$order=SORT_ASC) {
method changekey (line 110) | function changekey(array &$var,$old,$new) {
method calendar (line 124) | function calendar($date='now',$first=0) {
FILE: session.php
class Session (line 24) | class Session extends Magic {
method open (line 48) | function open(string $path, string $name): bool
method close (line 57) | function close(): bool
method read (line 69) | #[ReturnTypeWillChange]
method write (line 93) | function write(string $id, string $data): bool
method destroy (line 112) | function destroy(string $id): bool
method gc (line 121) | #[ReturnTypeWillChange]
method sid (line 132) | function sid() {
method csrf (line 140) | function csrf() {
method ip (line 148) | function ip() {
method stamp (line 156) | function stamp() {
method agent (line 167) | function agent() {
method __construct (line 176) | function __construct($onsuspect=NULL,$key=NULL,$cache=null) {
method exists (line 211) | function exists($key) {
method get (line 220) | function &get($key) {
method set (line 224) | function set($key,$val) {
method clear (line 228) | function clear($key) {
FILE: sessionadapter.php
class SessionAdapter (line 6) | class SessionAdapter implements \SessionHandlerInterface
method __construct (line 10) | public function __construct($handler)
method close (line 15) | public function close(): bool
method destroy (line 20) | public function destroy(string $id): bool
method gc (line 25) | #[ReturnTypeWillChange]
method open (line 31) | public function open(string $path, string $name): bool
method read (line 36) | #[ReturnTypeWillChange]
method write (line 42) | public function write(string $id, string $data): bool
FILE: smtp.php
class SMTP (line 24) | class SMTP extends Magic {
method fixheader (line 61) | protected function fixheader($key) {
method exists (line 71) | function exists($key) {
method set (line 82) | function set($key,$val) {
method get (line 92) | function &get($key) {
method clear (line 106) | function clear($key) {
method log (line 115) | function log() {
method dialog (line 126) | protected function dialog($cmd=NULL,$log=TRUE,$mock=FALSE) {
method attach (line 173) | function attach($file,$alias=NULL,$cid=NULL) {
method send (line 188) | function send($message,$log=TRUE,$mock=FALSE) {
method __construct (line 348) | function __construct(
FILE: template.php
class Template (line 24) | class Template extends Preview {
method _set (line 42) | protected function _set(array $node) {
method _include (line 57) | protected function _include(array $node) {
method _exclude (line 87) | protected function _exclude() {
method _ignore (line 96) | protected function _ignore(array $node) {
method _loop (line 105) | protected function _loop(array $node) {
method _repeat (line 122) | protected function _repeat(array $node) {
method _check (line 144) | protected function _check(array $node) {
method _true (line 167) | protected function _true(array $node) {
method _false (line 176) | protected function _false(array $node) {
method _switch (line 185) | protected function _switch(array $node) {
method _case (line 202) | protected function _case(array $node) {
method _default (line 220) | protected function _default(array $node) {
method build (line 232) | function build($node) {
method extend (line 247) | function extend($tag,$func) {
method __call (line 258) | function __call($func,array $args) {
method parse (line 271) | function parse($text) {
method __construct (line 343) | function __construct() {
FILE: test.php
class Test (line 24) | class Test {
method results (line 45) | function results() {
method passed (line 53) | function passed() {
method expect (line 63) | function expect($cond,$text=NULL) {
method message (line 85) | function message($text) {
method __construct (line 94) | function __construct($level=self::FLAG_Both) {
FILE: utf.php
class UTF (line 24) | class UTF extends Prefab {
method strlen (line 31) | function strlen($str) {
method strrev (line 41) | function strrev($str) {
method stripos (line 53) | function stripos($stack,$needle,$ofs=0) {
method strpos (line 65) | function strpos($stack,$needle,$ofs=0,$case=FALSE) {
method stristr (line 79) | function stristr($stack,$needle,$before=FALSE) {
method strstr (line 92) | function strstr($stack,$needle,$before=FALSE,$case=FALSE) {
method substr (line 111) | function substr($str,$start,$len=0) {
method substr_count (line 126) | function substr_count($stack,$needle) {
method ltrim (line 137) | function ltrim($str) {
method rtrim (line 146) | function rtrim($str) {
method trim (line 155) | function trim($str) {
method bom (line 163) | function bom() {
method translate (line 172) | function translate($str) {
method emojify (line 182) | function emojify($str) {
FILE: web.php
class Web (line 24) | class Web extends Prefab {
method mime (line 41) | function mime($file, $inspect=FALSE) {
method acceptable (line 171) | function acceptable($list=NULL) {
method send (line 206) | function send($file,$mime=NULL,$kbps=0,$force=TRUE,$name=NULL,$flush=T...
method receive (line 256) | function receive($func=NULL,$overwrite=FALSE,$slug=TRUE) {
method progress (line 333) | function progress($id) {
method _curl (line 346) | protected function _curl($url,$options) {
method _stream (line 415) | protected function _stream($url,$options) {
method _socket (line 469) | protected function _socket($url,$options) {
method engine (line 564) | function engine($arg='curl') {
method subst (line 585) | function subst(array &$old,$new) {
method request (line 603) | function request($url,?array $options=NULL) {
method minify (line 695) | function minify($files,$mime=NULL,$header=TRUE,$path=NULL) {
method rss (line 842) | function rss($url,$max=10,$tags=NULL) {
method whois (line 877) | function whois($addr,$server='whois.internic.net') {
method diacritics (line 902) | function diacritics() {
method slug (line 962) | function slug($text, $separator = '-')
method filler (line 978) | function filler($count=1,$max=20,$std=TRUE) {
function gzdecode (line 1019) | function gzdecode($str) {
FILE: web/geo.php
class Geo (line 26) | class Geo extends \Prefab {
method tzinfo (line 33) | function tzinfo($zone) {
method location (line 54) | function location($ip=NULL) {
method weather (line 95) | function weather($latitude,$longitude,$key) {
FILE: web/google/recaptcha.php
class Recaptcha (line 26) | class Recaptcha {
method verify (line 38) | static function verify($secret,$response=NULL) {
FILE: web/google/staticmap.php
class StaticMap (line 26) | class StaticMap {
method __call (line 42) | function __call($func,array $args) {
method dump (line 51) | function dump() {
FILE: web/oauth2.php
class OAuth2 (line 26) | class OAuth2 extends \Magic {
method uri (line 40) | function uri($endpoint,$query=TRUE) {
method request (line 52) | function request($uri,$method,$token=NULL) {
method jwt (line 92) | function jwt($token) {
method setEncoding (line 105) | function setEncoding($type) {
method b64url (line 114) | function b64url($data) {
method exists (line 123) | function exists($key) {
method set (line 133) | function set($key,$val) {
method get (line 142) | function &get($key) {
method clear (line 155) | function clear($key=NULL) {
FILE: web/openid.php
class OpenID (line 26) | class OpenID extends \Magic {
method discover (line 39) | protected function discover($proxy) {
method auth (line 144) | function auth($proxy=NULL,$attr=[],?array $reqd=NULL) {
method verified (line 174) | function verified($proxy=NULL) {
method response (line 203) | function response() {
method exists (line 212) | function exists($key) {
method set (line 222) | function set($key,$val) {
method get (line 231) | function &get($key) {
method clear (line 244) | function clear($key) {
FILE: web/pingback.php
class Pingback (line 26) | class Pingback extends \Prefab {
method enabled (line 37) | protected function enabled($url) {
method inspect (line 64) | function inspect($source) {
method listen (line 110) | function listen($func,$path=NULL) {
method log (line 163) | function log() {
method __construct (line 171) | function __construct() {
Condensed preview — 41 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (483K chars).
[
{
"path": ".github/FUNDING.yml",
"chars": 37,
"preview": "github: ikkez\nbuy_me_a_coffee: ikkez\n"
},
{
"path": "CHANGELOG.md",
"chars": 59507,
"preview": "CHANGELOG\n\n3.9.2 (02.12.2025)\n---\nfeat, Audit: Added bot/AI detection, #401\nfix: php 8.5 compatibility\n\n3.9.1 (09.08.202"
},
{
"path": "COPYING",
"chars": 31824,
"preview": "GNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n"
},
{
"path": "README.md",
"chars": 707,
"preview": "# fatfree-core\nFat-Free Framework core library\n\n### Usage:\n\nFirst make sure to add a proper url rewrite configuration to"
},
{
"path": "audit.php",
"chars": 5880,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "auth.php",
"chars": 6741,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "base.php",
"chars": 96577,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2023 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "basket.php",
"chars": 4715,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "bcrypt.php",
"chars": 2494,
"preview": "<?php\n\n/**\n*\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n*\n*\tThis file is part of the Fat-Free "
},
{
"path": "cli/ws.php",
"chars": 10234,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "code.css",
"chars": 1406,
"preview": "code{word-wrap:break-word;color:black}.comment,.doc_comment,.ml_comment{color:dimgray;font-style:italic}.variable{color:"
},
{
"path": "composer.json",
"chars": 314,
"preview": "{\n\t\"name\": \"bcosca/fatfree-core\",\n\t\"description\": \"A powerful yet easy-to-use PHP micro-framework designed to help you b"
},
{
"path": "db/cursor.php",
"chars": 7751,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/jig/mapper.php",
"chars": 13171,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/jig/session.php",
"chars": 4413,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/jig.php",
"chars": 3718,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/mongo/mapper.php",
"chars": 9482,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/mongo/session.php",
"chars": 4432,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/mongo.php",
"chars": 3216,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/sql/mapper.php",
"chars": 20112,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/sql/session.php",
"chars": 5539,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "db/sql.php",
"chars": 14666,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "f3.php",
"chars": 1112,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "image.php",
"chars": 15850,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "log.php",
"chars": 1645,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "magic.php",
"chars": 2947,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "markdown.php",
"chars": 14044,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "matrix.php",
"chars": 3830,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "session.php",
"chars": 4765,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "sessionadapter.php",
"chars": 991,
"preview": "<?php\n\n/**\n * To be removed once the legacy session handlers are reworked when php 7 support is dropped\n */\nclass Sessio"
},
{
"path": "smtp.php",
"chars": 9510,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "template.php",
"chars": 8745,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "test.php",
"chars": 2074,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "utf.php",
"chars": 4722,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web/geo.php",
"chars": 3066,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web/google/recaptcha.php",
"chars": 1559,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web/google/staticmap.php",
"chars": 1570,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web/oauth2.php",
"chars": 3666,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web/openid.php",
"chars": 6831,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web/pingback.php",
"chars": 4943,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
},
{
"path": "web.php",
"chars": 31864,
"preview": "<?php\n\n/*\n\n\tCopyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.\n\n\tThis file is part of the Fat-Free Fra"
}
]
About this extraction
This page contains the full source code of the bcosca/fatfree-core GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 41 files (420.6 KB), approximately 131.9k tokens, and a symbol index with 597 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.